diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c244479 --- /dev/null +++ b/go.mod @@ -0,0 +1,81 @@ +module github.com/TeaWeb/code + +go 1.14 + +require ( + github.com/Azure/azure-sdk-for-go v44.2.0+incompatible + github.com/Azure/go-autorest/autorest v0.11.2 + github.com/Azure/go-autorest/autorest/adal v0.9.0 + github.com/Azure/go-autorest/autorest/azure/auth v0.5.0 + github.com/Azure/go-autorest/autorest/to v0.4.0 + github.com/Azure/go-autorest/autorest/validation v0.3.0 // indirect + github.com/BurntSushi/toml v0.3.1 + github.com/JamesClonk/vultr v2.0.1+incompatible + github.com/Microsoft/go-winio v0.4.14 + github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87 + github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect + github.com/TeaWeb/agent v0.0.0-20191129072344-6274ce47207a + github.com/TeaWeb/plugin v0.0.0-20190202040243-6fb957e0eb4a + github.com/TeaWeb/uaparser v0.0.0-20190526084055-a1c9449348d8 + github.com/akamai/AkamaiOPEN-edgegrid-golang v0.9.18 + github.com/aliyun/alibaba-cloud-sdk-go v1.61.370 + github.com/aws/aws-sdk-go v1.30.20 + github.com/cenkalti/backoff v2.2.1+incompatible + github.com/cloudflare/cloudflare-go v0.13.0 + github.com/cpu/goacmedns v0.0.3 + github.com/dchest/captcha v0.0.0-20170622155422-6a29415a8364 + github.com/dchest/siphash v1.2.1 + github.com/decker502/dnspod-go v0.2.0 + github.com/dnsimple/dnsimple-go v0.63.0 + github.com/exoscale/egoscale v0.28.0 + github.com/go-acme/lego v2.7.2+incompatible + github.com/go-ole/go-ole v1.2.4 // indirect + github.com/go-redis/redis v6.15.8+incompatible + github.com/go-sql-driver/mysql v1.5.0 + github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible + github.com/go-yaml/yaml v2.1.0+incompatible + github.com/gophercloud/gophercloud v0.12.0 + github.com/gorilla/websocket v1.4.2 + github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df + github.com/iwind/TeaGo v0.0.0-20200731084534-255664a0c121 + github.com/iwind/gofcgi v0.0.0-20181229122301-daea2786cb0d + github.com/jlaffaye/ftp v0.0.0-20200730135723-c2ee4fa2503b + github.com/labbsr0x/bindman-dns-webhook v1.0.2 + github.com/lib/pq v1.8.0 + github.com/linode/linodego v0.20.0 + github.com/luckygo666/lego/v3 v3.8.88 + github.com/mailru/easyjson v0.7.2 + github.com/miekg/dns v1.1.31 + github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04 + github.com/nrdcg/auroradns v1.0.1 + github.com/nrdcg/goinwx v0.7.0 + github.com/nrdcg/namesilo v0.2.1 // indirect + github.com/oracle/oci-go-sdk v22.0.0+incompatible + github.com/oschwald/geoip2-golang v1.4.0 + github.com/ovh/go-ovh v1.1.0 + github.com/pkg/sftp v1.11.0 + github.com/pquerna/ffjson v0.0.0-20190930134022-aa0246cd15f7 + github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2 + github.com/robertkrimen/otto v0.0.0-20191219234010-c382bd3c16ff + github.com/sacloud/libsacloud v1.36.1 + github.com/shirou/gopsutil v2.20.6+incompatible + github.com/stretchr/testify v1.6.1 + github.com/syndtr/goleveldb v1.0.0 + github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e + github.com/technoweenie/multipartstreamer v1.0.1 // indirect + github.com/timewasted/linode v0.0.0-20160829202747-37e84520dcf7 + github.com/transip/gotransip v5.8.2+incompatible + github.com/urfave/cli v1.22.4 + github.com/vmihailenco/msgpack v4.0.4+incompatible + github.com/vultr/govultr v0.4.2 // indirect + go.mongodb.org/mongo-driver v1.4.0 + golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de + golang.org/x/net v0.0.0-20200707034311-ab3426394381 + golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d + golang.org/x/sys v0.0.0-20200802091954-4b90ce9b60b3 + google.golang.org/api v0.29.0 + google.golang.org/appengine v1.6.6 // indirect + gopkg.in/ns1/ns1-go.v2 v2.4.1 + gopkg.in/sourcemap.v1 v1.0.5 // indirect + gopkg.in/square/go-jose.v2 v2.5.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..edbd77c --- /dev/null +++ b/go.sum @@ -0,0 +1,831 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.56.0 h1:WRz29PgAsVEyPSDHyk+0fpEkwEFyfhHn+JbksT6gIL4= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/Azure/azure-sdk-for-go v44.2.0+incompatible h1:d0WY8HTXhnurVBAkLXzv4bRpd+P5r3U/W17Z88PJWiI= +github.com/Azure/azure-sdk-for-go v44.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= +github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest v0.11.0/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= +github.com/Azure/go-autorest/autorest v0.11.2 h1:BR5GoSGobeiMwGOOIxXuvNKNPy+HMGdteKB8kJUDnBE= +github.com/Azure/go-autorest/autorest v0.11.2/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/adal v0.9.0 h1:SigMbuFNuKgc1xcGhaeapbh+8fgsu+GxgDRFyg7f5lM= +github.com/Azure/go-autorest/autorest/adal v0.9.0/go.mod h1:/c022QCutn2P7uY+/oQWWNcK9YU+MH96NgK+jErpbcg= +github.com/Azure/go-autorest/autorest/azure/auth v0.5.0 h1:nSMjYIe24eBYasAIxt859TxyXef/IqoH+8/g4+LmcVs= +github.com/Azure/go-autorest/autorest/azure/auth v0.5.0/go.mod h1:QRTvSZQpxqm8mSErhnbI+tANIBAKP7B+UIE2z4ypUO0= +github.com/Azure/go-autorest/autorest/azure/cli v0.4.0 h1:Ml+UCrnlKD+cJmSzrZ/RDcDw86NjkRUpnFh7V5JUhzU= +github.com/Azure/go-autorest/autorest/azure/cli v0.4.0/go.mod h1:JljT387FplPzBA31vUcvsetLKF3pec5bdAxjVU4kI2s= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= +github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.4.0 h1:z20OWOSG5aCye0HEkDp6TPmP17ZcfeMxPi6HnSALa8c= +github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= +github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+XA683u8EctwboHk= +github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE= +github.com/Azure/go-autorest/autorest/validation v0.3.0 h1:3I9AAI63HfcLtphd9g39ruUwRI+Ca+z/f36KHPFRUss= +github.com/Azure/go-autorest/autorest/validation v0.3.0/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/logger v0.2.0 h1:e4RVHVZKC5p6UANLJHkM4OfR1UKZPj8Wt8Pcx+3oqrE= +github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= +github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/JamesClonk/vultr v2.0.1+incompatible h1:8mI2fM7FkXJBfpyI3siQ87KCIjo+FsAOiBbgmrYxAQQ= +github.com/JamesClonk/vultr v2.0.1+incompatible/go.mod h1:k9Jhe7M4bxsOOTMtsXQ0Hj7R7vw0FW4Q4jVJrPis9a8= +github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU= +github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= +github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= +github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87 h1:xPMsUicZ3iosVPSIP7bW5EcGUzjiiMl1OYTe14y/R24= +github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87/go.mod h1:iGLljf5n9GjT6kc0HBvyI1nOKnGQbNB66VzSNbK5iks= +github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk= +github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= +github.com/TeaWeb/agent v0.0.0-20191129072344-6274ce47207a h1:mnPY948EeM107HWiX38/pK/vQpLBEpp+WinOb3lA11U= +github.com/TeaWeb/agent v0.0.0-20191129072344-6274ce47207a/go.mod h1:sKq3cDTMkEgazeYI4TKo03Xz9PTPwMZ2yiQnPg+qXLs= +github.com/TeaWeb/plugin v0.0.0-20190202040243-6fb957e0eb4a h1:eBirFjqMtroy4c/kqy+wh1JHuDMNMzPSf4IupEYxt1A= +github.com/TeaWeb/plugin v0.0.0-20190202040243-6fb957e0eb4a/go.mod h1:HZS9S9Dr7LiAMPAJtQn0A60wU6zFi/wZ49uK+g058R8= +github.com/TeaWeb/uaparser v0.0.0-20190526084055-a1c9449348d8 h1:RB/ViZWtFrBoOBCl1G/BoK+vwN5fn1T6Nu0ZRAX+pzM= +github.com/TeaWeb/uaparser v0.0.0-20190526084055-a1c9449348d8/go.mod h1:fZeQjUBKU5ZkEJdzN7IS7zs1NBmPcauemXXGfFBN0Q0= +github.com/akamai/AkamaiOPEN-edgegrid-golang v0.9.18 h1:KyEv96ncdgOIJRTKMcWlIqM0umf8X3LQP6oOyg0hNsM= +github.com/akamai/AkamaiOPEN-edgegrid-golang v0.9.18/go.mod h1:L+HB2uBoDgi3+r1pJEJcbGwyyHhd2QXaGsKLbDwtm8Q= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/aliyun/alibaba-cloud-sdk-go v1.61.370 h1:YB6kPMuCtNQSyCZQToeyUsKgQwBp1J9Ks1QbXOxlhHg= +github.com/aliyun/alibaba-cloud-sdk-go v1.61.370/go.mod h1:pUKYbK5JQ+1Dfxk80P0qxGqe5dkxDoabbZS7zOcouyA= +github.com/aws/aws-sdk-go v1.29.15 h1:0ms/213murpsujhsnxnNKNeVouW60aJqSd992Ks3mxs= +github.com/aws/aws-sdk-go v1.29.15/go.mod h1:1KvfttTE3SPKMpo8g2c6jL3ZKfXtFvKscTgahTma5Xg= +github.com/aws/aws-sdk-go v1.30.20 h1:ktsy2vodSZxz/arYqo7DlpkIeNohHL+4Rmjdo7YGtrE= +github.com/aws/aws-sdk-go v1.30.20/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= +github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/cloudflare-go v0.13.0 h1:Mx2gNz/r4H0eHETENq5ZPtc/kOX/uzEfT2UFuA+/XAU= +github.com/cloudflare/cloudflare-go v0.13.0/go.mod h1:6rZ6s/XWxP8WIWMATgDM7aUop0Z0ZOAfcm/4rEd0lOY= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cpu/goacmedns v0.0.3 h1:QOeMpIEsIdm1LSASSswjaTf8CXmzcrgy5OeCfHjppA4= +github.com/cpu/goacmedns v0.0.3/go.mod h1:4MipLkI+qScwqtVxcNO6okBhbgRrr7/tKXUSgSL0teQ= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cyberdelia/templates v0.0.0-20141128023046-ca7fffd4298c/go.mod h1:GyV+0YP4qX0UQ7r2MoYZ+AvYDp12OF5yg4q8rGnyNh4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dchest/captcha v0.0.0-20170622155422-6a29415a8364 h1:U+BMqUt8LFgyrF0/NKgPZdr1sGZ3j6uBECpOGcISpFI= +github.com/dchest/captcha v0.0.0-20170622155422-6a29415a8364/go.mod h1:QGrK8vMWWHQYQ3QU9bw9Y9OPNfxccGzfb41qjvVeXtY= +github.com/dchest/siphash v1.2.1 h1:4cLinnzVJDKxTCl9B01807Yiy+W7ZzVHj/KIroQRvT4= +github.com/dchest/siphash v1.2.1/go.mod h1:q+IRvb2gOSrUnYoPqHiyHXS0FOBBOdl6tONBlVnOnt4= +github.com/decker502/dnspod-go v0.2.0 h1:6dwhUFCYbC5bgpebLKn7PrI43e/5mn9tpUL9YcYCdTU= +github.com/decker502/dnspod-go v0.2.0/go.mod h1:qsurYu1FgxcDwfSwXJdLt4kRsBLZeosEb9uq4Sy+08g= +github.com/deepmap/oapi-codegen v1.3.7-0.20200311141508-ee90a3f9f1ae h1:TT7bfbLlmCLG3s0GRvqZr1ibJbZMpVNd6ko/bYjoDa4= +github.com/deepmap/oapi-codegen v1.3.7-0.20200311141508-ee90a3f9f1ae/go.mod h1:sLdeQJus+YPkWVQaVp+jRr/7t/TP1PTi8QSD7H86AZw= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TRo4= +github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= +github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= +github.com/dnsimple/dnsimple-go v0.63.0 h1:0doY8VW/ckRIMTmOw4E1vwqo+bhtjDzvh1pU2ZteFGA= +github.com/dnsimple/dnsimple-go v0.63.0/go.mod h1:O5TJ0/U6r7AfT8niYNlmohpLbCSG+c71tQlGr9SeGrg= +github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= +github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= +github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/exoscale/egoscale v0.28.0 h1:4pD9KJRgq2g+603NIUbJIYYXPYp18+fQxe3ar+Jm5pA= +github.com/exoscale/egoscale v0.28.0/go.mod h1:WThejIJgwf32NoUfOhIHIH7GfD6ZU4QK9mC1s8inIaU= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/getkin/kin-openapi v0.2.0/go.mod h1:V1z9xl9oF5Wt7v32ne4FmiF1alpS4dM6mNzoywPOXlk= +github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-acme/lego v2.7.2+incompatible h1:ThhpPBgf6oa9X/vRd0kEmWOsX7+vmYdckmGZSb+FEp0= +github.com/go-acme/lego v2.7.2+incompatible/go.mod h1:yzMNe9CasVUhkquNvti5nAtPmG94USbYxYrZfTkIn0M= +github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= +github.com/go-cmd/cmd v1.0.5/go.mod h1:y8q8qlK5wQibcw63djSl/ntiHUHXHGdCkPk0j4QeW4s= +github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= +github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI= +github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM= +github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= +github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= +github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= +github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= +github.com/go-redis/redis v6.15.8+incompatible h1:BKZuG6mCnRj5AOaWJXoCgf6rqTYnYJLe4en2hxT7r9o= +github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-resty/resty/v2 v2.1.1-0.20191201195748-d7b97669fe48 h1:JVrqSeQfdhYRFk24TvhTZWU0q8lfCojxZQFi3Ou7+uY= +github.com/go-resty/resty/v2 v2.1.1-0.20191201195748-d7b97669fe48/go.mod h1:dZGr0i9PLlaaTD4H/hoZIDjQ+r6xq8mgbRzHZf7f2J8= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= +github.com/go-yaml/yaml v2.1.0+incompatible h1:RYi2hDdss1u4YE7GwixGzWwVo47T8UQwnTLB6vQiq+o= +github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0= +github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0= +github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY= +github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg= +github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs= +github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk= +github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28= +github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo= +github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk= +github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw= +github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360= +github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg= +github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE= +github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8= +github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ= +github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0= +github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw= +github.com/gofrs/uuid v3.2.0+incompatible h1:y12jRkkFxsd7GpqdSZ+/KCs/fJbqpEXSGd4+jfEaewE= +github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golangci/lint-1 v0.0.0-20181222135242-d2cdd8c08219/go.mod h1:/X8TswGSh1pIozq4ZwCfxS0WA5JGXguxk94ar/4c87Y= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= +github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/googleapis/gnostic v0.1.0 h1:rVsPeBmXbYv4If/cumu1AzZPwV58q433hvONV1UEZoI= +github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/gophercloud/gophercloud v0.1.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= +github.com/gophercloud/gophercloud v0.12.0 h1:mZrie07npp6ODiwHZolTicr5jV8Ogn43AvAsSMm6Ork= +github.com/gophercloud/gophercloud v0.12.0/go.mod h1:gmC5oQqMDOMO1t1gq5DquX/yAU808e/4mzjjDA76+Ss= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= +github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= +github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI= +github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= +github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP3V9oNE4hmsM= +github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df h1:MZf03xP9WdakyXhOWuAD5uPK3wHh96wCsqe3hCMKh8E= +github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df/go.mod h1:QMZY7/J/KSQEhKWFeDesPjMj+wCHReeknARU3wqlyN4= +github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q= +github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/iwind/TeaGo v0.0.0-20200731084534-255664a0c121 h1:wgys8ruwEX92NP8tSbKZMzswjsyz0o2vbJL4OhD9Ssg= +github.com/iwind/TeaGo v0.0.0-20200731084534-255664a0c121/go.mod h1:zjM7k+b+Jthhf0T0fKwuF0iy4TWb5SsU1gmKR2l+OmE= +github.com/iwind/gofcgi v0.0.0-20181229122301-daea2786cb0d h1:nxDdqzn7XmgGZCrUx2qyl6W5qHp2ioR8aXB9YgQ9qMA= +github.com/iwind/gofcgi v0.0.0-20181229122301-daea2786cb0d/go.mod h1:Z/PdoqueJP653H+hs+zp93mwMI2MS+xJDYf9WCuZNL8= +github.com/jlaffaye/ftp v0.0.0-20200730135723-c2ee4fa2503b h1:Nkvgm5aGQ8GgFOoGo3suLnNYL0sWbz8Svx3gldSwNLE= +github.com/jlaffaye/ftp v0.0.0-20200730135723-c2ee4fa2503b/go.mod h1:2lmrmq866uF2tnje75wQHzmPXhmSWUt7Gyx2vgK1RCU= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.5 h1:gL2yXlmiIo4+t+y32d4WGwOjKGYcGOuyrg46vadswDE= +github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.8 h1:QiWkFLKq0T7mpzwOTu6BzNDbfTE8OLrYhVKYMLF46Ok= +github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= +github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.9.5 h1:U+CaK85mrNNb4k8BNOfgJtJ/gr6kswUCFj6miSzVC6M= +github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/kolo/xmlrpc v0.0.0-20200310150728-e0350524596b h1:DzHy0GlWeF0KAglaTMY7Q+khIFoG8toHP+wLFBVBQJc= +github.com/kolo/xmlrpc v0.0.0-20200310150728-e0350524596b/go.mod h1:o03bZfuBwAXHetKXuInt4S7omeXUu62/A845kiycsSQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/labbsr0x/bindman-dns-webhook v1.0.2 h1:I7ITbmQPAVwrDdhd6dHKi+MYJTJqPCK0jE6YNBAevnk= +github.com/labbsr0x/bindman-dns-webhook v1.0.2/go.mod h1:p6b+VCXIR8NYKpDr8/dg1HKfQoRHCdcsROXKvmoehKA= +github.com/labbsr0x/goh v1.0.1 h1:97aBJkDjpyBZGPbQuOK5/gHcSFbcr5aRsq3RSRJFpPk= +github.com/labbsr0x/goh v1.0.1/go.mod h1:8K2UhVoaWXcCU7Lxoa2omWnC8gyW8px7/lmO61c027w= +github.com/labstack/echo/v4 v4.1.11 h1:z0BZoArY4FqdpUEl+wlHp4hnr/oSR6MTmQmv8OHSoww= +github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= +github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= +github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= +github.com/lib/pq v1.8.0 h1:9xohqzkUwzR4Ga4ivdTcawVS89YSDVxXMa3xJX3cGzg= +github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/linode/linodego v0.20.0 h1:EaMO01fC6lwpMAx6xXZVz4UdaKblQxaSJFOEQspvUDM= +github.com/linode/linodego v0.20.0/go.mod h1:XOWXRHjqeU2uPS84tKLgfWIfTlv3TYzCS0io4GOQzEI= +github.com/luckygo666/lego v2.7.2+incompatible h1:9f6E3WJv239UqLdeHzvw521RnGCLpzUr3vJoMRLcl7M= +github.com/luckygo666/lego v2.7.2+incompatible/go.mod h1:1AlOLs0VQgzQ4GLWl9j7wk3/WHS2ktzkMqqmuanKFBw= +github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.2 h1:V9ecaZWDYm7v9uJ15RZD6DajMu5sE0hdep0aoDwT9g4= +github.com/mailru/easyjson v0.7.2/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= +github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= +github.com/matryer/moq v0.0.0-20190312154309-6cfb0558e1bd/go.mod h1:9ELz6aaclSIGnZBoaSLZ3NAl1VTufbOrXBPvtcy6WiQ= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= +github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-tty v0.0.0-20180219170247-931426f7535a/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.1.31 h1:sJFOl9BgwbYAWOGEwr61FU28pqsBNdpRBnhGXtO06Oo= +github.com/miekg/dns v1.1.31/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-vnc v0.0.0-20150629162542-723ed9867aed/go.mod h1:3rdaFaCv4AyBgu5ALFM0+tSuHrBh6v692nyQe3ikrq0= +github.com/mitchellh/mapstructure v1.3.1 h1:cCBH2gTD2K0OtLlv/Y5H01VQCqmlDxz30kS5Y5bqfLA= +github.com/mitchellh/mapstructure v1.3.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04 h1:o6uBwrhM5C8Ll3MAAxrQxRHEu7FkapwTuI2WmL1rw4g= +github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04/go.mod h1:5sN+Lt1CaY4wsPvgQH/jsuJi4XO2ssZbdsIizr4CVC8= +github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= +github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nrdcg/auroradns v1.0.1 h1:m/kBq83Xvy3cU261MOknd8BdnOk12q4lAWM+kOdsC2Y= +github.com/nrdcg/auroradns v1.0.1/go.mod h1:y4pc0i9QXYlFCWrhWrUSIETnZgrf4KuwjDIWmmXo3JI= +github.com/nrdcg/goinwx v0.7.0 h1:j6JlOp0nNwtvaP09TvKqc9pktjH81nOad0+Gx9S1t9U= +github.com/nrdcg/goinwx v0.7.0/go.mod h1:4tKJOCi/1lTxuw9/yB2Ez0aojwtUCSkckjc22eALpqE= +github.com/nrdcg/namesilo v0.2.1 h1:kLjCjsufdW/IlC+iSfAqj0iQGgKjlbUUeDJio5Y6eMg= +github.com/nrdcg/namesilo v0.2.1/go.mod h1:lwMvfQTyYq+BbjJd30ylEG4GPSS6PII0Tia4rRpRiyw= +github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA= +github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= +github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/oracle/oci-go-sdk v22.0.0+incompatible h1:EDi5Hji0AVU3HVw6B8smL35EBCo//g1215W/T9soc0k= +github.com/oracle/oci-go-sdk v22.0.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888= +github.com/oschwald/geoip2-golang v1.4.0 h1:5RlrjCgRyIGDz/mBmPfnAF4h8k0IAcRv9PvrpOfz+Ug= +github.com/oschwald/geoip2-golang v1.4.0/go.mod h1:8QwxJvRImBH+Zl6Aa6MaIcs5YdlZSTKtzmPGzQqi9ng= +github.com/oschwald/maxminddb-golang v1.6.0 h1:KAJSjdHQ8Kv45nFIbtoLGrGWqHFajOIm7skTyz/+Dls= +github.com/oschwald/maxminddb-golang v1.6.0/go.mod h1:DUJFucBg2cvqx42YmDa/+xHvb0elJtOm3o4aFQ/nb/w= +github.com/ovh/go-ovh v1.1.0 h1:bHXZmw8nTgZin4Nv7JuaLs0KG5x54EQR7migYTd1zrk= +github.com/ovh/go-ovh v1.1.0/go.mod h1:AxitLZ5HBRPyUd+Zl60Ajaag+rNTdVXWIkzfrVuTXWA= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo= +github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.11.0 h1:4Zv0OGbpkg4yNuUtH0s8rvoYxRCNyT29NVUo6pgPmxI= +github.com/pkg/sftp v1.11.0/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pquerna/ffjson v0.0.0-20190930134022-aa0246cd15f7 h1:xoIK0ctDddBMnc74udxJYBqlo9Ylnsp1waqjLsnef20= +github.com/pquerna/ffjson v0.0.0-20190930134022-aa0246cd15f7/go.mod h1:YARuvh7BUWHNhzDq2OM5tzR2RiCcN2D7sapiKyCel/M= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2 h1:dq90+d51/hQRaHEqRAsQ1rE/pC1GUS4sc2rCbbFsAIY= +github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2/go.mod h1:7tZKcyumwBO6qip7RNQ5r77yrssm9bfCowcLEBcU5IA= +github.com/robertkrimen/otto v0.0.0-20191219234010-c382bd3c16ff h1:+6NUiITWwE5q1KO6SAfUX918c+Tab0+tGAM/mtdlUyA= +github.com/robertkrimen/otto v0.0.0-20191219234010-c382bd3c16ff/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY= +github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sacloud/libsacloud v1.36.1 h1:tCpFjWsvu/2Im8/SDmRZ49SttVXy7nHerobRc1LU9pI= +github.com/sacloud/libsacloud v1.36.1/go.mod h1:P7YAOVmnIn3DKHqCZcUKYUXmSwGBm3yS7IBEjKVSrjg= +github.com/shirou/gopsutil v2.20.6+incompatible h1:P37G9YH8M4vqkKcwBosp+URN5O8Tay67D2MbR361ioY= +github.com/shirou/gopsutil v2.20.6+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a h1:pa8hGb/2YqsZKovtsgrwcDH1RZhVbTKCjLp47XpqCDs= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE= +github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ= +github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e h1:nt2877sKfojlHCTOBXbpWjBkuWKritFaGIfgQwbQUls= +github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e/go.mod h1:B4+Kq1u5FlULTjFSM707Q6e/cOHFv0z/6QRoxubDIQ8= +github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM= +github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog= +github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/timewasted/linode v0.0.0-20160829202747-37e84520dcf7 h1:CpHxIaZzVy26GqJn8ptRyto8fuoYOd1v0fXm9bG3wQ8= +github.com/timewasted/linode v0.0.0-20160829202747-37e84520dcf7/go.mod h1:imsgLplxEC/etjIhdr3dNzV3JeT27LbVu5pYWm0JCBY= +github.com/transip/gotransip v5.8.2+incompatible h1:aNJhw/w/3QBqFcHAIPz1ytoK5FexeMzbUCGrrhWr3H0= +github.com/transip/gotransip v5.8.2+incompatible/go.mod h1:uacMoJVmrfOcscM4Bi5NVg708b7c6rz2oDTWqa7i2Ic= +github.com/uber-go/atomic v1.3.2 h1:Azu9lPBWRNKzYXSIwRfgRuDuS0YKsK4NFhiQv98gkxo= +github.com/uber-go/atomic v1.3.2/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g= +github.com/urfave/cli v1.22.4 h1:u7tSpNPPswAFymm8IehJhy4uJMlUuU/GmqSkvJ1InXA= +github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= +github.com/valyala/fasttemplate v1.1.0 h1:RZqt0yGBsps8NGvLSGW804QQqCUYYLsaOjTVHy1Ocw4= +github.com/valyala/fasttemplate v1.1.0/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= +github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= +github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vultr/govultr v0.4.2 h1:9i8xKZ+xp6vwZ9raqHoBLzhB4wCnMj7nOQTj5YIRLWY= +github.com/vultr/govultr v0.4.2/go.mod h1:TUuUizMOFc7z+PNMssb6iGjKjQfpw5arIaOLfocVudQ= +github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c h1:u40Z8hqBAAQyv+vATcGgV0YCnDjqSL7/q/JyPhhJSPk= +github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= +github.com/xdg/stringprep v0.0.0-20180714160509-73f8eece6fdc h1:n+nNi93yXLkJvKwXNP9d55HC7lGK4H/SRcwB5IaUZLo= +github.com/xdg/stringprep v0.0.0-20180714160509-73f8eece6fdc/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.mongodb.org/mongo-driver v1.4.0 h1:C8rFn1VF4GVEM/rG+dSoMmlm2pyQ9cs2/oRtUATejRU= +go.mongodb.org/mongo-driver v1.4.0/go.mod h1:llVBH2pkj9HywK0Dtdt6lDikOjFLbceHVu/Rc0iMKLs= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.uber.org/atomic v1.3.2 h1:2Oa65PReHzfn29GpvgsYwloV9AVFHPDk8tYxt2c2tr4= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/ratelimit v0.0.0-20180316092928-c15da0234277 h1:d9qaMM+ODpCq+9We41//fu/sHsTnXcrqd1en3x+GKy4= +go.uber.org/ratelimit v0.0.0-20180316092928-c15da0234277/go.mod h1:2X8KaoNd1J0lZV+PxJk/5+DGbO/tpwLR1m++a7FnB/Y= +golang.org/x/crypto v0.0.0-20180621125126-a49355c7e3f8/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191112222119-e1110fd1c708/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20191202143827-86a70503ff7e/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de h1:ikNHVSjEfnvz6sxdSPCaPt572qowuyMDMJLLm3Db3ig= +golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191126235420-ef20fe5d7933/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200707034311-ab3426394381 h1:VXak5I6aEWmAXeQjA+QSZzlgNrpq9mjcfDemuexIKsU= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180622082034-63fc586f45fe/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191224085550-c709ea063b76/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200802091954-4b90ce9b60b3 h1:qDJKu1y/1SjhWac4BQZjLljqvqiWUhjmDMnonmVGDAU= +golang.org/x/sys v0.0.0-20200802091954-4b90ce9b60b3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e h1:EHBhcS0mlXEAVwNyO2dLfjToGsyY4j24pTs2ScHnX7s= +golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191203134012-c197fd4bf371/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.29.0 h1:BaiDisFir8O4IJxvAabCGGkQ6yCJegNQqSVoYUNAnbk= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940 h1:MRHtG0U6SnaUb+s+LhNE1qt1FQ1wlhqr5E4usBKC0uA= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0 h1:bO/TA4OxCOummhSf10siHuG7vJOiwh7SpRpFZDkOgl4= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/h2non/gock.v1 v1.0.15 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0= +gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/ini.v1 v1.42.0 h1:7N3gPTt50s8GuLortA00n8AqRTk75qOP98+mTPpgzRk= +gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.57.0 h1:9unxIsFcTt4I55uWluz+UmL95q4kdJ0buvQ1ZIqVQww= +gopkg.in/ini.v1 v1.57.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ns1/ns1-go.v2 v2.4.1 h1:TW9qG+gETxGChMmEqd3Jh9zPJxWnJfxoiuzIOfPio0k= +gopkg.in/ns1/ns1-go.v2 v2.4.1/go.mod h1:GMnKY+ZuoJ+lVLL+78uSTjwTz2jMazq6AfGKQOYhsPk= +gopkg.in/sourcemap.v1 v1.0.5 h1:inv58fC9f9J3TK2Y2R1NPntXEn3/wjWHkonhIUODNTI= +gopkg.in/sourcemap.v1 v1.0.5/go.mod h1:2RlvNNSMglmRrcvhfuzp4hQHwOtjxlbjX7UPY/GXb78= +gopkg.in/square/go-jose.v2 v2.5.1 h1:7odma5RETjNHWJnR32wx8t+Io4djHE1PqxCFx3iiZ2w= +gopkg.in/square/go-jose.v2 v2.5.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +k8s.io/api v0.18.3 h1:2AJaUQdgUZLoDZHrun21PW2Nx9+ll6cUzvn3IKhSIn0= +k8s.io/api v0.18.3/go.mod h1:UOaMwERbqJMfeeeHc8XJKawj4P9TgDRnViIqqBeH2QA= +k8s.io/apimachinery v0.18.3 h1:pOGcbVAhxADgUYnjS08EFXs9QMl8qaH5U4fr5LGUrSk= +k8s.io/apimachinery v0.18.3/go.mod h1:OaXp26zu/5J7p0f92ASynJa1pZo06YlV9fG7BoWbCko= +k8s.io/client-go v0.18.3 h1:QaJzz92tsN67oorwzmoB0a9r9ZVHuD5ryjbCKP0U22k= +k8s.io/client-go v0.18.3/go.mod h1:4a/dpQEvzAhT1BbuWW09qvIaGw6Gbu1gZYiQZIi1DMw= +k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= +k8s.io/klog v0.3.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= +k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= +k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= +k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= +k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89 h1:d4vVOjXm687F1iLSP2q3lyPPuyvTUt3aVoBpi2DqRsU= +k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= +sigs.k8s.io/structured-merge-diff/v3 v3.0.0-20200116222232-67a7b8c61874/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= +sigs.k8s.io/structured-merge-diff/v3 v3.0.0 h1:dOmIZBMfhcHS09XZkMyUgkq5trg3/jRyJYFZUiaOp8E= +sigs.k8s.io/structured-merge-diff/v3 v3.0.0/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= +sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q= +sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= diff --git a/teacache/redis.go b/teacache/redis.go index 56a5a65..cf05ac4 100644 --- a/teacache/redis.go +++ b/teacache/redis.go @@ -5,7 +5,6 @@ import ( "github.com/go-redis/redis" "github.com/iwind/TeaGo/logs" "github.com/iwind/TeaGo/maps" - "golang.org/x/net/context" "strings" "time" ) @@ -74,12 +73,12 @@ func (this *RedisManager) SetOptions(options map[string]interface{}) { } func (this *RedisManager) Write(key string, data []byte) error { - cmd := this.client.Set(context.Background(), "TEA_CACHE_"+this.id+key, string(data), this.Life) + cmd := this.client.Set("TEA_CACHE_"+this.id+key, string(data), this.Life) return cmd.Err() } func (this *RedisManager) Read(key string) (data []byte, err error) { - cmd := this.client.Get(context.Background(), "TEA_CACHE_"+this.id+key) + cmd := this.client.Get("TEA_CACHE_"+this.id+key) if cmd.Err() != nil { if cmd.Err() == redis.Nil { return nil, ErrNotFound @@ -92,7 +91,7 @@ func (this *RedisManager) Read(key string) (data []byte, err error) { // 删除 func (this *RedisManager) Delete(key string) error { - cmd := this.client.Del(context.Background(), "TEA_CACHE_"+this.id+key) + cmd := this.client.Del("TEA_CACHE_"+this.id+key) return cmd.Err() } @@ -112,7 +111,7 @@ func (this *RedisManager) DeletePrefixes(prefixes []string) (int, error) { loopCount++ var keys []string - keys, cursor, err = this.client.Scan(context.Background(), cursor, keyPrefix+"*", 10000).Result() + keys, cursor, err = this.client.Scan(cursor, keyPrefix+"*", 10000).Result() if err != nil { return count, err } @@ -121,7 +120,7 @@ func (this *RedisManager) DeletePrefixes(prefixes []string) (int, error) { realKey := key[keyPrefixLength:] for _, prefix := range prefixes { if strings.HasPrefix(realKey, prefix) || strings.HasPrefix("http://"+realKey, prefix) || strings.HasPrefix("https://"+realKey, prefix) { - err1 := this.client.Del(context.Background(), key).Err() + err1 := this.client.Del(key).Err() if err1 != nil { err = err1 break @@ -154,14 +153,14 @@ func (this *RedisManager) Stat() (size int64, countKeys int, err error) { loopCount++ var keys []string - keys, cursor, err = this.client.Scan(context.Background(), cursor, "TEA_CACHE_"+this.Id()+"*", 10000).Result() + keys, cursor, err = this.client.Scan(cursor, "TEA_CACHE_"+this.Id()+"*", 10000).Result() if err != nil { return } if len(keys) > 0 { countKeys += len(keys) for _, key := range keys { - val, _ := this.client.Get(context.Background(), key).Bytes() + val, _ := this.client.Get(key).Bytes() size += int64(len(val)) } } @@ -187,13 +186,13 @@ func (this *RedisManager) Clean() error { loopCount++ var keys []string - keys, cursor, err = this.client.Scan(context.Background(), cursor, "TEA_CACHE_"+this.Id()+"*", 10000).Result() + keys, cursor, err = this.client.Scan(cursor, "TEA_CACHE_"+this.Id()+"*", 10000).Result() if err != nil { return err } if len(keys) > 0 { for _, key := range keys { - err1 := this.client.Del(context.Background(), key).Err() + err1 := this.client.Del(key).Err() if err1 != nil { err = err1 break diff --git a/teaconfigs/ssl_acme_request.go b/teaconfigs/ssl_acme_request.go index ec4a440..53d124c 100644 --- a/teaconfigs/ssl_acme_request.go +++ b/teaconfigs/ssl_acme_request.go @@ -8,14 +8,14 @@ import ( "crypto/x509" "encoding/base64" "errors" - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/registration" - "github.com/iwind/TeaGo/utils/time" + timeutil "github.com/iwind/TeaGo/utils/time" + "github.com/luckygo666/lego/v3/acme" + "github.com/luckygo666/lego/v3/certcrypto" + "github.com/luckygo666/lego/v3/certificate" + "github.com/luckygo666/lego/v3/challenge/dns01" + "github.com/luckygo666/lego/v3/lego" + "github.com/luckygo666/lego/v3/log" + "github.com/luckygo666/lego/v3/registration" "io/ioutil" golog "log" "strings" diff --git a/teaconfigs/ssl_acme_user.go b/teaconfigs/ssl_acme_user.go index e0e7667..ade0404 100644 --- a/teaconfigs/ssl_acme_user.go +++ b/teaconfigs/ssl_acme_user.go @@ -2,7 +2,7 @@ package teaconfigs import ( "crypto" - "github.com/go-acme/lego/registration" + "github.com/luckygo666/lego/v3/registration" ) // ACME用户账号定义 diff --git a/teatesting/require.go b/teatesting/require.go index 9757d98..216b0b1 100644 --- a/teatesting/require.go +++ b/teatesting/require.go @@ -1,7 +1,6 @@ package teatesting import ( - "context" "github.com/TeaWeb/code/teautils" "github.com/go-redis/redis" "github.com/iwind/TeaGo/logs" @@ -102,7 +101,7 @@ func RequireRedis() bool { Addr: "127.0.0.1:6379", DialTimeout: 5 * time.Second, }) - cmd := client.Ping(context.Background()) + cmd := client.Ping() return cmd.Err() == nil } diff --git a/vendor/github.com/go-acme/lego/.dockerignore b/vendor/github.com/go-acme/lego/.dockerignore deleted file mode 100644 index e27fb10..0000000 --- a/vendor/github.com/go-acme/lego/.dockerignore +++ /dev/null @@ -1,8 +0,0 @@ -lego.exe -.lego -.gitcookies -.idea -.vscode/ -dist/ -builds/ -docs/ diff --git a/vendor/github.com/go-acme/lego/.gitcookies.enc b/vendor/github.com/go-acme/lego/.gitcookies.enc deleted file mode 100644 index 09c303c..0000000 Binary files a/vendor/github.com/go-acme/lego/.gitcookies.enc and /dev/null differ diff --git a/vendor/github.com/go-acme/lego/.gitignore b/vendor/github.com/go-acme/lego/.gitignore deleted file mode 100644 index 03ba0e6..0000000 --- a/vendor/github.com/go-acme/lego/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.lego -.gitcookies -.idea -.vscode/ -dist/ -builds/ diff --git a/vendor/github.com/go-acme/lego/.golangci.toml b/vendor/github.com/go-acme/lego/.golangci.toml deleted file mode 100644 index 81912c4..0000000 --- a/vendor/github.com/go-acme/lego/.golangci.toml +++ /dev/null @@ -1,83 +0,0 @@ -[run] - deadline = "5m" - skip-files = [] - -[linters-settings] - - [linters-settings.govet] - check-shadowing = true - - [linters-settings.gocyclo] - min-complexity = 12.0 - - [linters-settings.maligned] - suggest-new = true - - [linters-settings.goconst] - min-len = 3.0 - min-occurrences = 3.0 - - [linters-settings.misspell] - locale = "US" - -[linters] - enable-all = true - disable = [ - "maligned", - "lll", - "gas", - "dupl", - "prealloc", - "scopelint", - ] - -[issues] - exclude-use-default = false - max-per-linter = 0 - max-same-issues = 0 - exclude = [ - "Error return value of .((os\\.)?std(out|err)\\..*|.*Close|.*Flush|os\\.Remove(All)?|.*printf?|os\\.(Un)?Setenv). is not checked", - "exported (type|method|function) (.+) should have comment or be unexported", - ] - [[issues.exclude-rules]] - path = "providers/dns/dns_providers.go" - linters = ["gocyclo"] - [[issues.exclude-rules]] - path = "providers/dns/gcloud/googlecloud_test.go" - text = "string `(lego\\.wtf|manhattan)` has (\\d+) occurrences, make it a constant" - [[issues.exclude-rules]] - path = "providers/dns/zoneee/zoneee_test.go" - text = "string `(bar|foo)` has (\\d+) occurrences, make it a constant" - [[issues.exclude-rules]] - path = "certcrypto/crypto.go" - text = "`(tlsFeatureExtensionOID|ocspMustStapleFeature)` is a global variable" - [[issues.exclude-rules]] - path = "challenge/dns01/nameserver.go" - text = "`(defaultNameservers|recursiveNameservers|dnsTimeout|fqdnToZone|muFqdnToZone)` is a global variable" - [[issues.exclude-rules]] - path = "challenge/tlsalpn01/tls_alpn_challenge.go" - text = "`idPeAcmeIdentifierV1` is a global variable" - [[issues.exclude-rules]] - path = "log/logger.go" - text = "`Logger` is a global variable" - [[issues.exclude-rules]] - path = "cmd/lego/main.go" - text = "`version` is a global variable" - [[issues.exclude-rules]] - path = "e2e/(dnschallenge/)?[\\d\\w]+_test.go" - text = "`load` is a global variable" - [[issues.exclude-rules]] - path = "providers/dns/([\\d\\w]+/)*[\\d\\w]+_test.go" - text = "`envTest` is a global variable" - [[issues.exclude-rules]] - path = "providers/dns/namecheap/namecheap_test.go" - text = "`(tldsMock|testCases)` is a global variable" - [[issues.exclude-rules]] - path = "providers/dns/acmedns/acmedns_test.go" - text = "`(errorClientErr|errorStorageErr|egTestAccount)` is a global variable" - [[issues.exclude-rules]] - path = "providers/http/memcached/memcached_test.go" - text = "`memcachedHosts` is a global variable" - [[issues.exclude-rules]] - path = "providers/dns/sakuracloud/client_test.go" - text = "cyclomatic complexity 13 of func `(TestDNSProvider_cleanupTXTRecord_concurrent|TestDNSProvider_addTXTRecord_concurrent)` is high" diff --git a/vendor/github.com/go-acme/lego/.goreleaser.yml b/vendor/github.com/go-acme/lego/.goreleaser.yml deleted file mode 100644 index 64290e6..0000000 --- a/vendor/github.com/go-acme/lego/.goreleaser.yml +++ /dev/null @@ -1,43 +0,0 @@ -project_name: lego - -builds: - - binary: lego - - main: ./cmd/lego/main.go - ldflags: - - -s -w -X main.version={{.Version}} - - goos: - - windows - - darwin - - linux - - freebsd - - openbsd - - solaris - goarch: - - amd64 - - 386 - - arm - - arm64 - goarm: - - 7 - - ignore: - - goos: darwin - goarch: 386 - - goos: openbsd - goarch: arm - -archive: - name_template: '{{ .ProjectName }}_v{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm - }}v{{ .Arm }}{{ end }}' - format: tar.gz - format_overrides: - - goos: windows - format: zip - files: - - LICENSE - - CHANGELOG.md - -release: - disable: true \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/.travis.yml b/vendor/github.com/go-acme/lego/.travis.yml deleted file mode 100644 index 9430d54..0000000 --- a/vendor/github.com/go-acme/lego/.travis.yml +++ /dev/null @@ -1,83 +0,0 @@ -language: go - -go: - - 1.12.x - - 1.x - -services: - - memcached - -go_import_path: github.com/go-acme/lego - -addons: - hosts: - # for e2e tests - - acme.wtf - - lego.wtf - - acme.lego.wtf - - légô.wtf - - xn--lg-bja9b.wtf - -env: - - MEMCACHED_HOSTS=localhost:11211 - -before_install: - - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_26c593b079d9_key -iv $encrypted_26c593b079d9_iv -in .gitcookies.enc -out .gitcookies -d || true' - - # Download and install dep - - curl -sI https://github.com/golang/dep/releases/latest | grep -Fi Location | tr -d '\r' | sed "s/tag/download/g" | awk -F " " '{ print $2 "/dep-linux-amd64"}' | wget --output-document=$GOPATH/bin/dep -i - - - chmod +x $GOPATH/bin/dep - - # Install Pebble and challtestsrv - - go get -u github.com/letsencrypt/pebble/... - - # Install linters and misspell - - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.16.0 - - golangci-lint --version - - # Hugo - documentation - - wget -O /tmp/hugo.deb https://github.com/gohugoio/hugo/releases/download/v0.54.0/hugo_0.54.0_Linux-64bit.deb - - sudo dpkg -i /tmp/hugo.deb - -install: - - echo "TRAVIS_GO_VERSION=$TRAVIS_GO_VERSION" - - dep status -v - -before_script: - - make validate-doc - -after_success: - - make clean - -before_deploy: - - > - if ! [ "$BEFORE_DEPLOY_RUN" ]; then - export BEFORE_DEPLOY_RUN=1; - make docs-build - fi - -deploy: - - provider: script - skip_cleanup: true - script: curl -sL https://git.io/goreleaser | bash - on: - tags: true - condition: $TRAVIS_GO_VERSION =~ ^1\.x$ - - - provider: releases - api_key: ${GITHUB_TOKEN} - file: dist/lego_* - skip_cleanup: true - overwrite: true - file_glob: true - on: - tags: true - condition: $TRAVIS_GO_VERSION =~ ^1\.x$ - - - provider: pages - local_dir: docs/public - skip_cleanup: true - github_token: ${GITHUB_TOKEN} - on: - tags: true - condition: $TRAVIS_GO_VERSION =~ ^1\.x$ diff --git a/vendor/github.com/go-acme/lego/CHANGELOG.md b/vendor/github.com/go-acme/lego/CHANGELOG.md deleted file mode 100644 index 77c1284..0000000 --- a/vendor/github.com/go-acme/lego/CHANGELOG.md +++ /dev/null @@ -1,392 +0,0 @@ -# Changelog - -## [v2.6.0] - 2019-05-27 - -### Added: -- **[dnsprovider]** Add support for Joker.com DMAPI -- **[dnsprovider]** Add support for Bindman DNS provider -- **[dnsprovider]** Add support for EasyDNS -- **[lib]** Get an existing certificate by URL - -### Changed: -- **[dnsprovider]** digitalocean: LEGO_EXPERIMENTAL_CNAME_SUPPORT support -- **[dnsprovider]** gcloud: Use fqdn to get zone Present/CleanUp -- **[dnsprovider]** exec: serial behavior -- **[dnsprovider]** manual: serial behavior. -- **[dnsprovider]** Strip newlines when reading environment variables from `_FILE` suffixed files. - -### Fixed: -- **[cli]** fix: cli disable-cp option. -- **[dnsprovider]** gcloud: fix zone visibility. - -## [v2.5.0] - 2019-04-17 - -### Added: -- **[cli]** Adds renew hook -- **[dnsprovider]** Adds 'Since' to DNS providers documentation - -### Changed: -- **[dnsprovider]** gcloud: use public DNS zones -- **[dnsprovider]** route53: enhance documentation. - -### Fixed: -- **[dnsprovider]** cloudns: fix TTL and status validation -- **[dnsprovider]** sakuracloud: supports concurrent update -- **[dnsprovider]** Disable authz when solve fail. -- Add tzdata to the Docker image. - -## [v2.4.0] - 2019-03-25 - -- Migrate from xenolf/lego to go-acme/lego. - -### Added: -- **[dnsprovider]** Add DNS Provider for Domain Offensive (do.de) -- **[dnsprovider]** Adds information about '_FILE' suffix. - -### Fixed: -- **[cli,dnsprovider]** Add 'manual' provider to the output of dnshelp -- **[dnsprovider]** hostingde: Use provided ZoneName instead of domain -- **[dnsprovider]** pdns: fix wildcard with SANs - -## [v2.3.0] - 2019-03-11 - -### Added: -- **[dnsprovider]** Add DNS Provider for ClouDNS.net -- **[dnsprovider]** Add DNS Provider for Oracle Cloud - -### Changed: -- **[cli]** Adds log when no renewal. -- **[dnsprovider,lib]** Add a mechanism to wrap a PreCheckFunc -- **[dnsprovider]** oraclecloud: better way to get private key. -- **[dnsprovider]** exoscale: update library - -### Fixed: -- **[dnsprovider]** OVH: Refresh zone after deleting challenge record -- **[dnsprovider]** oraclecloud: ttl config and timeout -- **[dnsprovider]** hostingde: fix client fails if customer has no access to dns-groups -- **[dnsprovider]** vscale: getting sub-domain -- **[dnsprovider]** selectel: getting sub-domain -- **[dnsprovider]** vscale: fix TXT records clean up -- **[dnsprovider]** selectel: fix TXT records clean up - -## [v2.2.0] - 2019-02-08 - -### Added: -- **[dnsprovider]** Add support for Openstack Designate as a DNS provider -- **[dnsprovider]** gcloud: Option to specify gcloud service account json by env as string -- **[experimental feature]** Resolve CNAME when creating dns-01 challenge. To enable: set `LEGO_EXPERIMENTAL_CNAME_SUPPORT` to `true`. - -### Changed: -- **[cli]** Applies Let’s Encrypt’s recommendation about renew. The option `--days` of the command `renew` has a new default value (`30`) -- **[lib]** Uses a jittered exponential backoff - -### Fixed: -- **[cli]** CLI and key type. -- **[dnsprovider]** httpreq: Endpoint with path. -- **[dnsprovider]** fastdns: Do not overwrite existing TXT records -- Log wildcard domain correctly in validation - -## [v2.1.0] - 2019-01-24 - -### Added: -- **[dnsprovider]** Add support for zone.ee as a DNS provider. - -### Changed: -- **[dnsprovider]** nifcloud: Change DNS base url. -- **[dnsprovider]** gcloud: More detailed information about Google Cloud DNS. - -### Fixed: -- **[lib]** fix: OCSP, set HTTP client. -- **[dnsprovider]** alicloud: fix pagination. -- **[dnsprovider]** namecheap: fix panic. - -## [v2.0.0] - 2019-01-09 - -### Added: -- **[cli,lib]** Option to disable the complete propagation Requirement -- **[lib,cli]** Support non-ascii domain name (punnycode) -- **[cli,lib]** Add configurable timeout when obtaining certificates -- **[cli]** Archive revoked certificates -- **[cli]** Add command to list certificates. -- **[cli]** support for renew with CSR -- **[cli]** add SAN on renew -- **[lib]** Adds `Remove` for challenges -- **[lib]** Add version to xenolf-acme in User-Agent. -- **[dnsprovider]** The ability for a DNS provider to solve the challenge sequentially -- **[dnsprovider]** Add DNS provider for "HTTP request". -- **[dnsprovider]** Add DNS Provider for Vscale -- **[dnsprovider]** Add DNS Provider for TransIP -- **[dnsprovider]** Add DNS Provider for inwx -- **[dnsprovider]** alidns: add support to handle more than 20 domains - -### Changed: -- **[lib]** Check all challenges in a predictable order -- **[lib]** Poll authz URL instead of challenge URL -- **[lib]** Check all nameservers in a predictable order -- **[lib]** Logs every iteration of waiting for the propagation -- **[cli]** `--http`: enable HTTP challenge **important** -- **[cli]** `--http.port`: previously named `--http` -- **[cli]** `--http.webroot`: previously named `--webroot` -- **[cli]** `--http.memcached-host`: previously named `--memcached-host` -- **[cli]** `--tls`: enable TLS challenge **important** -- **[cli]** `--tls.port`: previously named `--tls` -- **[cli]** `--dns.resolvers`: previously named `--dns-resolvers` -- **[cli]** the option `--days` of the command `renew` has default value (`15`) -- **[dnsprovider]** gcloud: Use GCE_PROJECT for project always, if specified - -### Removed: -- **[lib]** Remove `SetHTTP01Address` -- **[lib]** Remove `SetTLSALPN01Address` -- **[lib]** Remove `Exclude` -- **[cli]** Remove `--exclude`, `-x` - -### Fixed: -- **[lib]** Fixes revocation for subdomains and non-ascii domains -- **[lib]** Disable pending authorizations -- **[dnsprovider]** transip: concurrent access to the API. -- **[dnsprovider]** gcloud: fix for wildcard -- **[dnsprovider]** Azure: Do not overwrite existing TXT records -- **[dnsprovider]** fix: Cloudflare error. - -## [v1.2.0] - 2018-11-04 - -### Added: -- **[dnsprovider]** Add DNS Provider for ConoHa DNS -- **[dnsprovider]** Add DNS Provider for MyDNS.jp -- **[dnsprovider]** Add DNS Provider for Selectel - -### Fixed: -- **[dnsprovider]** netcup: make unmarshalling of api-responses more lenient. - -### Changed: -- **[dnsprovider]** aurora: change DNS client -- **[dnsprovider]** azure: update auth to support instance metadata service -- **[dnsprovider]** dnsmadeeasy: log response body on error -- **[lib]** TLS-ALPN-01: Update idPeAcmeIdentifierV1, draft refs. -- **[lib]** Do not send a JWS body when POSTing challenges. -- **[lib]** Support POST-as-GET. - -## [v1.1.0] - 2018-10-16 - -### Added: -- **[lib]** TLS-ALPN-01 Challenge -- **[cli]** Add filename parameter -- **[dnsprovider]** Allow to configure TTL, interval and timeout -- **[dnsprovider]** Add support for reading DNS provider setup from files -- **[dnsprovider]** Add DNS Provider for ACME-DNS -- **[dnsprovider]** Add DNS Provider for ALIYUN DNS -- **[dnsprovider]** Add DNS Provider for DreamHost -- **[dnsprovider]** Add DNS provider for hosting.de -- **[dnsprovider]** Add DNS Provider for IIJ -- **[dnsprovider]** Add DNS Provider for netcup -- **[dnsprovider]** Add DNS Provider for NIFCLOUD DNS -- **[dnsprovider]** Add DNS Provider for SAKURA Cloud -- **[dnsprovider]** Add DNS Provider for Stackpath -- **[dnsprovider]** Add DNS Provider for VegaDNS -- **[dnsprovider]** exec: add EXEC_MODE=RAW support. -- **[dnsprovider]** cloudflare: support for CF_API_KEY and CF_API_EMAIL - -### Fixed: -- **[lib]** Don't trust identifiers order. -- **[lib]** Fix missing issuer certificates from Let's Encrypt -- **[dnsprovider]** duckdns: fix TXT record update url -- **[dnsprovider]** duckdns: fix subsubdomain -- **[dnsprovider]** gcloud: update findTxtRecords to use Name=fqdn and Type=TXT -- **[dnsprovider]** lightsail: Fix Domain does not exist error -- **[dnsprovider]** ns1: use the authoritative zone and not the domain name -- **[dnsprovider]** ovh: check error to avoid panic due to nil client - -### Changed: -- **[lib]** Submit all dns records up front, then validate serially - -## [v1.0.0] - 2018-05-30 - -### Changed: -- **[lib]** ACME v2 Support. -- **[dnsprovider]** Renamed `/providers/dns/googlecloud` to `/providers/dns/gcloud`. -- **[dnsprovider]** Modified Google Cloud provider `gcloud.NewDNSProviderServiceAccount` function to extract the project id directly from the service account file. -- **[dnsprovider]** Made errors more verbose for the Cloudflare provider. - -## [v0.5.0] - 2018-05-29 - -### Added: -- **[dnsprovider]** Add DNS challenge provider `exec` -- **[dnsprovider]** Add DNS Provider for Akamai FastDNS -- **[dnsprovider]** Add DNS Provider for Bluecat DNS -- **[dnsprovider]** Add DNS Provider for CloudXNS -- **[dnsprovider]** Add DNS Provider for Duck DNS -- **[dnsprovider]** Add DNS Provider for Gandi Beta Platform (LiveDNS) -- **[dnsprovider]** Add DNS Provider for GleSYS API -- **[dnsprovider]** Add DNS Provider for GoDaddy -- **[dnsprovider]** Add DNS Provider for Lightsail -- **[dnsprovider]** Add DNS Provider for Name.com - -### Fixed: -- **[dnsprovider]** Azure: Added missing environment variable in the comments -- **[dnsprovider]** PowerDNS: Fix zone URL, add leading slash. -- **[dnsprovider]** DNSimple: Fix api -- **[cli]** Correct help text for `--dns-resolvers` default. -- **[cli]** renew/revoke - don't panic on wrong account. -- **[lib]** Fix zone detection for cross-zone cnames. -- **[lib]** Use proxies from environment when making outbound http connections. - -### Changed: -- **[lib]** Users of an effective top-level domain can use the DNS challenge. -- **[dnsprovider]** Azure: Refactor to work with new Azure SDK version. -- **[dnsprovider]** Cloudflare and Azure: Adding output of which envvars are missing. -- **[dnsprovider]** Dyn DNS: Slightly improve provider error reporting. -- **[dnsprovider]** Exoscale: update to latest egoscale version. -- **[dnsprovider]** Route53: Use NewSessionWithOptions instead of deprecated New. - -## [0.4.1] - 2017-09-26 - -### Added: -- lib: A new DNS provider for OTC. -- lib: The `AWS_HOSTED_ZONE_ID` environment variable for the Route53 DNS provider to directly specify the zone. -- lib: The `RFC2136_TIMEOUT` enviroment variable to make the timeout for the RFC2136 provider configurable. -- lib: The `GCE_SERVICE_ACCOUNT_FILE` environment variable to specify a service account file for the Google Cloud DNS provider. - -### Fixed: -- lib: Fixed an authentication issue with the latest Azure SDK. - -## [0.4.0] - 2017-07-13 - -### Added: -- CLI: The `--http-timeout` switch. This allows for an override of the default client HTTP timeout. -- lib: The `HTTPClient` field. This allows for an override of the default HTTP timeout for library HTTP requests. -- CLI: The `--dns-timeout` switch. This allows for an override of the default DNS timeout for library DNS requests. -- lib: The `DNSTimeout` switch. This allows for an override of the default client DNS timeout. -- lib: The `QueryRegistration` function on `acme.Client`. This performs a POST on the client registration's URI and gets the updated registration info. -- lib: The `DeleteRegistration` function on `acme.Client`. This deletes the registration as currently configured in the client. -- lib: The `ObtainCertificateForCSR` function on `acme.Client`. The function allows to request a certificate for an already existing CSR. -- CLI: The `--csr` switch. Allows to use already existing CSRs for certificate requests on the command line. -- CLI: The `--pem` flag. This will change the certificate output so it outputs a .pem file concatanating the .key and .crt files together. -- CLI: The `--dns-resolvers` flag. Allows for users to override the default DNS servers used for recursive lookup. -- lib: Added a memcached provider for the HTTP challenge. -- CLI: The `--memcached-host` flag. This allows to use memcached for challenge storage. -- CLI: The `--must-staple` flag. This enables OCSP must staple in the generated CSR. -- lib: The library will now honor entries in your resolv.conf. -- lib: Added a field `IssuerCertificate` to the `CertificateResource` struct. -- lib: A new DNS provider for OVH. -- lib: A new DNS provider for DNSMadeEasy. -- lib: A new DNS provider for Linode. -- lib: A new DNS provider for AuroraDNS. -- lib: A new DNS provider for NS1. -- lib: A new DNS provider for Azure DNS. -- lib: A new DNS provider for Rackspace DNS. -- lib: A new DNS provider for Exoscale DNS. -- lib: A new DNS provider for DNSPod. - -### Changed: -- lib: Exported the `PreCheckDNS` field so library users can manage the DNS check in tests. -- lib: The library will now skip challenge solving if a valid Authz already exists. - -### Removed: -- lib: The library will no longer check for auto renewed certificates. This has been removed from the spec and is not supported in Boulder. - -### Fixed: -- lib: Fix a problem with the Route53 provider where it was possible the verification was published to a private zone. -- lib: Loading an account from file should fail if a integral part is nil -- lib: Fix a potential issue where the Dyn provider could resolve to an incorrect zone. -- lib: If a registration encounteres a conflict, the old registration is now recovered. -- CLI: The account.json file no longer has the executable flag set. -- lib: Made the client registration more robust in case of a 403 HTTP response. -- lib: Fixed an issue with zone lookups when they have a CNAME in another zone. -- lib: Fixed the lookup for the authoritative zone for Google Cloud. -- lib: Fixed a race condition in the nonce store. -- lib: The Google Cloud provider now removes old entries before trying to add new ones. -- lib: Fixed a condition where we could stall due to an early error condition. -- lib: Fixed an issue where Authz object could end up in an active state after an error condition. - -## [0.3.1] - 2016-04-19 - -### Added: -- lib: A new DNS provider for Vultr. - -### Fixed: -- lib: DNS Provider for DigitalOcean could not handle subdomains properly. -- lib: handleHTTPError should only try to JSON decode error messages with the right content type. -- lib: The propagation checker for the DNS challenge would not retry on send errors. - - -## [0.3.0] - 2016-03-19 - -### Added: -- CLI: The `--dns` switch. To include the DNS challenge for consideration. When using this switch, all other solvers are disabled. Supported are the following solvers: cloudflare, digitalocean, dnsimple, dyn, gandi, googlecloud, namecheap, route53, rfc2136 and manual. -- CLI: The `--accept-tos` switch. Indicates your acceptance of the Let's Encrypt terms of service without prompting you. -- CLI: The `--webroot` switch. The HTTP-01 challenge may now be completed by dropping a file into a webroot. When using this switch, all other solvers are disabled. -- CLI: The `--key-type` switch. This replaces the `--rsa-key-size` switch and supports the following key types: EC256, EC384, RSA2048, RSA4096 and RSA8192. -- CLI: The `--dnshelp` switch. This displays a more in-depth help topic for DNS solvers. -- CLI: The `--no-bundle` sub switch for the `run` and `renew` commands. When this switch is set, the CLI will not bundle the issuer certificate with your certificate. -- lib: A new type for challenge identifiers `Challenge` -- lib: A new interface for custom challenge providers `acme.ChallengeProvider` -- lib: A new interface for DNS-01 providers to allow for custom timeouts for the validation function `acme.ChallengeProviderTimeout` -- lib: SetChallengeProvider function. Pass a challenge identifier and a Provider to replace the default behaviour of a challenge. -- lib: The DNS-01 challenge has been implemented with modular solvers using the `ChallengeProvider` interface. Included solvers are: cloudflare, digitalocean, dnsimple, gandi, namecheap, route53, rfc2136 and manual. -- lib: The `acme.KeyType` type was added and is used for the configuration of crypto parameters for RSA and EC keys. Valid KeyTypes are: EC256, EC384, RSA2048, RSA4096 and RSA8192. - -### Changed -- lib: ExcludeChallenges now expects to be passed an array of `Challenge` types. -- lib: HTTP-01 now supports custom solvers using the `ChallengeProvider` interface. -- lib: TLS-SNI-01 now supports custom solvers using the `ChallengeProvider` interface. -- lib: The `GetPrivateKey` function in the `acme.User` interface is now expected to return a `crypto.PrivateKey` instead of an `rsa.PrivateKey` for EC compat. -- lib: The `acme.NewClient` function now expects an `acme.KeyType` instead of the keyBits parameter. - -### Removed -- CLI: The `rsa-key-size` switch was removed in favor of `key-type` to support EC keys. - -### Fixed -- lib: Fixed a race condition in HTTP-01 -- lib: Fixed an issue where status codes on ACME challenge responses could lead to no action being taken. -- lib: Fixed a regression when calling the Renew function with a SAN certificate. - -## [0.2.0] - 2016-01-09 - -### Added: -- CLI: The `--exclude` or `-x` switch. To exclude a challenge from being solved. -- CLI: The `--http` switch. To set the listen address and port of HTTP based challenges. Supports `host:port` and `:port` for any interface. -- CLI: The `--tls` switch. To set the listen address and port of TLS based challenges. Supports `host:port` and `:port` for any interface. -- CLI: The `--reuse-key` switch for the `renew` operation. This lets you reuse an existing private key for renewals. -- lib: ExcludeChallenges function. Pass an array of challenge identifiers to exclude them from solving. -- lib: SetHTTPAddress function. Pass a port to set the listen port for HTTP based challenges. -- lib: SetTLSAddress function. Pass a port to set the listen port of TLS based challenges. -- lib: acme.UserAgent variable. Use this to customize the user agent on all requests sent by lego. - -### Changed: -- lib: NewClient does no longer accept the optPort parameter -- lib: ObtainCertificate now returns a SAN certificate if you pass more then one domain. -- lib: GetOCSPForCert now returns the parsed OCSP response instead of just the status. -- lib: ObtainCertificate has a new parameter `privKey crypto.PrivateKey` which lets you reuse an existing private key for new certificates. -- lib: RenewCertificate now expects the PrivateKey property of the CertificateResource to be set only if you want to reuse the key. - -### Removed: -- CLI: The `--port` switch was removed. -- lib: RenewCertificate does no longer offer to also revoke your old certificate. - -### Fixed: -- CLI: Fix logic using the `--days` parameter for renew - -## [0.1.1] - 2015-12-18 - -### Added: -- CLI: Added a way to automate renewal through a cronjob using the --days parameter to renew - -### Changed: -- lib: Improved log output on challenge failures. - -### Fixed: -- CLI: The short parameter for domains would not get accepted -- CLI: The cli did not return proper exit codes on error library errors. -- lib: RenewCertificate did not properly renew SAN certificates. - -### Security -- lib: Fix possible DOS on GetOCSPForCert - -## [0.1.0] - 2015-12-03 -- Initial release - -[0.3.1]: https://github.com/go-acme/lego/compare/v0.3.0...v0.3.1 -[0.3.0]: https://github.com/go-acme/lego/compare/v0.2.0...v0.3.0 -[0.2.0]: https://github.com/go-acme/lego/compare/v0.1.1...v0.2.0 -[0.1.1]: https://github.com/go-acme/lego/compare/v0.1.0...v0.1.1 -[0.1.0]: https://github.com/go-acme/lego/tree/v0.1.0 diff --git a/vendor/github.com/go-acme/lego/CONTRIBUTING.md b/vendor/github.com/go-acme/lego/CONTRIBUTING.md deleted file mode 100644 index c81702f..0000000 --- a/vendor/github.com/go-acme/lego/CONTRIBUTING.md +++ /dev/null @@ -1,75 +0,0 @@ -# How to contribute to lego - -Contributions in the form of patches and proposals are essential to keep lego great and to make it even better. -To ensure a great and easy experience for everyone, please review the few guidelines in this document. - -## Bug reports - -- Use the issue search to see if the issue has already been reported. -- Also look for closed issues to see if your issue has already been fixed. -- If both of the above do not apply create a new issue and include as much information as possible. - -Bug reports should include all information a person could need to reproduce your problem without the need to -follow up for more information. If possible, provide detailed steps for us to reproduce it, the expected behaviour and the actual behaviour. - -## Feature proposals and requests - -Feature requests are welcome and should be discussed in an issue. -Please keep proposals focused on one thing at a time and be as detailed as possible. -It is up to you to make a strong point about your proposal and convince us of the merits and the added complexity of this feature. - -## Pull requests - -Patches, new features and improvements are a great way to help the project. -Please keep them focused on one thing and do not include unrelated commits. - -All pull requests which alter the behaviour of the program, add new behaviour or somehow alter code in a non-trivial way should **always** include tests. - -If you want to contribute a significant pull request (with a non-trivial workload for you) please **ask first**. We do not want you to spend -a lot of time on something the project's developers might not want to merge into the project. - -**IMPORTANT**: By submitting a patch, you agree to allow the project -owners to license your work under the terms of the [MIT License](LICENSE). - -### How to create a pull request - -First, you have to install [GoLang](https://golang.org/doc/install) and [golangci-lint](https://github.com/golangci/golangci-lint#install). - -```bash -# Create the root folder -mkdir -p $GOPATH/src/github.com/go-acme -cd $GOPATH/src/github.com/go-acme - -# clone your fork -git clone git@github.com:YOUR_USERNAME/lego.git -cd lego - -# Add the go-acme/lego remote -git remote add upstream git@github.com:go-acme/lego.git -git fetch upstream -``` - -```bash -# Create your branch -git checkout -b my-feature - -## Create your code ## -``` - -```bash -# Format -make fmt -# Linters -make checks -# Tests -make test -# Compile -make build -``` - -```bash -# push your branch -git push -u origin my-feature - -## create a pull request on Github ## -``` diff --git a/vendor/github.com/go-acme/lego/Dockerfile b/vendor/github.com/go-acme/lego/Dockerfile deleted file mode 100644 index a8df46c..0000000 --- a/vendor/github.com/go-acme/lego/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM golang:alpine3.9 as builder - -RUN apk --update upgrade \ - && apk --no-cache --no-progress add make git - -WORKDIR /go/src/github.com/go-acme/lego -COPY . . -RUN make build - -FROM alpine:3.9 -RUN apk update \ - && apk add --no-cache ca-certificates tzdata \ - && update-ca-certificates - -COPY --from=builder /go/src/github.com/go-acme/lego/dist/lego /usr/bin/lego -ENTRYPOINT [ "/usr/bin/lego" ] diff --git a/vendor/github.com/go-acme/lego/Gopkg.lock b/vendor/github.com/go-acme/lego/Gopkg.lock deleted file mode 100644 index 4ec54bd..0000000 --- a/vendor/github.com/go-acme/lego/Gopkg.lock +++ /dev/null @@ -1,871 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:5c3894b2aa4d6bead0ceeea6831b305d62879c871780e7b76296ded1b004bc57" - name = "cloud.google.com/go" - packages = ["compute/metadata"] - pruneopts = "NUT" - revision = "64a2037ec6be8a4b0c1d1f706ed35b428b989239" - version = "v0.26.0" - -[[projects]] - digest = "1:e589e863ce0d0500bb806c716877c2f8caffe2a2b6c2f6c148d535d8eeb92d00" - name = "github.com/Azure/azure-sdk-for-go" - packages = [ - "services/dns/mgmt/2017-09-01/dns", - "version", - ] - pruneopts = "NUT" - revision = "4e8cbbfb1aeab140cd0fa97fd16b64ee18c3ca6a" - version = "v19.1.0" - -[[projects]] - digest = "1:0b2163d4a757420217d4e0461128bf5c96be6d1614513b31d35029872a07ad40" - name = "github.com/Azure/go-autorest" - packages = [ - "autorest", - "autorest/adal", - "autorest/azure", - "autorest/azure/auth", - "autorest/date", - "autorest/to", - "autorest/validation", - "logger", - "version", - ] - pruneopts = "NUT" - revision = "39013ecb48eaf6ced3f4e3e1d95515140ce6b3cf" - version = "v10.15.2" - -[[projects]] - digest = "1:5d72bbcc9c8667b11c3dc3cbe681c5a6f71e5096744c0bf7726ab5c6425d5dc4" - name = "github.com/BurntSushi/toml" - packages = ["."] - pruneopts = "NUT" - revision = "3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005" - version = "v0.3.1" - -[[projects]] - digest = "1:ed3fc9992df610d07c85c24e0b792268cc1ce226dd9bf8cb2e6ad9a377b35415" - name = "github.com/JamesClonk/vultr" - packages = ["lib"] - pruneopts = "NUT" - revision = "fa1c0367800db75e4d10d0ec90c49a8731670224" - version = "1.15.0" - -[[projects]] - branch = "master" - digest = "1:a4068a93355ba3cff0a719425713123d23c90010cb4d023b40c679a22465736d" - name = "github.com/OpenDNS/vegadns2client" - packages = ["."] - pruneopts = "NUT" - revision = "a3fa4a771d87bda2514a90a157e1fed1b6897d2e" - -[[projects]] - digest = "1:47071ecf8d840dd357ede1b2aed46576bdd0a866adecef3c9e85a00db9672202" - name = "github.com/akamai/AkamaiOPEN-edgegrid-golang" - packages = [ - "client-v1", - "configdns-v1", - "edgegrid", - "jsonhooks-v1", - ] - pruneopts = "NUT" - revision = "1471ce9c14c6d8c007516e129262962a628fecdf" - version = "v0.7.3" - -[[projects]] - digest = "1:823e87ae25170339e2bfd1d6f7c2e27554c6bb5655f91c67b37bd5be45bb6b32" - name = "github.com/aliyun/alibaba-cloud-sdk-go" - packages = [ - "sdk", - "sdk/auth", - "sdk/auth/credentials", - "sdk/auth/signers", - "sdk/endpoints", - "sdk/errors", - "sdk/requests", - "sdk/responses", - "sdk/utils", - "services/alidns", - ] - pruneopts = "NUT" - revision = "cad214d7d71fba7883fcf3b7e550ba782c15b400" - version = "1.27.7" - -[[projects]] - digest = "1:1634c57333a07adf7d7e206d3329340f1c36e82bca9e61e2cff08c064ab85046" - name = "github.com/aws/aws-sdk-go" - packages = [ - "aws", - "aws/awserr", - "aws/awsutil", - "aws/client", - "aws/client/metadata", - "aws/corehandlers", - "aws/credentials", - "aws/credentials/ec2rolecreds", - "aws/credentials/endpointcreds", - "aws/credentials/stscreds", - "aws/csm", - "aws/defaults", - "aws/ec2metadata", - "aws/endpoints", - "aws/request", - "aws/session", - "aws/signer/v4", - "internal/sdkio", - "internal/sdkrand", - "internal/sdkuri", - "internal/shareddefaults", - "private/protocol", - "private/protocol/json/jsonutil", - "private/protocol/jsonrpc", - "private/protocol/query", - "private/protocol/query/queryutil", - "private/protocol/rest", - "private/protocol/restxml", - "private/protocol/xml/xmlutil", - "service/lightsail", - "service/route53", - "service/sts", - ] - pruneopts = "NUT" - revision = "8b15f938ed215522a37275106e847f6f0be85fe8" - version = "v1.15.23" - -[[projects]] - digest = "1:cdee563173093e5ae7ab2a19c298e0904129719e1919a3c532b7bb0c3398b818" - name = "github.com/cenkalti/backoff" - packages = ["."] - pruneopts = "NUT" - revision = "1e4cf3da559842a91afcb6ea6141451e6c30c618" - version = "v2.1.1" - -[[projects]] - digest = "1:03cfacdc6bfd46007c15786c1ece3fa074f89e5193a292f0f26d9e98c99c7cc2" - name = "github.com/cloudflare/cloudflare-go" - packages = ["."] - pruneopts = "NUT" - revision = "1f9007fbecae20711133c60519338c41cef1ffb4" - version = "v0.8.5" - -[[projects]] - branch = "master" - digest = "1:2a7013a7e8cfec93dd725f95ea0c4b390d7d71f8a8bc3dbde05cfc9524ba5ea8" - name = "github.com/cpu/goacmedns" - packages = ["."] - pruneopts = "NUT" - revision = "565ecf2a84df654865cc102705ac160a3b04fc01" - -[[projects]] - digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" - name = "github.com/davecgh/go-spew" - packages = ["spew"] - pruneopts = "NUT" - revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" - version = "v1.1.1" - -[[projects]] - branch = "master" - digest = "1:981e5cf3c23056668c447439e90d3a441358eb68e5189b1952c909772383b944" - name = "github.com/decker502/dnspod-go" - packages = ["."] - pruneopts = "NUT" - revision = "83a3ba562b048c9fc88229408e593494b7774684" - -[[projects]] - digest = "1:7a6852b35eb5bbc184561443762d225116ae630c26a7c4d90546619f1e7d2ad2" - name = "github.com/dgrijalva/jwt-go" - packages = ["."] - pruneopts = "NUT" - revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" - version = "v3.2.0" - -[[projects]] - branch = "master" - digest = "1:ec6271918b59b872a2d25e374569a4f75f1839d91e4191470c297b7eaaaf7641" - name = "github.com/dimchansky/utfbom" - packages = ["."] - pruneopts = "NUT" - revision = "5448fe645cb1964ba70ac8f9f2ffe975e61a536c" - -[[projects]] - digest = "1:e856fc44ab196970612bdc8c15e65ccf92ed8d4ccb3a2e65b88dc240a2fe5d0b" - name = "github.com/dnsimple/dnsimple-go" - packages = ["dnsimple"] - pruneopts = "NUT" - revision = "f5ead9c20763fd925dea1362f2af5d671ed2a459" - version = "v0.21.0" - -[[projects]] - digest = "1:9013e4c7a6ff077dcb478aa75524aa73b5763136efb4efe8949b18d9b90dd212" - name = "github.com/exoscale/egoscale" - packages = ["."] - pruneopts = "NUT" - revision = "4acc53d7aa0960f007acf1daedef69a6d24d8d1f" - version = "v0.14.0" - -[[projects]] - digest = "1:aa3ed0a71c4e66e4ae6486bf97a3f4cab28edc78df2e50c5ad01dc7d91604b88" - name = "github.com/fatih/structs" - packages = ["."] - pruneopts = "NUT" - revision = "4966fc68f5b7593aafa6cbbba2d65ec6e1416047" - version = "v1.1.0" - -[[projects]] - digest = "1:ea1d5bfdb4ec5c2ee48c97865e6de1a28fa8c4849a3f56b27d521aa619038e06" - name = "github.com/go-errors/errors" - packages = ["."] - pruneopts = "NUT" - revision = "a6af135bd4e28680facf08a3d206b454abc877a4" - version = "v1.0.1" - -[[projects]] - digest = "1:74d9b0a7b4107b41e0ade759fac64502876f82d29fb23d77b3dd24b194ee3dd5" - name = "github.com/go-ini/ini" - packages = ["."] - pruneopts = "NUT" - revision = "5cf292cae48347c2490ac1a58fe36735fb78df7e" - version = "v1.38.2" - -[[projects]] - digest = "1:ed6fe3cdb5ccb17387b5cb11c0cbd125699f5f5d23626ccf78a7c5859183e063" - name = "github.com/go-resty/resty" - packages = ["."] - pruneopts = "NUT" - revision = "97a15579492cd5f35632499f315d7a8df94160a1" - version = "v1.8.0" - -[[projects]] - digest = "1:63ccdfbd20f7ccd2399d0647a7d100b122f79c13bb83da9660b1598396fd9f62" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "NUT" - revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5" - version = "v1.2.0" - -[[projects]] - branch = "master" - digest = "1:a63cff6b5d8b95638bfe300385d93b2a6d9d687734b863da8e09dc834510a690" - name = "github.com/google/go-querystring" - packages = ["query"] - pruneopts = "NUT" - revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a" - -[[projects]] - digest = "1:1bb197a3b5db4e06e00b7560f8e89836c486627f2a0338332ed37daa003d259e" - name = "github.com/google/uuid" - packages = ["."] - pruneopts = "NUT" - revision = "064e2069ce9c359c118179501254f67d7d37ba24" - version = "0.2" - -[[projects]] - branch = "master" - digest = "1:de9a3291ce7afad12af8b11f3e9972edca4b77ca1374eacd0c9fa1ff1bddcc7c" - name = "github.com/gophercloud/gophercloud" - packages = [ - ".", - "openstack", - "openstack/dns/v2/recordsets", - "openstack/dns/v2/zones", - "openstack/identity/v2/tenants", - "openstack/identity/v2/tokens", - "openstack/identity/v3/tokens", - "openstack/utils", - "pagination", - ] - pruneopts = "NUT" - revision = "a2b0ad6ce68c8302027db1a5f9dbb03b0c8ab072" - -[[projects]] - digest = "1:67474f760e9ac3799f740db2c489e6423a4cde45520673ec123ac831ad849cb8" - name = "github.com/hashicorp/golang-lru" - packages = ["simplelru"] - pruneopts = "NUT" - revision = "7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c" - version = "v0.5.1" - -[[projects]] - branch = "master" - digest = "1:c45e4f1755487478216e06437e161d56299d963282ce109555091bc4c7a57343" - name = "github.com/iij/doapi" - packages = [ - ".", - "protocol", - ] - pruneopts = "NUT" - revision = "8803795a9b7b938fa88ddbd63a77893beee14cd8" - -[[projects]] - digest = "1:ac6d01547ec4f7f673311b4663909269bfb8249952de3279799289467837c3cc" - name = "github.com/jmespath/go-jmespath" - packages = ["."] - pruneopts = "NUT" - revision = "0b12d6b5" - -[[projects]] - digest = "1:8e36686e8b139f8fe240c1d5cf3a145bc675c22ff8e707857cdd3ae17b00d728" - name = "github.com/json-iterator/go" - packages = ["."] - pruneopts = "NUT" - revision = "1624edc4454b8682399def8740d46db5e4362ba4" - version = "v1.1.5" - -[[projects]] - digest = "1:8b3234b10eacd5edea45bf0c13a585b608749da23f94aaf29b46d9ef8a8babf4" - name = "github.com/juju/ratelimit" - packages = ["."] - pruneopts = "NUT" - revision = "59fac5042749a5afb9af70e813da1dd5474f0167" - version = "1.0.1" - -[[projects]] - branch = "master" - digest = "1:ec142582cd3bb5cc29a2bc7181a6e67367b90b19f6a957ce506dcd7d1500bf95" - name = "github.com/kolo/xmlrpc" - packages = ["."] - pruneopts = "NUT" - revision = "16bdd962781df9696f40cc2bab924f1a855a7f89" - -[[projects]] - digest = "1:1082aeb059ff66b4fb6da53f9e7591726c6a81901f05ce48a470091784b23914" - name = "github.com/labbsr0x/bindman-dns-webhook" - packages = [ - "src/client", - "src/types", - ] - pruneopts = "NUT" - revision = "234ca2a50eebc2095f42a884709a6e9013366d86" - version = "v1.0.0" - -[[projects]] - branch = "master" - digest = "1:ad2a63b2d6dfe7d66bf14c01f1171a3951abef6e0fb136170359c3f7c4f51615" - name = "github.com/labbsr0x/goh" - packages = ["gohclient"] - pruneopts = "NUT" - revision = "8b16b4848295edda07b9a828e5a3b285c25c2b9c" - -[[projects]] - digest = "1:111ff5a09a32895248270bfaef9b8b6ac163a8cde9cdd603fed64b3e4b59e8ab" - name = "github.com/linode/linodego" - packages = ["."] - pruneopts = "NUT" - revision = "d0d31d8ca62fa3f7e4526ca0ce95de81e4ed001e" - version = "v0.5.1" - -[[projects]] - digest = "1:6676c63cef61a47c84eae578bcd8fe8352908ccfe3ea663c16797617a29e3c44" - name = "github.com/miekg/dns" - packages = ["."] - pruneopts = "NUT" - revision = "a220737569d8137d4c610f80bd33f1dc762522e5" - version = "v1.1.0" - -[[projects]] - digest = "1:a4df73029d2c42fabcb6b41e327d2f87e685284ec03edf76921c267d9cfc9c23" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "NUT" - revision = "ae18d6b8b3205b561c79e8e5f69bff09736185f4" - version = "v1.0.0" - -[[projects]] - digest = "1:a45ae66dea4c899d79fceb116accfa1892105c251f0dcd9a217ddc276b42ec68" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "NUT" - revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe" - version = "v1.1.2" - -[[projects]] - digest = "1:2f42fa12d6911c7b7659738758631bec870b7e9b4c6be5444f963cdcfccc191f" - name = "github.com/modern-go/concurrent" - packages = ["."] - pruneopts = "NUT" - revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" - version = "1.0.3" - -[[projects]] - digest = "1:c6aca19413b13dc59c220ad7430329e2ec454cc310bc6d8de2c7e2b93c18a0f6" - name = "github.com/modern-go/reflect2" - packages = ["."] - pruneopts = "NUT" - revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" - version = "1.0.1" - -[[projects]] - branch = "master" - digest = "1:9991da8d42da9b213f2890a05ecbe0fad7325ac216ca3bd6ae30921457971fa9" - name = "github.com/namedotcom/go" - packages = ["namecom"] - pruneopts = "NUT" - revision = "08470befbe04613bd4b44cb6978b05d50294c4d4" - -[[projects]] - digest = "1:417193ba917954c4837c6fc48c6ac241b3fefd13fc0889367b4a7e43b69d582c" - name = "github.com/nrdcg/auroradns" - packages = ["."] - pruneopts = "NUT" - revision = "750ca8603f9f2cca2457acb22ea6e44d3f05358c" - version = "v1.0.0" - -[[projects]] - digest = "1:78bc7967454f8c2a1257b3fe4ed1d57227fb1dff46fd74d38b91bd0d0cc2620a" - name = "github.com/nrdcg/goinwx" - packages = ["."] - pruneopts = "NUT" - revision = "d8152159450570012552f924a0ae6ab3d8c617e0" - version = "v0.6.0" - -[[projects]] - digest = "1:c665ac9fd8cedb7bea85380a441dec4e5de3c7d4574e18c6ba53dfe04cf50878" - name = "github.com/oracle/oci-go-sdk" - packages = [ - "common", - "dns", - ] - pruneopts = "NUT" - revision = "f1ecb80f81a9cfa7dbfc964a34a3c62323277a9d" - version = "v4.0.0" - -[[projects]] - branch = "master" - digest = "1:02584222c11b07d1d61cd76cc73e78cbc72810384a7ea69c543246d60d3335f7" - name = "github.com/ovh/go-ovh" - packages = ["ovh"] - pruneopts = "NUT" - revision = "c3e61035ea66f5c637719c90140da4e3ac3b1bf0" - -[[projects]] - digest = "1:5cf3f025cbee5951a4ee961de067c8a89fc95a5adabead774f82822efabab121" - name = "github.com/pkg/errors" - packages = ["."] - pruneopts = "NUT" - revision = "645ef00459ed84a119197bfb8d8205042c6df63d" - version = "v0.8.0" - -[[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - pruneopts = "NUT" - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - branch = "master" - digest = "1:2f0021b2ea953c35cf412d8b7eb03c972a914c8f03c4119993377244cd6aa70b" - name = "github.com/rainycape/memcache" - packages = ["."] - pruneopts = "NUT" - revision = "1031fa0ce2f20c1c0e1e1b51951d8ea02c84fa05" - -[[projects]] - digest = "1:5a632dc3d841d803524bd442976a52e390e4294826ece65722cb77020879d156" - name = "github.com/sacloud/libsacloud" - packages = [ - ".", - "api", - "sacloud", - "sacloud/ostype", - "utils/mutexkv", - ] - pruneopts = "NUT" - revision = "a949b57af53e809207587f8c41571d81f140276e" - version = "v1.19.0" - -[[projects]] - digest = "1:6bc0652ea6e39e22ccd522458b8bdd8665bf23bdc5a20eec90056e4dc7e273ca" - name = "github.com/satori/go.uuid" - packages = ["."] - pruneopts = "NUT" - revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3" - version = "v1.2.0" - -[[projects]] - digest = "1:b2339e83ce9b5c4f79405f949429a7f68a9a904fed903c672aac1e7ceb7f5f02" - name = "github.com/sirupsen/logrus" - packages = ["."] - pruneopts = "NUT" - revision = "3e01752db0189b9157070a0e1668a620f9a85da2" - version = "v1.0.6" - -[[projects]] - digest = "1:60a46e2410edbf02b419f833372dd1d24d7aa1b916a990a7370e792fada1eadd" - name = "github.com/stretchr/objx" - packages = ["."] - pruneopts = "NUT" - revision = "477a77ecc69700c7cdeb1fa9e129548e1c1c393c" - version = "v0.1.1" - -[[projects]] - digest = "1:f1e5a94fc8fde9a67a97106d7d7d386ad0b938b41fde2b110e70447590aea6e7" - name = "github.com/stretchr/testify" - packages = [ - "assert", - "mock", - "require", - "suite", - ] - pruneopts = "NUT" - revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" - version = "v1.2.2" - -[[projects]] - branch = "master" - digest = "1:99ce99ce6d6d0cbc5f822cda92095906e01d5546d60999ac839ab008938e4e17" - name = "github.com/timewasted/linode" - packages = [ - ".", - "dns", - ] - pruneopts = "NUT" - revision = "37e84520dcf74488f67654f9c775b9752c232dc1" - -[[projects]] - branch = "master" - digest = "1:3b236e8930d31aeb375fe405c15c2afc581e04bd6cb68da4723e1aa8d2e2da37" - name = "github.com/transip/gotransip" - packages = [ - ".", - "domain", - "util", - ] - pruneopts = "NUT" - revision = "1dc93a7db3567a5ccf865106afac88278ba940cf" - -[[projects]] - digest = "1:5dba68a1600a235630e208cb7196b24e58fcbb77bb7a6bec08fcd23f081b0a58" - name = "github.com/urfave/cli" - packages = ["."] - pruneopts = "NUT" - revision = "cfb38830724cc34fedffe9a2a29fb54fa9169cd1" - version = "v1.20.0" - -[[projects]] - digest = "1:045bc0ab96bb83bdffd2606f019003da03d1c139d3cb8aad13596863e4dd37d6" - name = "go.opencensus.io" - packages = [ - ".", - "internal", - "internal/tagencoding", - "metric/metricdata", - "metric/metricproducer", - "plugin/ochttp", - "plugin/ochttp/propagation/b3", - "resource", - "stats", - "stats/internal", - "stats/view", - "tag", - "trace", - "trace/internal", - "trace/propagation", - "trace/tracestate", - ] - pruneopts = "NUT" - revision = "8930459677fde1e11e3e1b50bbed1acc850b5665" - version = "v0.20.1" - -[[projects]] - branch = "master" - digest = "1:af471e1efb6318085c2c27ba0bcbf659feab5f7044388c0c0104f456831eb281" - name = "golang.org/x/crypto" - packages = [ - "ed25519", - "ed25519/internal/edwards25519", - "ocsp", - "pbkdf2", - "pkcs12", - "pkcs12/internal/rc2", - "ssh/terminal", - ] - pruneopts = "NUT" - revision = "614d502a4dac94afa3a6ce146bd1736da82514c6" - -[[projects]] - branch = "master" - digest = "1:34f748d79542b732d2e4fab7cc0aad8500673e716e2a665cc72836942377fac9" - name = "golang.org/x/net" - packages = [ - "bpf", - "context", - "context/ctxhttp", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/iana", - "internal/socket", - "internal/timeseries", - "ipv4", - "ipv6", - "publicsuffix", - "trace", - ] - pruneopts = "NUT" - revision = "8a410e7b638dca158bf9e766925842f6651ff828" - -[[projects]] - branch = "master" - digest = "1:b20a60bb1085d4c535af064faf3e74b4e185781b58bba1ad7406cd9733d82403" - name = "golang.org/x/oauth2" - packages = [ - ".", - "clientcredentials", - "google", - "internal", - "jws", - "jwt", - ] - pruneopts = "NUT" - revision = "d2e6202438beef2727060aa7cabdd924d92ebfd9" - -[[projects]] - branch = "master" - digest = "1:e1498a6884b2564efe2a4c4aefce64eb4bc6a4666acfd42db044cf581db4d9cb" - name = "golang.org/x/sys" - packages = [ - "unix", - "windows", - ] - pruneopts = "NUT" - revision = "d99a578cf41bfccdeaf48b0845c823a4b8b0ad5e" - -[[projects]] - digest = "1:e7071ed636b5422cc51c0e3a6cebc229d6c9fffc528814b519a980641422d619" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "NUT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "NUT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - branch = "master" - digest = "1:887c07769ee52c81222ea1112b11a3947c703da529d1643d85c216b9537d87b8" - name = "google.golang.org/api" - packages = [ - "dns/v1", - "gensupport", - "googleapi", - "googleapi/internal/uritemplates", - "googleapi/transport", - "internal", - "option", - "transport/http", - "transport/http/internal/propagation", - ] - pruneopts = "NUT" - revision = "0cbcb99a9ea0c8023c794b2693cbe1def82ed4d7" - -[[projects]] - digest = "1:b5aeceb800276be69165a745328380c8a4b6f2edc7a6bac112e22c8596ed8a49" - name = "google.golang.org/appengine" - packages = [ - ".", - "internal", - "internal/app_identity", - "internal/base", - "internal/datastore", - "internal/log", - "internal/modules", - "internal/remote_api", - "internal/urlfetch", - "urlfetch", - ] - pruneopts = "NUT" - revision = "b1f26356af11148e710935ed1ac8a7f5702c7612" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:c3076e7defee87de1236f1814beb588f40a75544c60121e6eb38b3b3721783e2" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "NUT" - revision = "64821d5d210748c883cd2b809589555ae4654203" - -[[projects]] - digest = "1:f9fe1989f8278a0976fadf27490720c7708c056a11ab7a7ad3d282ff26f28e9a" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "binarylog/grpc_binarylog_v1", - "codes", - "connectivity", - "credentials", - "credentials/internal", - "encoding", - "encoding/proto", - "grpclog", - "internal", - "internal/backoff", - "internal/binarylog", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/grpcsync", - "internal/syscall", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "NUT" - revision = "3507fb8e1a5ad030303c106fef3a47c9fdad16ad" - version = "v1.19.1" - -[[projects]] - digest = "1:74d9b0a7b4107b41e0ade759fac64502876f82d29fb23d77b3dd24b194ee3dd5" - name = "gopkg.in/ini.v1" - packages = ["."] - pruneopts = "NUT" - revision = "5cf292cae48347c2490ac1a58fe36735fb78df7e" - version = "v1.38.2" - -[[projects]] - branch = "v2" - digest = "1:f15af196d07dbb28a0633599eba0fb872acd0b24426001520dd6cb9944c7ad1a" - name = "gopkg.in/ns1/ns1-go.v2" - packages = [ - "rest", - "rest/model/account", - "rest/model/data", - "rest/model/dns", - "rest/model/filter", - "rest/model/monitor", - ] - pruneopts = "NUT" - revision = "028658c6d9be774b6d103a923d8c4b2715135c3f" - -[[projects]] - digest = "1:a50fabe7a46692dc7c656310add3d517abe7914df02afd151ef84da884605dc8" - name = "gopkg.in/square/go-jose.v2" - packages = [ - ".", - "cipher", - "json", - ] - pruneopts = "NUT" - revision = "ef984e69dd356202fd4e4910d4d9c24468bdf0b8" - version = "v2.1.9" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns", - "github.com/Azure/go-autorest/autorest", - "github.com/Azure/go-autorest/autorest/adal", - "github.com/Azure/go-autorest/autorest/azure", - "github.com/Azure/go-autorest/autorest/azure/auth", - "github.com/Azure/go-autorest/autorest/to", - "github.com/BurntSushi/toml", - "github.com/JamesClonk/vultr/lib", - "github.com/OpenDNS/vegadns2client", - "github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1", - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid", - "github.com/aliyun/alibaba-cloud-sdk-go/sdk", - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials", - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests", - "github.com/aliyun/alibaba-cloud-sdk-go/services/alidns", - "github.com/aws/aws-sdk-go/aws", - "github.com/aws/aws-sdk-go/aws/client", - "github.com/aws/aws-sdk-go/aws/credentials", - "github.com/aws/aws-sdk-go/aws/request", - "github.com/aws/aws-sdk-go/aws/session", - "github.com/aws/aws-sdk-go/service/lightsail", - "github.com/aws/aws-sdk-go/service/route53", - "github.com/cenkalti/backoff", - "github.com/cloudflare/cloudflare-go", - "github.com/cpu/goacmedns", - "github.com/decker502/dnspod-go", - "github.com/dnsimple/dnsimple-go/dnsimple", - "github.com/exoscale/egoscale", - "github.com/gophercloud/gophercloud", - "github.com/gophercloud/gophercloud/openstack", - "github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets", - "github.com/gophercloud/gophercloud/openstack/dns/v2/zones", - "github.com/iij/doapi", - "github.com/iij/doapi/protocol", - "github.com/labbsr0x/bindman-dns-webhook/src/client", - "github.com/linode/linodego", - "github.com/miekg/dns", - "github.com/namedotcom/go/namecom", - "github.com/nrdcg/auroradns", - "github.com/nrdcg/goinwx", - "github.com/oracle/oci-go-sdk/common", - "github.com/oracle/oci-go-sdk/dns", - "github.com/ovh/go-ovh/ovh", - "github.com/rainycape/memcache", - "github.com/sacloud/libsacloud/api", - "github.com/sacloud/libsacloud/sacloud", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/mock", - "github.com/stretchr/testify/require", - "github.com/stretchr/testify/suite", - "github.com/timewasted/linode", - "github.com/timewasted/linode/dns", - "github.com/transip/gotransip", - "github.com/transip/gotransip/domain", - "github.com/urfave/cli", - "golang.org/x/crypto/ocsp", - "golang.org/x/net/context", - "golang.org/x/net/idna", - "golang.org/x/net/publicsuffix", - "golang.org/x/oauth2", - "golang.org/x/oauth2/clientcredentials", - "golang.org/x/oauth2/google", - "google.golang.org/api/dns/v1", - "google.golang.org/api/googleapi", - "google.golang.org/api/option", - "gopkg.in/ns1/ns1-go.v2/rest", - "gopkg.in/ns1/ns1-go.v2/rest/model/dns", - "gopkg.in/square/go-jose.v2", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/go-acme/lego/Gopkg.toml b/vendor/github.com/go-acme/lego/Gopkg.toml deleted file mode 100644 index f24172e..0000000 --- a/vendor/github.com/go-acme/lego/Gopkg.toml +++ /dev/null @@ -1,111 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - -[prune] - non-go = true - go-tests = true - unused-packages = true - -[[constraint]] - branch = "master" - name = "github.com/decker502/dnspod-go" - -[[constraint]] - version = "0.21.0" - name = "github.com/dnsimple/dnsimple-go" - -[[constraint]] - branch = "master" - name = "github.com/namedotcom/go" - -[[constraint]] - branch = "master" - name = "github.com/ovh/go-ovh" - -[[constraint]] - branch = "master" - name = "github.com/rainycape/memcache" - -[[constraint]] - branch = "master" - name = "github.com/timewasted/linode" - -[[constraint]] - version = "0.6.0" - name = "github.com/nrdcg/goinwx" - -[[constraint]] - version = "0.5.1" - name = "github.com/linode/linodego" - -[[constraint]] - branch = "master" - name = "golang.org/x/crypto" - -[[constraint]] - branch = "master" - name = "golang.org/x/net" - -[[constraint]] - branch = "master" - name = "golang.org/x/oauth2" - -[[constraint]] - branch = "master" - name = "google.golang.org/api" - -[[constraint]] - branch = "v2" - name = "gopkg.in/ns1/ns1-go.v2" - -[[constraint]] - version = "1.19.0" - name = "github.com/sacloud/libsacloud" - -[[constraint]] - branch = "master" - name = "github.com/transip/gotransip" - -[[constraint]] - version = "0.14.0" - name = "github.com/exoscale/egoscale" - -[[constraint]] - version = "v1.1.0" - name = "github.com/miekg/dns" - -[[constraint]] - version = "v0.7.3" - name = "github.com/akamai/AkamaiOPEN-edgegrid-golang" - -[[constraint]] - version = "4.0.0" - name = "github.com/oracle/oci-go-sdk" - - -[[constraint]] - name = "github.com/labbsr0x/bindman-dns-webhook" - version = "1.0.0" diff --git a/vendor/github.com/go-acme/lego/LICENSE b/vendor/github.com/go-acme/lego/LICENSE deleted file mode 100644 index 270cba0..0000000 --- a/vendor/github.com/go-acme/lego/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2017 Sebastian Erhart - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/Makefile b/vendor/github.com/go-acme/lego/Makefile deleted file mode 100644 index 745012d..0000000 --- a/vendor/github.com/go-acme/lego/Makefile +++ /dev/null @@ -1,85 +0,0 @@ -.PHONY: clean checks test build image dependencies e2e fmt - -SRCS = $(shell git ls-files '*.go' | grep -v '^vendor/') - -LEGO_IMAGE := go-acme/lego -MAIN_DIRECTORY := ./cmd/lego/ -ifeq (${GOOS}, windows) - BIN_OUTPUT := dist/lego.exe -else - BIN_OUTPUT := dist/lego -endif - -TAG_NAME := $(shell git tag -l --contains HEAD) -SHA := $(shell git rev-parse HEAD) -VERSION := $(if $(TAG_NAME),$(TAG_NAME),$(SHA)) - -default: clean generate-dns checks test build - -clean: - rm -rf dist/ builds/ cover.out - -build: clean - @echo Version: $(VERSION) - go build -v -ldflags '-X "main.version=${VERSION}"' -o ${BIN_OUTPUT} ${MAIN_DIRECTORY} - -image: - @echo Version: $(VERSION) - docker build -t $(LEGO_IMAGE) . - -dependencies: - dep ensure -v - -test: clean - go test -v -cover ./... - -e2e: clean - LEGO_E2E_TESTS=local go test -count=1 -v ./e2e/... - -checks: - golangci-lint run - -fmt: - gofmt -s -l -w $(SRCS) - -# Release helper -.PHONY: patch minor major detach - -patch: - go run internal/release.go release -m patch - -minor: - go run internal/release.go release -m minor - -major: - go run internal/release.go release -m major - -detach: - go run internal/release.go detach - -# Docs -.PHONY: docs-build docs-serve docs-themes - -docs-build: generate-dns - @make -C ./docs hugo-build - -docs-serve: generate-dns - @make -C ./docs hugo - -docs-themes: - @make -C ./docs hugo-themes - -# DNS Documentation -.PHONY: generate-dns validate-doc - -generate-dns: - go generate ./... - -validate-doc: generate-dns -ifneq ($(shell git status --porcelain -- ./docs/ ./cmd/ 2>/dev/null),) - @echo 'The documentation must be regenerated, please use `make generate-dns`.' - @git status --porcelain -- ./docs/ ./cmd/ 2>/dev/null - @exit 2 -else - @echo 'All documentation changes are done the right way.' -endif diff --git a/vendor/github.com/go-acme/lego/README.md b/vendor/github.com/go-acme/lego/README.md deleted file mode 100644 index be621b0..0000000 --- a/vendor/github.com/go-acme/lego/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# lego - -Let's Encrypt client and ACME library written in Go. - -[![GoDoc](https://godoc.org/github.com/go-acme/lego?status.svg)](https://godoc.org/github.com/go-acme/lego/acme) -[![Build Status](https://travis-ci.com/go-acme/lego.svg?branch=master)](https://travis-ci.com/go-acme/lego) -[![Docker Pulls](https://img.shields.io/docker/pulls/goacme/lego.svg)](https://hub.docker.com/r/goacme/lego/) - -## Features - -- Register with CA -- Obtain certificates, both from scratch or with an existing CSR -- Renew certificates -- Revoke certificates -- Robust implementation of all ACME challenges - - HTTP (http-01) - - DNS (dns-01) - - TLS (tls-alpn-01) -- SAN certificate support -- Comes with multiple optional [DNS providers](https://go-acme.github.io/lego/dns) -- [Custom challenge solvers](https://go-acme.github.io/lego/usage/library/writing-a-challenge-solver/) -- Certificate bundling -- OCSP helper function - -lego introduced support for ACME v2 in [v1.0.0](https://github.com/go-acme/lego/releases/tag/v1.0.0). If you still need to utilize ACME v1, you can do so by using the [v0.5.0](https://github.com/go-acme/lego/releases/tag/v0.5.0) version. - -## Installation - -How to [install](https://go-acme.github.io/lego/installation/). - -## Usage - -- as a [CLI](https://go-acme.github.io/lego/usage/cli) -- as a [library](https://go-acme.github.io/lego/usage/library) - -## Documentation - -Documentation is hosted live at https://go-acme.github.io/lego/. - -## DNS providers - -Detailed documentation is available [here](https://go-acme.github.io/lego/dns). - -| | | | | -|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------| -| [Alibaba Cloud DNS](https://go-acme.github.io/lego/dns/alidns/) | [Amazon Lightsail](https://go-acme.github.io/lego/dns/lightsail/) | [Amazon Route 53](https://go-acme.github.io/lego/dns/route53/) | [Aurora DNS](https://go-acme.github.io/lego/dns/auroradns/) | -| [Azure](https://go-acme.github.io/lego/dns/azure/) | [Bindman](https://go-acme.github.io/lego/dns/bindman/) | [Bluecat](https://go-acme.github.io/lego/dns/bluecat/) | [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) | -| [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) | [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) | [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | -| [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | [DNSPod](https://go-acme.github.io/lego/dns/dnspod/) | -| [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | [Dyn](https://go-acme.github.io/lego/dns/dyn/) | -| [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) | [External program](https://go-acme.github.io/lego/dns/exec/) | [FastDNS](https://go-acme.github.io/lego/dns/fastdns/) | -| [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) | [Gandi](https://go-acme.github.io/lego/dns/gandi/) | [Glesys](https://go-acme.github.io/lego/dns/glesys/) | [Go Daddy](https://go-acme.github.io/lego/dns/godaddy/) | -| [Google Cloud](https://go-acme.github.io/lego/dns/gcloud/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) | -| [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns) | [Linode (deprecated)](https://go-acme.github.io/lego/dns/linode/) | -| [Linode (v4)](https://go-acme.github.io/lego/dns/linodev4/) | [Manual](https://go-acme.github.io/lego/dns/manual/) | [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | [Name.com](https://go-acme.github.io/lego/dns/namedotcom/) | -| [Namecheap](https://go-acme.github.io/lego/dns/namecheap/) | [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) | [NS1](https://go-acme.github.io/lego/dns/ns1/) | -| [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) | [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | [OVH](https://go-acme.github.io/lego/dns/ovh/) | [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | -| [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Selectel](https://go-acme.github.io/lego/dns/selectel/) | -| [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) | -| [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | | | diff --git a/vendor/github.com/go-acme/lego/acme/api/account.go b/vendor/github.com/go-acme/lego/acme/api/account.go deleted file mode 100644 index fd23314..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/account.go +++ /dev/null @@ -1,69 +0,0 @@ -package api - -import ( - "encoding/base64" - "errors" - "fmt" - - "github.com/go-acme/lego/acme" -) - -type AccountService service - -// New Creates a new account. -func (a *AccountService) New(req acme.Account) (acme.ExtendedAccount, error) { - var account acme.Account - resp, err := a.core.post(a.core.GetDirectory().NewAccountURL, req, &account) - location := getLocation(resp) - - if len(location) > 0 { - a.core.jws.SetKid(location) - } - - if err != nil { - return acme.ExtendedAccount{Location: location}, err - } - - return acme.ExtendedAccount{Account: account, Location: location}, nil -} - -// NewEAB Creates a new account with an External Account Binding. -func (a *AccountService) NewEAB(accMsg acme.Account, kid string, hmacEncoded string) (acme.ExtendedAccount, error) { - hmac, err := base64.RawURLEncoding.DecodeString(hmacEncoded) - if err != nil { - return acme.ExtendedAccount{}, fmt.Errorf("acme: could not decode hmac key: %v", err) - } - - eabJWS, err := a.core.signEABContent(a.core.GetDirectory().NewAccountURL, kid, hmac) - if err != nil { - return acme.ExtendedAccount{}, fmt.Errorf("acme: error signing eab content: %v", err) - } - accMsg.ExternalAccountBinding = eabJWS - - return a.New(accMsg) -} - -// Get Retrieves an account. -func (a *AccountService) Get(accountURL string) (acme.Account, error) { - if len(accountURL) == 0 { - return acme.Account{}, errors.New("account[get]: empty URL") - } - - var account acme.Account - _, err := a.core.post(accountURL, acme.Account{}, &account) - if err != nil { - return acme.Account{}, err - } - return account, nil -} - -// Deactivate Deactivates an account. -func (a *AccountService) Deactivate(accountURL string) error { - if len(accountURL) == 0 { - return errors.New("account[deactivate]: empty URL") - } - - req := acme.Account{Status: acme.StatusDeactivated} - _, err := a.core.post(accountURL, req, nil) - return err -} diff --git a/vendor/github.com/go-acme/lego/acme/api/api.go b/vendor/github.com/go-acme/lego/acme/api/api.go deleted file mode 100644 index 912e7c5..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/api.go +++ /dev/null @@ -1,166 +0,0 @@ -package api - -import ( - "bytes" - "context" - "crypto" - "encoding/json" - "errors" - "fmt" - "net/http" - "time" - - "github.com/cenkalti/backoff" - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api/internal/nonces" - "github.com/go-acme/lego/acme/api/internal/secure" - "github.com/go-acme/lego/acme/api/internal/sender" - "github.com/go-acme/lego/log" -) - -// Core ACME/LE core API. -type Core struct { - doer *sender.Doer - nonceManager *nonces.Manager - jws *secure.JWS - directory acme.Directory - HTTPClient *http.Client - - common service // Reuse a single struct instead of allocating one for each service on the heap. - Accounts *AccountService - Authorizations *AuthorizationService - Certificates *CertificateService - Challenges *ChallengeService - Orders *OrderService -} - -// New Creates a new Core. -func New(httpClient *http.Client, userAgent string, caDirURL, kid string, privateKey crypto.PrivateKey) (*Core, error) { - doer := sender.NewDoer(httpClient, userAgent) - - dir, err := getDirectory(doer, caDirURL) - if err != nil { - return nil, err - } - - nonceManager := nonces.NewManager(doer, dir.NewNonceURL) - - jws := secure.NewJWS(privateKey, kid, nonceManager) - - c := &Core{doer: doer, nonceManager: nonceManager, jws: jws, directory: dir, HTTPClient: httpClient} - - c.common.core = c - c.Accounts = (*AccountService)(&c.common) - c.Authorizations = (*AuthorizationService)(&c.common) - c.Certificates = (*CertificateService)(&c.common) - c.Challenges = (*ChallengeService)(&c.common) - c.Orders = (*OrderService)(&c.common) - - return c, nil -} - -// post performs an HTTP POST request and parses the response body as JSON, -// into the provided respBody object. -func (a *Core) post(uri string, reqBody, response interface{}) (*http.Response, error) { - content, err := json.Marshal(reqBody) - if err != nil { - return nil, errors.New("failed to marshal message") - } - - return a.retrievablePost(uri, content, response) -} - -// postAsGet performs an HTTP POST ("POST-as-GET") request. -// https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-6.3 -func (a *Core) postAsGet(uri string, response interface{}) (*http.Response, error) { - return a.retrievablePost(uri, []byte{}, response) -} - -func (a *Core) retrievablePost(uri string, content []byte, response interface{}) (*http.Response, error) { - // during tests, allow to support ~90% of bad nonce with a minimum of attempts. - bo := backoff.NewExponentialBackOff() - bo.InitialInterval = 200 * time.Millisecond - bo.MaxInterval = 5 * time.Second - bo.MaxElapsedTime = 20 * time.Second - - ctx, cancel := context.WithCancel(context.Background()) - - var resp *http.Response - operation := func() error { - var err error - resp, err = a.signedPost(uri, content, response) - if err != nil { - switch err.(type) { - // Retry if the nonce was invalidated - case *acme.NonceError: - log.Infof("nonce error retry: %s", err) - return err - default: - cancel() - return err - } - } - - return nil - } - - err := backoff.Retry(operation, backoff.WithContext(bo, ctx)) - if err != nil { - return nil, err - } - - return resp, nil -} - -func (a *Core) signedPost(uri string, content []byte, response interface{}) (*http.Response, error) { - signedContent, err := a.jws.SignContent(uri, content) - if err != nil { - return nil, fmt.Errorf("failed to post JWS message -> failed to sign content -> %v", err) - } - - signedBody := bytes.NewBuffer([]byte(signedContent.FullSerialize())) - - resp, err := a.doer.Post(uri, signedBody, "application/jose+json", response) - - // nonceErr is ignored to keep the root error. - nonce, nonceErr := nonces.GetFromResponse(resp) - if nonceErr == nil { - a.nonceManager.Push(nonce) - } - - return resp, err -} - -func (a *Core) signEABContent(newAccountURL, kid string, hmac []byte) ([]byte, error) { - eabJWS, err := a.jws.SignEABContent(newAccountURL, kid, hmac) - if err != nil { - return nil, err - } - - return []byte(eabJWS.FullSerialize()), nil -} - -// GetKeyAuthorization Gets the key authorization -func (a *Core) GetKeyAuthorization(token string) (string, error) { - return a.jws.GetKeyAuthorization(token) -} - -func (a *Core) GetDirectory() acme.Directory { - return a.directory -} - -func getDirectory(do *sender.Doer, caDirURL string) (acme.Directory, error) { - var dir acme.Directory - if _, err := do.Get(caDirURL, &dir); err != nil { - return dir, fmt.Errorf("get directory at '%s': %v", caDirURL, err) - } - - if dir.NewAccountURL == "" { - return dir, errors.New("directory missing new registration URL") - } - if dir.NewOrderURL == "" { - return dir, errors.New("directory missing new order URL") - } - - return dir, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/authorization.go b/vendor/github.com/go-acme/lego/acme/api/authorization.go deleted file mode 100644 index a59fa0d..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/authorization.go +++ /dev/null @@ -1,34 +0,0 @@ -package api - -import ( - "errors" - - "github.com/go-acme/lego/acme" -) - -type AuthorizationService service - -// Get Gets an authorization. -func (c *AuthorizationService) Get(authzURL string) (acme.Authorization, error) { - if len(authzURL) == 0 { - return acme.Authorization{}, errors.New("authorization[get]: empty URL") - } - - var authz acme.Authorization - _, err := c.core.postAsGet(authzURL, &authz) - if err != nil { - return acme.Authorization{}, err - } - return authz, nil -} - -// Deactivate Deactivates an authorization. -func (c *AuthorizationService) Deactivate(authzURL string) error { - if len(authzURL) == 0 { - return errors.New("authorization[deactivate]: empty URL") - } - - var disabledAuth acme.Authorization - _, err := c.core.post(authzURL, acme.Authorization{Status: acme.StatusDeactivated}, &disabledAuth) - return err -} diff --git a/vendor/github.com/go-acme/lego/acme/api/certificate.go b/vendor/github.com/go-acme/lego/acme/api/certificate.go deleted file mode 100644 index 65904e7..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/certificate.go +++ /dev/null @@ -1,99 +0,0 @@ -package api - -import ( - "crypto/x509" - "encoding/pem" - "errors" - "io/ioutil" - "net/http" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/log" -) - -// maxBodySize is the maximum size of body that we will read. -const maxBodySize = 1024 * 1024 - -type CertificateService service - -// Get Returns the certificate and the issuer certificate. -// 'bundle' is only applied if the issuer is provided by the 'up' link. -func (c *CertificateService) Get(certURL string, bundle bool) ([]byte, []byte, error) { - cert, up, err := c.get(certURL) - if err != nil { - return nil, nil, err - } - - // Get issuerCert from bundled response from Let's Encrypt - // See https://community.letsencrypt.org/t/acme-v2-no-up-link-in-response/64962 - _, issuer := pem.Decode(cert) - if issuer != nil { - return cert, issuer, nil - } - - issuer, err = c.getIssuerFromLink(up) - if err != nil { - // If we fail to acquire the issuer cert, return the issued certificate - do not fail. - log.Warnf("acme: Could not bundle issuer certificate [%s]: %v", certURL, err) - } else if len(issuer) > 0 { - // If bundle is true, we want to return a certificate bundle. - // To do this, we append the issuer cert to the issued cert. - if bundle { - cert = append(cert, issuer...) - } - } - - return cert, issuer, nil -} - -// Revoke Revokes a certificate. -func (c *CertificateService) Revoke(req acme.RevokeCertMessage) error { - _, err := c.core.post(c.core.GetDirectory().RevokeCertURL, req, nil) - return err -} - -// get Returns the certificate and the "up" link. -func (c *CertificateService) get(certURL string) ([]byte, string, error) { - if len(certURL) == 0 { - return nil, "", errors.New("certificate[get]: empty URL") - } - - resp, err := c.core.postAsGet(certURL, nil) - if err != nil { - return nil, "", err - } - - cert, err := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize)) - if err != nil { - return nil, "", err - } - - // The issuer certificate link may be supplied via an "up" link - // in the response headers of a new certificate. - // See https://tools.ietf.org/html/draft-ietf-acme-acme-12#section-7.4.2 - up := getLink(resp.Header, "up") - - return cert, up, err -} - -// getIssuerFromLink requests the issuer certificate -func (c *CertificateService) getIssuerFromLink(up string) ([]byte, error) { - if len(up) == 0 { - return nil, nil - } - - log.Infof("acme: Requesting issuer cert from %s", up) - - cert, _, err := c.get(up) - if err != nil { - return nil, err - } - - _, err = x509.ParseCertificate(cert) - if err != nil { - return nil, err - } - - return certcrypto.PEMEncode(certcrypto.DERCertificateBytes(cert)), nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/certificate_test.go b/vendor/github.com/go-acme/lego/acme/api/certificate_test.go deleted file mode 100644 index f52774b..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/certificate_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package api - -import ( - "crypto/rand" - "crypto/rsa" - "encoding/pem" - "net/http" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const certResponseMock = `-----BEGIN CERTIFICATE----- -MIIDEDCCAfigAwIBAgIHPhckqW5fPDANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQD -Ex1QZWJibGUgSW50ZXJtZWRpYXRlIENBIDM5NWU2MTAeFw0xODExMDcxNzQ2NTZa -Fw0yMzExMDcxNzQ2NTZaMBMxETAPBgNVBAMTCGFjbWUud3RmMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwtLNKvZXD20XPUQCWYSK9rUSKxD9Eb0c9fag -bxOxOkLRTgL8LH6yln+bxc3MrHDou4PpDUdeo2CyOQu3CKsTS5mrH3NXYHu0H7p5 -y3riOJTHnfkGKLT9LciGz7GkXd62nvNP57bOf5Sk4P2M+Qbxd0hPTSfu52740LSy -144cnxe2P1aDYehrEp6nYCESuyD/CtUHTo0qwJmzIy163Sp3rSs15BuCPyhySnE3 -BJ8Ggv+qC6D5I1932DfSqyQJ79iq/HRm0Fn84am3KwvRlUfWxabmsUGARXoqCgnE -zcbJVOZKewv0zlQJpfac+b+Imj6Lvt1TGjIz2mVyefYgLx8gwwIDAQABo1QwUjAO -BgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG -A1UdEwEB/wQCMAAwEwYDVR0RBAwwCoIIYWNtZS53dGYwDQYJKoZIhvcNAQELBQAD -ggEBABB/0iYhmfPSQot5RaeeovQnsqYjI5ryQK2cwzW6qcTJfv8N6+p6XkqF1+W4 -jXZjrQP8MvgO9KNWlvx12vhINE6wubk88L+2piAi5uS2QejmZbXpyYB9s+oPqlk9 -IDvfdlVYOqvYAhSx7ggGi+j73mjZVtjAavP6dKuu475ZCeq+NIC15RpbbikWKtYE -HBJ7BW8XQKx67iHGx8ygHTDLbREL80Bck3oUm7wIYGMoNijD6RBl25p4gYl9dzOd -TqGl5hW/1P5hMbgEzHbr4O3BfWqU2g7tV36TASy3jbC3ONFRNNYrpEZ1AL3+cUri -OPPkKtAKAbQkKbUIfsHpBZjKZMU= ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE -AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw -NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl -NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT -SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh -0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen -SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx -HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt -D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu -mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD -AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA -upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm -iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd -QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ -wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv -rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2 -7R4IbHGnj0BJA2vMYC4hSw== ------END CERTIFICATE----- -` - -const issuerMock = `-----BEGIN CERTIFICATE----- -MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE -AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw -NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl -NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT -SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh -0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen -SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx -HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt -D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu -mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD -AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA -upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm -iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd -QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ -wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv -rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2 -7R4IbHGnj0BJA2vMYC4hSw== ------END CERTIFICATE----- -` - -func TestCertificateService_Get_issuerRelUp(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`) - _, err := w.Write([]byte(certResponseMock)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - mux.HandleFunc("/issuer", func(w http.ResponseWriter, _ *http.Request) { - p, _ := pem.Decode([]byte(issuerMock)) - _, err := w.Write(p.Bytes) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - cert, issuer, err := core.Certificates.Get(apiURL+"/certificate", true) - require.NoError(t, err) - assert.Equal(t, certResponseMock, string(cert), "Certificate") - assert.Equal(t, issuerMock, string(issuer), "IssuerCertificate") -} - -func TestCertificateService_Get_embeddedIssuer(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { - _, err := w.Write([]byte(certResponseMock)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - cert, issuer, err := core.Certificates.Get(apiURL+"/certificate", true) - require.NoError(t, err) - assert.Equal(t, certResponseMock, string(cert), "Certificate") - assert.Equal(t, issuerMock, string(issuer), "IssuerCertificate") -} diff --git a/vendor/github.com/go-acme/lego/acme/api/challenge.go b/vendor/github.com/go-acme/lego/acme/api/challenge.go deleted file mode 100644 index f4e8dbe..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/challenge.go +++ /dev/null @@ -1,45 +0,0 @@ -package api - -import ( - "errors" - - "github.com/go-acme/lego/acme" -) - -type ChallengeService service - -// New Creates a challenge. -func (c *ChallengeService) New(chlgURL string) (acme.ExtendedChallenge, error) { - if len(chlgURL) == 0 { - return acme.ExtendedChallenge{}, errors.New("challenge[new]: empty URL") - } - - // Challenge initiation is done by sending a JWS payload containing the trivial JSON object `{}`. - // We use an empty struct instance as the postJSON payload here to achieve this result. - var chlng acme.ExtendedChallenge - resp, err := c.core.post(chlgURL, struct{}{}, &chlng) - if err != nil { - return acme.ExtendedChallenge{}, err - } - - chlng.AuthorizationURL = getLink(resp.Header, "up") - chlng.RetryAfter = getRetryAfter(resp) - return chlng, nil -} - -// Get Gets a challenge. -func (c *ChallengeService) Get(chlgURL string) (acme.ExtendedChallenge, error) { - if len(chlgURL) == 0 { - return acme.ExtendedChallenge{}, errors.New("challenge[get]: empty URL") - } - - var chlng acme.ExtendedChallenge - resp, err := c.core.postAsGet(chlgURL, &chlng) - if err != nil { - return acme.ExtendedChallenge{}, err - } - - chlng.AuthorizationURL = getLink(resp.Header, "up") - chlng.RetryAfter = getRetryAfter(resp) - return chlng, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager.go b/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager.go deleted file mode 100644 index c08f6d4..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager.go +++ /dev/null @@ -1,78 +0,0 @@ -package nonces - -import ( - "errors" - "fmt" - "net/http" - "sync" - - "github.com/go-acme/lego/acme/api/internal/sender" -) - -// Manager Manages nonces. -type Manager struct { - do *sender.Doer - nonceURL string - nonces []string - sync.Mutex -} - -// NewManager Creates a new Manager. -func NewManager(do *sender.Doer, nonceURL string) *Manager { - return &Manager{ - do: do, - nonceURL: nonceURL, - } -} - -// Pop Pops a nonce. -func (n *Manager) Pop() (string, bool) { - n.Lock() - defer n.Unlock() - - if len(n.nonces) == 0 { - return "", false - } - - nonce := n.nonces[len(n.nonces)-1] - n.nonces = n.nonces[:len(n.nonces)-1] - return nonce, true -} - -// Push Pushes a nonce. -func (n *Manager) Push(nonce string) { - n.Lock() - defer n.Unlock() - n.nonces = append(n.nonces, nonce) -} - -// Nonce implement jose.NonceSource -func (n *Manager) Nonce() (string, error) { - if nonce, ok := n.Pop(); ok { - return nonce, nil - } - return n.getNonce() -} - -func (n *Manager) getNonce() (string, error) { - resp, err := n.do.Head(n.nonceURL) - if err != nil { - return "", fmt.Errorf("failed to get nonce from HTTP HEAD -> %v", err) - } - - return GetFromResponse(resp) -} - -// GetFromResponse Extracts a nonce from a HTTP response. -func GetFromResponse(resp *http.Response) (string, error) { - if resp == nil { - return "", errors.New("nil response") - } - - nonce := resp.Header.Get("Replay-Nonce") - if nonce == "" { - return "", fmt.Errorf("server did not respond with a proper nonce header") - } - - return nonce, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager_test.go b/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager_test.go deleted file mode 100644 index 1c56da0..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package nonces - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api/internal/sender" - "github.com/go-acme/lego/platform/tester" -) - -func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - time.Sleep(250 * time.Millisecond) - w.Header().Add("Replay-Nonce", "12345") - w.Header().Add("Retry-After", "0") - err := tester.WriteJSONResponse(w, &acme.Challenge{Type: "http-01", Status: "Valid", URL: "http://example.com/", Token: "token"}) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - })) - defer ts.Close() - - doer := sender.NewDoer(http.DefaultClient, "lego-test") - j := NewManager(doer, ts.URL) - ch := make(chan bool) - resultCh := make(chan bool) - go func() { - _, errN := j.Nonce() - if errN != nil { - t.Log(errN) - } - ch <- true - }() - go func() { - _, errN := j.Nonce() - if errN != nil { - t.Log(errN) - } - ch <- true - }() - go func() { - <-ch - <-ch - resultCh <- true - }() - select { - case <-resultCh: - case <-time.After(400 * time.Millisecond): - t.Fatal("JWS is probably holding a lock while making HTTP request") - } -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws.go b/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws.go deleted file mode 100644 index 213aeda..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws.go +++ /dev/null @@ -1,130 +0,0 @@ -package secure - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "encoding/base64" - "fmt" - - "github.com/go-acme/lego/acme/api/internal/nonces" - jose "gopkg.in/square/go-jose.v2" -) - -// JWS Represents a JWS. -type JWS struct { - privKey crypto.PrivateKey - kid string // Key identifier - nonces *nonces.Manager -} - -// NewJWS Create a new JWS. -func NewJWS(privateKey crypto.PrivateKey, kid string, nonceManager *nonces.Manager) *JWS { - return &JWS{ - privKey: privateKey, - nonces: nonceManager, - kid: kid, - } -} - -// SetKid Sets a key identifier. -func (j *JWS) SetKid(kid string) { - j.kid = kid -} - -// SignContent Signs a content with the JWS. -func (j *JWS) SignContent(url string, content []byte) (*jose.JSONWebSignature, error) { - var alg jose.SignatureAlgorithm - switch k := j.privKey.(type) { - case *rsa.PrivateKey: - alg = jose.RS256 - case *ecdsa.PrivateKey: - if k.Curve == elliptic.P256() { - alg = jose.ES256 - } else if k.Curve == elliptic.P384() { - alg = jose.ES384 - } - } - - signKey := jose.SigningKey{ - Algorithm: alg, - Key: jose.JSONWebKey{Key: j.privKey, KeyID: j.kid}, - } - - options := jose.SignerOptions{ - NonceSource: j.nonces, - ExtraHeaders: map[jose.HeaderKey]interface{}{ - "url": url, - }, - } - - if j.kid == "" { - options.EmbedJWK = true - } - - signer, err := jose.NewSigner(signKey, &options) - if err != nil { - return nil, fmt.Errorf("failed to create jose signer -> %v", err) - } - - signed, err := signer.Sign(content) - if err != nil { - return nil, fmt.Errorf("failed to sign content -> %v", err) - } - return signed, nil -} - -// SignEABContent Signs an external account binding content with the JWS. -func (j *JWS) SignEABContent(url, kid string, hmac []byte) (*jose.JSONWebSignature, error) { - jwk := jose.JSONWebKey{Key: j.privKey} - jwkJSON, err := jwk.Public().MarshalJSON() - if err != nil { - return nil, fmt.Errorf("acme: error encoding eab jwk key: %v", err) - } - - signer, err := jose.NewSigner( - jose.SigningKey{Algorithm: jose.HS256, Key: hmac}, - &jose.SignerOptions{ - EmbedJWK: false, - ExtraHeaders: map[jose.HeaderKey]interface{}{ - "kid": kid, - "url": url, - }, - }, - ) - if err != nil { - return nil, fmt.Errorf("failed to create External Account Binding jose signer -> %v", err) - } - - signed, err := signer.Sign(jwkJSON) - if err != nil { - return nil, fmt.Errorf("failed to External Account Binding sign content -> %v", err) - } - - return signed, nil -} - -// GetKeyAuthorization Gets the key authorization for a token. -func (j *JWS) GetKeyAuthorization(token string) (string, error) { - var publicKey crypto.PublicKey - switch k := j.privKey.(type) { - case *ecdsa.PrivateKey: - publicKey = k.Public() - case *rsa.PrivateKey: - publicKey = k.Public() - } - - // Generate the Key Authorization for the challenge - jwk := &jose.JSONWebKey{Key: publicKey} - - thumbBytes, err := jwk.Thumbprint(crypto.SHA256) - if err != nil { - return "", err - } - - // unpad the base64URL - keyThumb := base64.RawURLEncoding.EncodeToString(thumbBytes) - - return token + "." + keyThumb, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws_test.go b/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws_test.go deleted file mode 100644 index ee4ec9d..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package secure - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api/internal/nonces" - "github.com/go-acme/lego/acme/api/internal/sender" - "github.com/go-acme/lego/platform/tester" -) - -func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - time.Sleep(250 * time.Millisecond) - w.Header().Add("Replay-Nonce", "12345") - w.Header().Add("Retry-After", "0") - err := tester.WriteJSONResponse(w, &acme.Challenge{Type: "http-01", Status: "Valid", URL: "http://example.com/", Token: "token"}) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - })) - defer ts.Close() - - doer := sender.NewDoer(http.DefaultClient, "lego-test") - j := nonces.NewManager(doer, ts.URL) - ch := make(chan bool) - resultCh := make(chan bool) - go func() { - _, errN := j.Nonce() - if errN != nil { - t.Log(errN) - } - ch <- true - }() - go func() { - _, errN := j.Nonce() - if errN != nil { - t.Log(errN) - } - ch <- true - }() - go func() { - <-ch - <-ch - resultCh <- true - }() - select { - case <-resultCh: - case <-time.After(400 * time.Millisecond): - t.Fatal("JWS is probably holding a lock while making HTTP request") - } -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender.go b/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender.go deleted file mode 100644 index e08f2ff..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender.go +++ /dev/null @@ -1,146 +0,0 @@ -package sender - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "runtime" - "strings" - - "github.com/go-acme/lego/acme" -) - -type RequestOption func(*http.Request) error - -func contentType(ct string) RequestOption { - return func(req *http.Request) error { - req.Header.Set("Content-Type", ct) - return nil - } -} - -type Doer struct { - httpClient *http.Client - userAgent string -} - -// NewDoer Creates a new Doer. -func NewDoer(client *http.Client, userAgent string) *Doer { - return &Doer{ - httpClient: client, - userAgent: userAgent, - } -} - -// Get performs a GET request with a proper User-Agent string. -// If "response" is not provided, callers should close resp.Body when done reading from it. -func (d *Doer) Get(url string, response interface{}) (*http.Response, error) { - req, err := d.newRequest(http.MethodGet, url, nil) - if err != nil { - return nil, err - } - - return d.do(req, response) -} - -// Head performs a HEAD request with a proper User-Agent string. -// The response body (resp.Body) is already closed when this function returns. -func (d *Doer) Head(url string) (*http.Response, error) { - req, err := d.newRequest(http.MethodHead, url, nil) - if err != nil { - return nil, err - } - - return d.do(req, nil) -} - -// Post performs a POST request with a proper User-Agent string. -// If "response" is not provided, callers should close resp.Body when done reading from it. -func (d *Doer) Post(url string, body io.Reader, bodyType string, response interface{}) (*http.Response, error) { - req, err := d.newRequest(http.MethodPost, url, body, contentType(bodyType)) - if err != nil { - return nil, err - } - - return d.do(req, response) -} - -func (d *Doer) newRequest(method, uri string, body io.Reader, opts ...RequestOption) (*http.Request, error) { - req, err := http.NewRequest(method, uri, body) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - req.Header.Set("User-Agent", d.formatUserAgent()) - - for _, opt := range opts { - err = opt(req) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - } - - return req, nil -} - -func (d *Doer) do(req *http.Request, response interface{}) (*http.Response, error) { - resp, err := d.httpClient.Do(req) - if err != nil { - return nil, err - } - - if err = checkError(req, resp); err != nil { - return resp, err - } - - if response != nil { - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return resp, err - } - - defer resp.Body.Close() - - err = json.Unmarshal(raw, response) - if err != nil { - return resp, fmt.Errorf("failed to unmarshal %q to type %T: %v", raw, response, err) - } - } - - return resp, nil -} - -// formatUserAgent builds and returns the User-Agent string to use in requests. -func (d *Doer) formatUserAgent() string { - ua := fmt.Sprintf("%s %s (%s; %s; %s)", d.userAgent, ourUserAgent, ourUserAgentComment, runtime.GOOS, runtime.GOARCH) - return strings.TrimSpace(ua) -} - -func checkError(req *http.Request, resp *http.Response) error { - if resp.StatusCode >= http.StatusBadRequest { - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("%d :: %s :: %s :: %v", resp.StatusCode, req.Method, req.URL, err) - } - - var errorDetails *acme.ProblemDetails - err = json.Unmarshal(body, &errorDetails) - if err != nil { - return fmt.Errorf("%d ::%s :: %s :: %v :: %s", resp.StatusCode, req.Method, req.URL, err, string(body)) - } - - errorDetails.Method = req.Method - errorDetails.URL = req.URL.String() - - // Check for errors we handle specifically - if errorDetails.HTTPStatus == http.StatusBadRequest && errorDetails.Type == acme.BadNonceErr { - return &acme.NonceError{ProblemDetails: errorDetails} - } - - return errorDetails - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender_test.go b/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender_test.go deleted file mode 100644 index 0ab0225..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package sender - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) { - var ua, method string - ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { - ua = r.Header.Get("User-Agent") - method = r.Method - })) - defer ts.Close() - - doer := NewDoer(http.DefaultClient, "") - - testCases := []struct { - method string - call func(u string) (*http.Response, error) - }{ - { - method: http.MethodGet, - call: func(u string) (*http.Response, error) { - return doer.Get(u, nil) - }, - }, - { - method: http.MethodHead, - call: doer.Head, - }, - { - method: http.MethodPost, - call: func(u string) (*http.Response, error) { - return doer.Post(u, strings.NewReader("falalalala"), "text/plain", nil) - }, - }, - } - - for _, test := range testCases { - t.Run(test.method, func(t *testing.T) { - - _, err := test.call(ts.URL) - require.NoError(t, err) - - assert.Equal(t, test.method, method) - assert.Contains(t, ua, ourUserAgent, "User-Agent") - }) - } -} - -func TestDo_CustomUserAgent(t *testing.T) { - customUA := "MyApp/1.2.3" - doer := NewDoer(http.DefaultClient, customUA) - - ua := doer.formatUserAgent() - assert.Contains(t, ua, ourUserAgent) - assert.Contains(t, ua, customUA) - if strings.HasSuffix(ua, " ") { - t.Errorf("UA should not have trailing spaces; got '%s'", ua) - } - assert.Len(t, strings.Split(ua, " "), 5) -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/sender/useragent.go b/vendor/github.com/go-acme/lego/acme/api/internal/sender/useragent.go deleted file mode 100644 index 5f52f36..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/sender/useragent.go +++ /dev/null @@ -1,14 +0,0 @@ -package sender - -// CODE GENERATED AUTOMATICALLY -// THIS FILE MUST NOT BE EDITED BY HAND - -const ( - // ourUserAgent is the User-Agent of this underlying library package. - ourUserAgent = "xenolf-acme/2.6.0" - - // ourUserAgentComment is part of the UA comment linked to the version status of this underlying library package. - // values: detach|release - // NOTE: Update this with each tagged release. - ourUserAgentComment = "detach" -) diff --git a/vendor/github.com/go-acme/lego/acme/api/order.go b/vendor/github.com/go-acme/lego/acme/api/order.go deleted file mode 100644 index 11240b4..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/order.go +++ /dev/null @@ -1,65 +0,0 @@ -package api - -import ( - "encoding/base64" - "errors" - - "github.com/go-acme/lego/acme" -) - -type OrderService service - -// New Creates a new order. -func (o *OrderService) New(domains []string) (acme.ExtendedOrder, error) { - var identifiers []acme.Identifier - for _, domain := range domains { - identifiers = append(identifiers, acme.Identifier{Type: "dns", Value: domain}) - } - - orderReq := acme.Order{Identifiers: identifiers} - - var order acme.Order - resp, err := o.core.post(o.core.GetDirectory().NewOrderURL, orderReq, &order) - if err != nil { - return acme.ExtendedOrder{}, err - } - - return acme.ExtendedOrder{ - Location: resp.Header.Get("Location"), - Order: order, - }, nil -} - -// Get Gets an order. -func (o *OrderService) Get(orderURL string) (acme.Order, error) { - if len(orderURL) == 0 { - return acme.Order{}, errors.New("order[get]: empty URL") - } - - var order acme.Order - _, err := o.core.postAsGet(orderURL, &order) - if err != nil { - return acme.Order{}, err - } - - return order, nil -} - -// UpdateForCSR Updates an order for a CSR. -func (o *OrderService) UpdateForCSR(orderURL string, csr []byte) (acme.Order, error) { - csrMsg := acme.CSRMessage{ - Csr: base64.RawURLEncoding.EncodeToString(csr), - } - - var order acme.Order - _, err := o.core.post(orderURL, csrMsg, &order) - if err != nil { - return acme.Order{}, err - } - - if order.Status == acme.StatusInvalid { - return acme.Order{}, order.Error - } - - return order, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/order_test.go b/vendor/github.com/go-acme/lego/acme/api/order_test.go deleted file mode 100644 index da12cee..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/order_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package api - -import ( - "crypto/rand" - "crypto/rsa" - "encoding/json" - "io/ioutil" - "net/http" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - jose "gopkg.in/square/go-jose.v2" -) - -func TestOrderService_New(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - // small value keeps test fast - privateKey, errK := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, errK, "Could not generate test key") - - mux.HandleFunc("/newOrder", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - body, err := readSignedBody(r, privateKey) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - } - - order := acme.Order{} - err = json.Unmarshal(body, &order) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - err = tester.WriteJSONResponse(w, acme.Order{ - Status: acme.StatusValid, - Identifiers: order.Identifiers, - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - order, err := core.Orders.New([]string{"example.com"}) - require.NoError(t, err) - - expected := acme.ExtendedOrder{ - Order: acme.Order{ - Status: "valid", - Identifiers: []acme.Identifier{{Type: "dns", Value: "example.com"}}, - }, - } - assert.Equal(t, expected, order) -} - -func readSignedBody(r *http.Request, privateKey *rsa.PrivateKey) ([]byte, error) { - reqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - return nil, err - } - - jws, err := jose.ParseSigned(string(reqBody)) - if err != nil { - return nil, err - } - - body, err := jws.Verify(&jose.JSONWebKey{ - Key: privateKey.Public(), - Algorithm: "RSA", - }) - if err != nil { - return nil, err - } - - return body, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/service.go b/vendor/github.com/go-acme/lego/acme/api/service.go deleted file mode 100644 index ff043bc..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/service.go +++ /dev/null @@ -1,45 +0,0 @@ -package api - -import ( - "net/http" - "regexp" -) - -type service struct { - core *Core -} - -// getLink get a rel into the Link header -func getLink(header http.Header, rel string) string { - var linkExpr = regexp.MustCompile(`<(.+?)>;\s*rel="(.+?)"`) - - for _, link := range header["Link"] { - for _, m := range linkExpr.FindAllStringSubmatch(link, -1) { - if len(m) != 3 { - continue - } - if m[2] == rel { - return m[1] - } - } - } - return "" -} - -// getLocation get the value of the header Location -func getLocation(resp *http.Response) string { - if resp == nil { - return "" - } - - return resp.Header.Get("Location") -} - -// getRetryAfter get the value of the header Retry-After -func getRetryAfter(resp *http.Response) string { - if resp == nil { - return "" - } - - return resp.Header.Get("Retry-After") -} diff --git a/vendor/github.com/go-acme/lego/acme/api/service_test.go b/vendor/github.com/go-acme/lego/acme/api/service_test.go deleted file mode 100644 index d0095a1..0000000 --- a/vendor/github.com/go-acme/lego/acme/api/service_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package api - -import ( - "net/http" - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_getLink(t *testing.T) { - testCases := []struct { - desc string - header http.Header - relName string - expected string - }{ - { - desc: "success", - header: http.Header{ - "Link": []string{`; rel="next", ; rel="up"`}, - }, - relName: "up", - expected: "https://acme-staging-v02.api.letsencrypt.org/up?query", - }, - { - desc: "success several lines", - header: http.Header{ - "Link": []string{`; rel="next"`, `; rel="up"`}, - }, - relName: "up", - expected: "https://acme-staging-v02.api.letsencrypt.org/up?query", - }, - { - desc: "no link", - header: http.Header{}, - relName: "up", - expected: "", - }, - { - desc: "no header", - relName: "up", - expected: "", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - link := getLink(test.header, test.relName) - - assert.Equal(t, test.expected, link) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/acme/commons.go b/vendor/github.com/go-acme/lego/acme/commons.go deleted file mode 100644 index c449369..0000000 --- a/vendor/github.com/go-acme/lego/acme/commons.go +++ /dev/null @@ -1,284 +0,0 @@ -// Package acme contains all objects related the ACME endpoints. -// https://tools.ietf.org/html/draft-ietf-acme-acme-16 -package acme - -import ( - "encoding/json" - "time" -) - -// Challenge statuses -// https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.6 -const ( - StatusPending = "pending" - StatusInvalid = "invalid" - StatusValid = "valid" - StatusProcessing = "processing" - StatusDeactivated = "deactivated" - StatusExpired = "expired" - StatusRevoked = "revoked" -) - -// Directory the ACME directory object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.1 -type Directory struct { - NewNonceURL string `json:"newNonce"` - NewAccountURL string `json:"newAccount"` - NewOrderURL string `json:"newOrder"` - NewAuthzURL string `json:"newAuthz"` - RevokeCertURL string `json:"revokeCert"` - KeyChangeURL string `json:"keyChange"` - Meta Meta `json:"meta"` -} - -// Meta the ACME meta object (related to Directory). -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.1 -type Meta struct { - // termsOfService (optional, string): - // A URL identifying the current terms of service. - TermsOfService string `json:"termsOfService"` - - // website (optional, string): - // An HTTP or HTTPS URL locating a website providing more information about the ACME server. - Website string `json:"website"` - - // caaIdentities (optional, array of string): - // The hostnames that the ACME server recognizes as referring to itself - // for the purposes of CAA record validation as defined in [RFC6844]. - // Each string MUST represent the same sequence of ASCII code points - // that the server will expect to see as the "Issuer Domain Name" in a CAA issue or issuewild property tag. - // This allows clients to determine the correct issuer domain name to use when configuring CAA records. - CaaIdentities []string `json:"caaIdentities"` - - // externalAccountRequired (optional, boolean): - // If this field is present and set to "true", - // then the CA requires that all new- account requests include an "externalAccountBinding" field - // associating the new account with an external account. - ExternalAccountRequired bool `json:"externalAccountRequired"` -} - -// ExtendedAccount a extended Account. -type ExtendedAccount struct { - Account - // Contains the value of the response header `Location` - Location string `json:"-"` -} - -// Account the ACME account Object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.2 -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.3 -type Account struct { - // status (required, string): - // The status of this account. - // Possible values are: "valid", "deactivated", and "revoked". - // The value "deactivated" should be used to indicate client-initiated deactivation - // whereas "revoked" should be used to indicate server- initiated deactivation. (See Section 7.1.6) - Status string `json:"status,omitempty"` - - // contact (optional, array of string): - // An array of URLs that the server can use to contact the client for issues related to this account. - // For example, the server may wish to notify the client about server-initiated revocation or certificate expiration. - // For information on supported URL schemes, see Section 7.3 - Contact []string `json:"contact,omitempty"` - - // termsOfServiceAgreed (optional, boolean): - // Including this field in a new-account request, - // with a value of true, indicates the client's agreement with the terms of service. - // This field is not updateable by the client. - TermsOfServiceAgreed bool `json:"termsOfServiceAgreed,omitempty"` - - // orders (required, string): - // A URL from which a list of orders submitted by this account can be fetched via a POST-as-GET request, - // as described in Section 7.1.2.1. - Orders string `json:"orders,omitempty"` - - // onlyReturnExisting (optional, boolean): - // If this field is present with the value "true", - // then the server MUST NOT create a new account if one does not already exist. - // This allows a client to look up an account URL based on an account key (see Section 7.3.1). - OnlyReturnExisting bool `json:"onlyReturnExisting,omitempty"` - - // externalAccountBinding (optional, object): - // An optional field for binding the new account with an existing non-ACME account (see Section 7.3.4). - ExternalAccountBinding json.RawMessage `json:"externalAccountBinding,omitempty"` -} - -// ExtendedOrder a extended Order. -type ExtendedOrder struct { - Order - // The order URL, contains the value of the response header `Location` - Location string `json:"-"` -} - -// Order the ACME order Object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.3 -type Order struct { - // status (required, string): - // The status of this order. - // Possible values are: "pending", "ready", "processing", "valid", and "invalid". - Status string `json:"status,omitempty"` - - // expires (optional, string): - // The timestamp after which the server will consider this order invalid, - // encoded in the format specified in RFC 3339 [RFC3339]. - // This field is REQUIRED for objects with "pending" or "valid" in the status field. - Expires string `json:"expires,omitempty"` - - // identifiers (required, array of object): - // An array of identifier objects that the order pertains to. - Identifiers []Identifier `json:"identifiers"` - - // notBefore (optional, string): - // The requested value of the notBefore field in the certificate, - // in the date format defined in [RFC3339]. - NotBefore string `json:"notBefore,omitempty"` - - // notAfter (optional, string): - // The requested value of the notAfter field in the certificate, - // in the date format defined in [RFC3339]. - NotAfter string `json:"notAfter,omitempty"` - - // error (optional, object): - // The error that occurred while processing the order, if any. - // This field is structured as a problem document [RFC7807]. - Error *ProblemDetails `json:"error,omitempty"` - - // authorizations (required, array of string): - // For pending orders, - // the authorizations that the client needs to complete before the requested certificate can be issued (see Section 7.5), - // including unexpired authorizations that the client has completed in the past for identifiers specified in the order. - // The authorizations required are dictated by server policy - // and there may not be a 1:1 relationship between the order identifiers and the authorizations required. - // For final orders (in the "valid" or "invalid" state), the authorizations that were completed. - // Each entry is a URL from which an authorization can be fetched with a POST-as-GET request. - Authorizations []string `json:"authorizations,omitempty"` - - // finalize (required, string): - // A URL that a CSR must be POSTed to once all of the order's authorizations are satisfied to finalize the order. - // The result of a successful finalization will be the population of the certificate URL for the order. - Finalize string `json:"finalize,omitempty"` - - // certificate (optional, string): - // A URL for the certificate that has been issued in response to this order - Certificate string `json:"certificate,omitempty"` -} - -// Authorization the ACME authorization object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.4 -type Authorization struct { - // status (required, string): - // The status of this authorization. - // Possible values are: "pending", "valid", "invalid", "deactivated", "expired", and "revoked". - Status string `json:"status"` - - // expires (optional, string): - // The timestamp after which the server will consider this authorization invalid, - // encoded in the format specified in RFC 3339 [RFC3339]. - // This field is REQUIRED for objects with "valid" in the "status" field. - Expires time.Time `json:"expires,omitempty"` - - // identifier (required, object): - // The identifier that the account is authorized to represent - Identifier Identifier `json:"identifier,omitempty"` - - // challenges (required, array of objects): - // For pending authorizations, the challenges that the client can fulfill in order to prove possession of the identifier. - // For valid authorizations, the challenge that was validated. - // For invalid authorizations, the challenge that was attempted and failed. - // Each array entry is an object with parameters required to validate the challenge. - // A client should attempt to fulfill one of these challenges, - // and a server should consider any one of the challenges sufficient to make the authorization valid. - Challenges []Challenge `json:"challenges,omitempty"` - - // wildcard (optional, boolean): - // For authorizations created as a result of a newOrder request containing a DNS identifier - // with a value that contained a wildcard prefix this field MUST be present, and true. - Wildcard bool `json:"wildcard,omitempty"` -} - -// ExtendedChallenge a extended Challenge. -type ExtendedChallenge struct { - Challenge - // Contains the value of the response header `Retry-After` - RetryAfter string `json:"-"` - // Contains the value of the response header `Link` rel="up" - AuthorizationURL string `json:"-"` -} - -// Challenge the ACME challenge object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.5 -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8 -type Challenge struct { - // type (required, string): - // The type of challenge encoded in the object. - Type string `json:"type"` - - // url (required, string): - // The URL to which a response can be posted. - URL string `json:"url"` - - // status (required, string): - // The status of this challenge. Possible values are: "pending", "processing", "valid", and "invalid". - Status string `json:"status"` - - // validated (optional, string): - // The time at which the server validated this challenge, - // encoded in the format specified in RFC 3339 [RFC3339]. - // This field is REQUIRED if the "status" field is "valid". - Validated time.Time `json:"validated,omitempty"` - - // error (optional, object): - // Error that occurred while the server was validating the challenge, if any, - // structured as a problem document [RFC7807]. - // Multiple errors can be indicated by using subproblems Section 6.7.1. - // A challenge object with an error MUST have status equal to "invalid". - Error *ProblemDetails `json:"error,omitempty"` - - // token (required, string): - // A random value that uniquely identifies the challenge. - // This value MUST have at least 128 bits of entropy. - // It MUST NOT contain any characters outside the base64url alphabet, - // and MUST NOT include base64 padding characters ("="). - // See [RFC4086] for additional information on randomness requirements. - // https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.3 - // https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.4 - Token string `json:"token"` - - // https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.1 - KeyAuthorization string `json:"keyAuthorization"` -} - -// Identifier the ACME identifier object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-9.7.7 -type Identifier struct { - Type string `json:"type"` - Value string `json:"value"` -} - -// CSRMessage Certificate Signing Request -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.4 -type CSRMessage struct { - // csr (required, string): - // A CSR encoding the parameters for the certificate being requested [RFC2986]. - // The CSR is sent in the base64url-encoded version of the DER format. - // (Note: Because this field uses base64url, and does not include headers, it is different from PEM.). - Csr string `json:"csr"` -} - -// RevokeCertMessage a certificate revocation message -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.6 -// - https://tools.ietf.org/html/rfc5280#section-5.3.1 -type RevokeCertMessage struct { - // certificate (required, string): - // The certificate to be revoked, in the base64url-encoded version of the DER format. - // (Note: Because this field uses base64url, and does not include headers, it is different from PEM.) - Certificate string `json:"certificate"` - - // reason (optional, int): - // One of the revocation reasonCodes defined in Section 5.3.1 of [RFC5280] to be used when generating OCSP responses and CRLs. - // If this field is not set the server SHOULD omit the reasonCode CRL entry extension when generating OCSP responses and CRLs. - // The server MAY disallow a subset of reasonCodes from being used by the user. - // If a request contains a disallowed reasonCode the server MUST reject it with the error type "urn:ietf:params:acme:error:badRevocationReason". - // The problem document detail SHOULD indicate which reasonCodes are allowed. - Reason *uint `json:"reason,omitempty"` -} diff --git a/vendor/github.com/go-acme/lego/acme/errors.go b/vendor/github.com/go-acme/lego/acme/errors.go deleted file mode 100644 index 1658fe8..0000000 --- a/vendor/github.com/go-acme/lego/acme/errors.go +++ /dev/null @@ -1,58 +0,0 @@ -package acme - -import ( - "fmt" -) - -// Errors types -const ( - errNS = "urn:ietf:params:acme:error:" - BadNonceErr = errNS + "badNonce" -) - -// ProblemDetails the problem details object -// - https://tools.ietf.org/html/rfc7807#section-3.1 -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.3.3 -type ProblemDetails struct { - Type string `json:"type,omitempty"` - Detail string `json:"detail,omitempty"` - HTTPStatus int `json:"status,omitempty"` - Instance string `json:"instance,omitempty"` - SubProblems []SubProblem `json:"subproblems,omitempty"` - - // additional values to have a better error message (Not defined by the RFC) - Method string `json:"method,omitempty"` - URL string `json:"url,omitempty"` -} - -// SubProblem a "subproblems" -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-6.7.1 -type SubProblem struct { - Type string `json:"type,omitempty"` - Detail string `json:"detail,omitempty"` - Identifier Identifier `json:"identifier,omitempty"` -} - -func (p ProblemDetails) Error() string { - msg := fmt.Sprintf("acme: error: %d", p.HTTPStatus) - if len(p.Method) != 0 || len(p.URL) != 0 { - msg += fmt.Sprintf(" :: %s :: %s", p.Method, p.URL) - } - msg += fmt.Sprintf(" :: %s :: %s", p.Type, p.Detail) - - for _, sub := range p.SubProblems { - msg += fmt.Sprintf(", problem: %q :: %s", sub.Type, sub.Detail) - } - - if len(p.Instance) == 0 { - msg += ", url: " + p.Instance - } - - return msg -} - -// NonceError represents the error which is returned -// if the nonce sent by the client was not accepted by the server. -type NonceError struct { - *ProblemDetails -} diff --git a/vendor/github.com/go-acme/lego/certcrypto/crypto.go b/vendor/github.com/go-acme/lego/certcrypto/crypto.go deleted file mode 100644 index c9d0c10..0000000 --- a/vendor/github.com/go-acme/lego/certcrypto/crypto.go +++ /dev/null @@ -1,256 +0,0 @@ -package certcrypto - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "errors" - "fmt" - "math/big" - "time" - - "golang.org/x/crypto/ocsp" -) - -// Constants for all key types we support. -const ( - EC256 = KeyType("P256") - EC384 = KeyType("P384") - RSA2048 = KeyType("2048") - RSA4096 = KeyType("4096") - RSA8192 = KeyType("8192") -) - -const ( - // OCSPGood means that the certificate is valid. - OCSPGood = ocsp.Good - // OCSPRevoked means that the certificate has been deliberately revoked. - OCSPRevoked = ocsp.Revoked - // OCSPUnknown means that the OCSP responder doesn't know about the certificate. - OCSPUnknown = ocsp.Unknown - // OCSPServerFailed means that the OCSP responder failed to process the request. - OCSPServerFailed = ocsp.ServerFailed -) - -// Constants for OCSP must staple -var ( - tlsFeatureExtensionOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 24} - ocspMustStapleFeature = []byte{0x30, 0x03, 0x02, 0x01, 0x05} -) - -// KeyType represents the key algo as well as the key size or curve to use. -type KeyType string - -type DERCertificateBytes []byte - -// ParsePEMBundle parses a certificate bundle from top to bottom and returns -// a slice of x509 certificates. This function will error if no certificates are found. -func ParsePEMBundle(bundle []byte) ([]*x509.Certificate, error) { - var certificates []*x509.Certificate - var certDERBlock *pem.Block - - for { - certDERBlock, bundle = pem.Decode(bundle) - if certDERBlock == nil { - break - } - - if certDERBlock.Type == "CERTIFICATE" { - cert, err := x509.ParseCertificate(certDERBlock.Bytes) - if err != nil { - return nil, err - } - certificates = append(certificates, cert) - } - } - - if len(certificates) == 0 { - return nil, errors.New("no certificates were found while parsing the bundle") - } - - return certificates, nil -} - -func ParsePEMPrivateKey(key []byte) (crypto.PrivateKey, error) { - keyBlock, _ := pem.Decode(key) - - switch keyBlock.Type { - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(keyBlock.Bytes) - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(keyBlock.Bytes) - default: - return nil, errors.New("unknown PEM header value") - } -} - -func GeneratePrivateKey(keyType KeyType) (crypto.PrivateKey, error) { - switch keyType { - case EC256: - return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - case EC384: - return ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - case RSA2048: - return rsa.GenerateKey(rand.Reader, 2048) - case RSA4096: - return rsa.GenerateKey(rand.Reader, 4096) - case RSA8192: - return rsa.GenerateKey(rand.Reader, 8192) - } - - return nil, fmt.Errorf("invalid KeyType: %s", keyType) -} - -func GenerateCSR(privateKey crypto.PrivateKey, domain string, san []string, mustStaple bool) ([]byte, error) { - template := x509.CertificateRequest{ - Subject: pkix.Name{CommonName: domain}, - DNSNames: san, - } - - if mustStaple { - template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{ - Id: tlsFeatureExtensionOID, - Value: ocspMustStapleFeature, - }) - } - - return x509.CreateCertificateRequest(rand.Reader, &template, privateKey) -} - -func PEMEncode(data interface{}) []byte { - return pem.EncodeToMemory(PEMBlock(data)) -} - -func PEMBlock(data interface{}) *pem.Block { - var pemBlock *pem.Block - switch key := data.(type) { - case *ecdsa.PrivateKey: - keyBytes, _ := x509.MarshalECPrivateKey(key) - pemBlock = &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes} - case *rsa.PrivateKey: - pemBlock = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)} - case *x509.CertificateRequest: - pemBlock = &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: key.Raw} - case DERCertificateBytes: - pemBlock = &pem.Block{Type: "CERTIFICATE", Bytes: []byte(data.(DERCertificateBytes))} - } - - return pemBlock -} - -func pemDecode(data []byte) (*pem.Block, error) { - pemBlock, _ := pem.Decode(data) - if pemBlock == nil { - return nil, fmt.Errorf("PEM decode did not yield a valid block. Is the certificate in the right format?") - } - - return pemBlock, nil -} - -func PemDecodeTox509CSR(pem []byte) (*x509.CertificateRequest, error) { - pemBlock, err := pemDecode(pem) - if pemBlock == nil { - return nil, err - } - - if pemBlock.Type != "CERTIFICATE REQUEST" { - return nil, fmt.Errorf("PEM block is not a certificate request") - } - - return x509.ParseCertificateRequest(pemBlock.Bytes) -} - -// ParsePEMCertificate returns Certificate from a PEM encoded certificate. -// The certificate has to be PEM encoded. Any other encodings like DER will fail. -func ParsePEMCertificate(cert []byte) (*x509.Certificate, error) { - pemBlock, err := pemDecode(cert) - if pemBlock == nil { - return nil, err - } - - // from a DER encoded certificate - return x509.ParseCertificate(pemBlock.Bytes) -} - -func ExtractDomains(cert *x509.Certificate) []string { - domains := []string{cert.Subject.CommonName} - - // Check for SAN certificate - for _, sanDomain := range cert.DNSNames { - if sanDomain == cert.Subject.CommonName { - continue - } - domains = append(domains, sanDomain) - } - - return domains -} - -func ExtractDomainsCSR(csr *x509.CertificateRequest) []string { - domains := []string{csr.Subject.CommonName} - - // loop over the SubjectAltName DNS names - for _, sanName := range csr.DNSNames { - if containsSAN(domains, sanName) { - // Duplicate; skip this name - continue - } - - // Name is unique - domains = append(domains, sanName) - } - - return domains -} - -func containsSAN(domains []string, sanName string) bool { - for _, existingName := range domains { - if existingName == sanName { - return true - } - } - return false -} - -func GeneratePemCert(privateKey *rsa.PrivateKey, domain string, extensions []pkix.Extension) ([]byte, error) { - derBytes, err := generateDerCert(privateKey, time.Time{}, domain, extensions) - if err != nil { - return nil, err - } - - return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}), nil -} - -func generateDerCert(privateKey *rsa.PrivateKey, expiration time.Time, domain string, extensions []pkix.Extension) ([]byte, error) { - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) - serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - return nil, err - } - - if expiration.IsZero() { - expiration = time.Now().Add(365) - } - - template := x509.Certificate{ - SerialNumber: serialNumber, - Subject: pkix.Name{ - CommonName: "ACME Challenge TEMP", - }, - NotBefore: time.Now(), - NotAfter: expiration, - - KeyUsage: x509.KeyUsageKeyEncipherment, - BasicConstraintsValid: true, - DNSNames: []string{domain}, - ExtraExtensions: extensions, - } - - return x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) -} diff --git a/vendor/github.com/go-acme/lego/certcrypto/crypto_test.go b/vendor/github.com/go-acme/lego/certcrypto/crypto_test.go deleted file mode 100644 index 27e3b41..0000000 --- a/vendor/github.com/go-acme/lego/certcrypto/crypto_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package certcrypto - -import ( - "bytes" - "crypto" - "crypto/rand" - "crypto/rsa" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGeneratePrivateKey(t *testing.T) { - key, err := GeneratePrivateKey(RSA2048) - require.NoError(t, err, "Error generating private key") - - assert.NotNil(t, key) -} - -func TestGenerateCSR(t *testing.T) { - privateKey, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err, "Error generating private key") - - type expected struct { - len int - error bool - } - - testCases := []struct { - desc string - privateKey crypto.PrivateKey - domain string - san []string - mustStaple bool - expected expected - }{ - { - desc: "without SAN", - privateKey: privateKey, - domain: "lego.acme", - mustStaple: true, - expected: expected{len: 245}, - }, - { - desc: "without SAN", - privateKey: privateKey, - domain: "lego.acme", - san: []string{}, - mustStaple: true, - expected: expected{len: 245}, - }, - { - desc: "with SAN", - privateKey: privateKey, - domain: "lego.acme", - san: []string{"a.lego.acme", "b.lego.acme", "c.lego.acme"}, - mustStaple: true, - expected: expected{len: 296}, - }, - { - desc: "no domain", - privateKey: privateKey, - domain: "", - mustStaple: true, - expected: expected{len: 225}, - }, - { - desc: "no domain with SAN", - privateKey: privateKey, - domain: "", - san: []string{"a.lego.acme", "b.lego.acme", "c.lego.acme"}, - mustStaple: true, - expected: expected{len: 276}, - }, - { - desc: "private key nil", - privateKey: nil, - domain: "fizz.buzz", - mustStaple: true, - expected: expected{error: true}, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - csr, err := GenerateCSR(test.privateKey, test.domain, test.san, test.mustStaple) - - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err, "Error generating CSR") - - assert.NotEmpty(t, csr) - assert.Len(t, csr, test.expected.len) - } - }) - } -} - -func TestPEMEncode(t *testing.T) { - buf := bytes.NewBufferString("TestingRSAIsSoMuchFun") - - reader := MockRandReader{b: buf} - key, err := rsa.GenerateKey(reader, 32) - require.NoError(t, err, "Error generating private key") - - data := PEMEncode(key) - require.NotNil(t, data) - assert.Len(t, data, 127) -} - -func TestParsePEMCertificate(t *testing.T) { - privateKey, err := GeneratePrivateKey(RSA2048) - require.NoError(t, err, "Error generating private key") - - expiration := time.Now().Add(365).Round(time.Second) - certBytes, err := generateDerCert(privateKey.(*rsa.PrivateKey), expiration, "test.com", nil) - require.NoError(t, err, "Error generating cert") - - buf := bytes.NewBufferString("TestingRSAIsSoMuchFun") - - // Some random string should return an error. - cert, err := ParsePEMCertificate(buf.Bytes()) - require.Errorf(t, err, "returned %v", cert) - - // A DER encoded certificate should return an error. - _, err = ParsePEMCertificate(certBytes) - require.Error(t, err, "Expected to return an error for DER certificates") - - // A PEM encoded certificate should work ok. - pemCert := PEMEncode(DERCertificateBytes(certBytes)) - cert, err = ParsePEMCertificate(pemCert) - require.NoError(t, err) - - assert.Equal(t, expiration.UTC(), cert.NotAfter) -} - -type MockRandReader struct { - b *bytes.Buffer -} - -func (r MockRandReader) Read(p []byte) (int, error) { - return r.b.Read(p) -} diff --git a/vendor/github.com/go-acme/lego/certificate/authorization.go b/vendor/github.com/go-acme/lego/certificate/authorization.go deleted file mode 100644 index 0006250..0000000 --- a/vendor/github.com/go-acme/lego/certificate/authorization.go +++ /dev/null @@ -1,69 +0,0 @@ -package certificate - -import ( - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/log" -) - -const ( - // overallRequestLimit is the overall number of request per second - // limited on the "new-reg", "new-authz" and "new-cert" endpoints. - // From the documentation the limitation is 20 requests per second, - // but using 20 as value doesn't work but 18 do - overallRequestLimit = 18 -) - -func (c *Certifier) getAuthorizations(order acme.ExtendedOrder) ([]acme.Authorization, error) { - resc, errc := make(chan acme.Authorization), make(chan domainError) - - delay := time.Second / overallRequestLimit - - for _, authzURL := range order.Authorizations { - time.Sleep(delay) - - go func(authzURL string) { - authz, err := c.core.Authorizations.Get(authzURL) - if err != nil { - errc <- domainError{Domain: authz.Identifier.Value, Error: err} - return - } - - resc <- authz - }(authzURL) - } - - var responses []acme.Authorization - failures := make(obtainError) - for i := 0; i < len(order.Authorizations); i++ { - select { - case res := <-resc: - responses = append(responses, res) - case err := <-errc: - failures[err.Domain] = err.Error - } - } - - for i, auth := range order.Authorizations { - log.Infof("[%s] AuthURL: %s", order.Identifiers[i].Value, auth) - } - - close(resc) - close(errc) - - // be careful to not return an empty failures map; - // even if empty, they become non-nil error values - if len(failures) > 0 { - return responses, failures - } - return responses, nil -} - -func (c *Certifier) deactivateAuthorizations(order acme.ExtendedOrder) { - for _, auth := range order.Authorizations { - if err := c.core.Authorizations.Deactivate(auth); err != nil { - log.Infof("Unable to deactivated authorizations: %s", auth) - } - } -} diff --git a/vendor/github.com/go-acme/lego/certificate/certificates.go b/vendor/github.com/go-acme/lego/certificate/certificates.go deleted file mode 100644 index a61c76a..0000000 --- a/vendor/github.com/go-acme/lego/certificate/certificates.go +++ /dev/null @@ -1,570 +0,0 @@ -package certificate - -import ( - "bytes" - "crypto" - "crypto/x509" - "encoding/base64" - "errors" - "fmt" - "github.com/go-acme/lego/challenge/dns01" - "io/ioutil" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/wait" - "golang.org/x/crypto/ocsp" - "golang.org/x/net/idna" -) - -// maxBodySize is the maximum size of body that we will read. -const maxBodySize = 1024 * 1024 - -// Resource represents a CA issued certificate. -// PrivateKey, Certificate and IssuerCertificate are all -// already PEM encoded and can be directly written to disk. -// Certificate may be a certificate bundle, -// depending on the options supplied to create it. -type Resource struct { - Domain string `json:"domain"` - CertURL string `json:"certUrl"` - CertStableURL string `json:"certStableUrl"` - PrivateKey []byte `json:"-"` - Certificate []byte `json:"-"` - IssuerCertificate []byte `json:"-"` - CSR []byte `json:"-"` -} - -// ObtainRequest The request to obtain certificate. -// -// The first domain in domains is used for the CommonName field of the certificate, -// all other domains are added using the Subject Alternate Names extension. -// -// A new private key is generated for every invocation of the function Obtain. -// If you do not want that you can supply your own private key in the privateKey parameter. -// If this parameter is non-nil it will be used instead of generating a new one. -// -// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. -type ObtainRequest struct { - Domains []string - Bundle bool - PrivateKey crypto.PrivateKey - MustStaple bool -} - -type resolver interface { - Solve(authorizations []acme.Authorization) error -} - -type CertifierOptions struct { - KeyType certcrypto.KeyType - Timeout time.Duration -} - -// Certifier A service to obtain/renew/revoke certificates. -type Certifier struct { - core *api.Core - resolver resolver - options CertifierOptions -} - -// NewCertifier creates a Certifier. -func NewCertifier(core *api.Core, resolver resolver, options CertifierOptions) *Certifier { - return &Certifier{ - core: core, - resolver: resolver, - options: options, - } -} - -func (c *Certifier) GetRecords(request ObtainRequest) (records []string, err error) { - if len(request.Domains) == 0 { - return nil, errors.New("no domains to obtain a certificate for") - } - - domains := sanitizeDomain(request.Domains) - - if request.Bundle { - log.Infof("[%s] acme: Obtaining bundled SAN certificate", strings.Join(domains, ", ")) - } else { - log.Infof("[%s] acme: Obtaining SAN certificate", strings.Join(domains, ", ")) - } - - order, err := c.core.Orders.New(domains) - if err != nil { - return nil, err - } - - authz, err := c.getAuthorizations(order) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - for _, a := range authz { - domain := challenge.GetTargetedDomain(a) - log.Infof("[%s] acme: Trying to solve DNS-01", domain) - - chlng, err := challenge.FindChallenge(challenge.DNS01, a) - if err != nil { - return nil, err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return nil, err - } - - fqdn, value := dns01.GetRecord(a.Identifier.Value, keyAuth) - records = append(records, fqdn+"|"+value) - } - - return records, nil -} - -// Obtain tries to obtain a single certificate using all domains passed into it. -// -// This function will never return a partial certificate. -// If one domain in the list fails, the whole certificate will fail. -func (c *Certifier) Obtain(request ObtainRequest) (*Resource, error) { - if len(request.Domains) == 0 { - return nil, errors.New("no domains to obtain a certificate for") - } - - domains := sanitizeDomain(request.Domains) - - if request.Bundle { - log.Infof("[%s] acme: Obtaining bundled SAN certificate", strings.Join(domains, ", ")) - } else { - log.Infof("[%s] acme: Obtaining SAN certificate", strings.Join(domains, ", ")) - } - - order, err := c.core.Orders.New(domains) - if err != nil { - return nil, err - } - - authz, err := c.getAuthorizations(order) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - err = c.resolver.Solve(authz) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", ")) - - failures := make(obtainError) - cert, err := c.getForOrder(domains, order, request.Bundle, request.PrivateKey, request.MustStaple) - if err != nil { - for _, auth := range authz { - failures[challenge.GetTargetedDomain(auth)] = err - } - } - - // Do not return an empty failures map, because - // it would still be a non-nil error value - if len(failures) > 0 { - return cert, failures - } - return cert, nil -} - -// ObtainForCSR tries to obtain a certificate matching the CSR passed into it. -// -// The domains are inferred from the CommonName and SubjectAltNames, if any. -// The private key for this CSR is not required. -// -// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. -// -// This function will never return a partial certificate. -// If one domain in the list fails, the whole certificate will fail. -func (c *Certifier) ObtainForCSR(csr x509.CertificateRequest, bundle bool) (*Resource, error) { - // figure out what domains it concerns - // start with the common name - domains := certcrypto.ExtractDomainsCSR(&csr) - - if bundle { - log.Infof("[%s] acme: Obtaining bundled SAN certificate given a CSR", strings.Join(domains, ", ")) - } else { - log.Infof("[%s] acme: Obtaining SAN certificate given a CSR", strings.Join(domains, ", ")) - } - - order, err := c.core.Orders.New(domains) - if err != nil { - return nil, err - } - - authz, err := c.getAuthorizations(order) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - err = c.resolver.Solve(authz) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", ")) - - failures := make(obtainError) - cert, err := c.getForCSR(domains, order, bundle, csr.Raw, nil) - if err != nil { - for _, auth := range authz { - failures[challenge.GetTargetedDomain(auth)] = err - } - } - - if cert != nil { - // Add the CSR to the certificate so that it can be used for renewals. - cert.CSR = certcrypto.PEMEncode(&csr) - } - - // Do not return an empty failures map, - // because it would still be a non-nil error value - if len(failures) > 0 { - return cert, failures - } - return cert, nil -} - -func (c *Certifier) getForOrder(domains []string, order acme.ExtendedOrder, bundle bool, privateKey crypto.PrivateKey, mustStaple bool) (*Resource, error) { - if privateKey == nil { - var err error - privateKey, err = certcrypto.GeneratePrivateKey(c.options.KeyType) - if err != nil { - return nil, err - } - } - - // Determine certificate name(s) based on the authorization resources - commonName := domains[0] - - // ACME draft Section 7.4 "Applying for Certificate Issuance" - // https://tools.ietf.org/html/draft-ietf-acme-acme-12#section-7.4 - // says: - // Clients SHOULD NOT make any assumptions about the sort order of - // "identifiers" or "authorizations" elements in the returned order - // object. - san := []string{commonName} - for _, auth := range order.Identifiers { - if auth.Value != commonName { - san = append(san, auth.Value) - } - } - - // TODO: should the CSR be customizable? - csr, err := certcrypto.GenerateCSR(privateKey, commonName, san, mustStaple) - if err != nil { - return nil, err - } - - return c.getForCSR(domains, order, bundle, csr, certcrypto.PEMEncode(privateKey)) -} - -func (c *Certifier) getForCSR(domains []string, order acme.ExtendedOrder, bundle bool, csr []byte, privateKeyPem []byte) (*Resource, error) { - respOrder, err := c.core.Orders.UpdateForCSR(order.Finalize, csr) - if err != nil { - return nil, err - } - - commonName := domains[0] - certRes := &Resource{ - Domain: commonName, - CertURL: respOrder.Certificate, - PrivateKey: privateKeyPem, - } - - if respOrder.Status == acme.StatusValid { - // if the certificate is available right away, short cut! - ok, errR := c.checkResponse(respOrder, certRes, bundle) - if errR != nil { - return nil, errR - } - - if ok { - return certRes, nil - } - } - - timeout := c.options.Timeout - if c.options.Timeout <= 0 { - timeout = 30 * time.Second - } - - err = wait.For("certificate", timeout, timeout/60, func() (bool, error) { - ord, errW := c.core.Orders.Get(order.Location) - if errW != nil { - return false, errW - } - - done, errW := c.checkResponse(ord, certRes, bundle) - if errW != nil { - return false, errW - } - - return done, nil - }) - - return certRes, err -} - -// checkResponse checks to see if the certificate is ready and a link is contained in the response. -// -// If so, loads it into certRes and returns true. -// If the cert is not yet ready, it returns false. -// -// The certRes input should already have the Domain (common name) field populated. -// -// If bundle is true, the certificate will be bundled with the issuer's cert. -func (c *Certifier) checkResponse(order acme.Order, certRes *Resource, bundle bool) (bool, error) { - valid, err := checkOrderStatus(order) - if err != nil || !valid { - return valid, err - } - - cert, issuer, err := c.core.Certificates.Get(order.Certificate, bundle) - if err != nil { - return false, err - } - - log.Infof("[%s] Server responded with a certificate.", certRes.Domain) - - certRes.IssuerCertificate = issuer - certRes.Certificate = cert - certRes.CertURL = order.Certificate - certRes.CertStableURL = order.Certificate - - return true, nil -} - -// Revoke takes a PEM encoded certificate or bundle and tries to revoke it at the CA. -func (c *Certifier) Revoke(cert []byte) error { - certificates, err := certcrypto.ParsePEMBundle(cert) - if err != nil { - return err - } - - x509Cert := certificates[0] - if x509Cert.IsCA { - return fmt.Errorf("certificate bundle starts with a CA certificate") - } - - revokeMsg := acme.RevokeCertMessage{ - Certificate: base64.RawURLEncoding.EncodeToString(x509Cert.Raw), - } - - return c.core.Certificates.Revoke(revokeMsg) -} - -// Renew takes a Resource and tries to renew the certificate. -// -// If the renewal process succeeds, the new certificate will ge returned in a new CertResource. -// Please be aware that this function will return a new certificate in ANY case that is not an error. -// If the server does not provide us with a new cert on a GET request to the CertURL -// this function will start a new-cert flow where a new certificate gets generated. -// -// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. -// -// For private key reuse the PrivateKey property of the passed in Resource should be non-nil. -func (c *Certifier) Renew(certRes Resource, bundle, mustStaple bool) (*Resource, error) { - // Input certificate is PEM encoded. - // Decode it here as we may need the decoded cert later on in the renewal process. - // The input may be a bundle or a single certificate. - certificates, err := certcrypto.ParsePEMBundle(certRes.Certificate) - if err != nil { - return nil, err - } - - x509Cert := certificates[0] - if x509Cert.IsCA { - return nil, fmt.Errorf("[%s] Certificate bundle starts with a CA certificate", certRes.Domain) - } - - // This is just meant to be informal for the user. - timeLeft := x509Cert.NotAfter.Sub(time.Now().UTC()) - log.Infof("[%s] acme: Trying renewal with %d hours remaining", certRes.Domain, int(timeLeft.Hours())) - - // We always need to request a new certificate to renew. - // Start by checking to see if the certificate was based off a CSR, - // and use that if it's defined. - if len(certRes.CSR) > 0 { - csr, errP := certcrypto.PemDecodeTox509CSR(certRes.CSR) - if errP != nil { - return nil, errP - } - - return c.ObtainForCSR(*csr, bundle) - } - - var privateKey crypto.PrivateKey - if certRes.PrivateKey != nil { - privateKey, err = certcrypto.ParsePEMPrivateKey(certRes.PrivateKey) - if err != nil { - return nil, err - } - } - - query := ObtainRequest{ - Domains: certcrypto.ExtractDomains(x509Cert), - Bundle: bundle, - PrivateKey: privateKey, - MustStaple: mustStaple, - } - return c.Obtain(query) -} - -// GetOCSP takes a PEM encoded cert or cert bundle returning the raw OCSP response, -// the parsed response, and an error, if any. -// -// The returned []byte can be passed directly into the OCSPStaple property of a tls.Certificate. -// If the bundle only contains the issued certificate, -// this function will try to get the issuer certificate from the IssuingCertificateURL in the certificate. -// -// If the []byte and/or ocsp.Response return values are nil, the OCSP status may be assumed OCSPUnknown. -func (c *Certifier) GetOCSP(bundle []byte) ([]byte, *ocsp.Response, error) { - certificates, err := certcrypto.ParsePEMBundle(bundle) - if err != nil { - return nil, nil, err - } - - // We expect the certificate slice to be ordered downwards the chain. - // SRV CRT -> CA. We need to pull the leaf and issuer certs out of it, - // which should always be the first two certificates. - // If there's no OCSP server listed in the leaf cert, there's nothing to do. - // And if we have only one certificate so far, we need to get the issuer cert. - - issuedCert := certificates[0] - - if len(issuedCert.OCSPServer) == 0 { - return nil, nil, errors.New("no OCSP server specified in cert") - } - - if len(certificates) == 1 { - // TODO: build fallback. If this fails, check the remaining array entries. - if len(issuedCert.IssuingCertificateURL) == 0 { - return nil, nil, errors.New("no issuing certificate URL") - } - - resp, errC := c.core.HTTPClient.Get(issuedCert.IssuingCertificateURL[0]) - if errC != nil { - return nil, nil, errC - } - defer resp.Body.Close() - - issuerBytes, errC := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize)) - if errC != nil { - return nil, nil, errC - } - - issuerCert, errC := x509.ParseCertificate(issuerBytes) - if errC != nil { - return nil, nil, errC - } - - // Insert it into the slice on position 0 - // We want it ordered right SRV CRT -> CA - certificates = append(certificates, issuerCert) - } - - issuerCert := certificates[1] - - // Finally kick off the OCSP request. - ocspReq, err := ocsp.CreateRequest(issuedCert, issuerCert, nil) - if err != nil { - return nil, nil, err - } - - resp, err := c.core.HTTPClient.Post(issuedCert.OCSPServer[0], "application/ocsp-request", bytes.NewReader(ocspReq)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - ocspResBytes, err := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize)) - if err != nil { - return nil, nil, err - } - - ocspRes, err := ocsp.ParseResponse(ocspResBytes, issuerCert) - if err != nil { - return nil, nil, err - } - - return ocspResBytes, ocspRes, nil -} - -// Get attempts to fetch the certificate at the supplied URL. -// The URL is the same as what would normally be supplied at the Resource's CertURL. -// -// The returned Resource will not have the PrivateKey and CSR fields populated as these will not be available. -// -// If bundle is true, the Certificate field in the returned Resource includes the issuer certificate. -func (c *Certifier) Get(url string, bundle bool) (*Resource, error) { - cert, issuer, err := c.core.Certificates.Get(url, bundle) - if err != nil { - return nil, err - } - - // Parse the returned cert bundle so that we can grab the domain from the common name. - x509Certs, err := certcrypto.ParsePEMBundle(cert) - if err != nil { - return nil, err - } - - return &Resource{ - Domain: x509Certs[0].Subject.CommonName, - Certificate: cert, - IssuerCertificate: issuer, - CertURL: url, - CertStableURL: url, - }, nil -} - -func checkOrderStatus(order acme.Order) (bool, error) { - switch order.Status { - case acme.StatusValid: - return true, nil - case acme.StatusInvalid: - return false, order.Error - default: - return false, nil - } -} - -// https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.4 -// The domain name MUST be encoded -// in the form in which it would appear in a certificate. That is, it -// MUST be encoded according to the rules in Section 7 of [RFC5280]. -// -// https://tools.ietf.org/html/rfc5280#section-7 -func sanitizeDomain(domains []string) []string { - var sanitizedDomains []string - for _, domain := range domains { - sanitizedDomain, err := idna.ToASCII(domain) - if err != nil { - log.Infof("skip domain %q: unable to sanitize (punnycode): %v", domain, err) - } else { - sanitizedDomains = append(sanitizedDomains, sanitizedDomain) - } - } - return sanitizedDomains -} diff --git a/vendor/github.com/go-acme/lego/certificate/certificates_test.go b/vendor/github.com/go-acme/lego/certificate/certificates_test.go deleted file mode 100644 index 8ab8a51..0000000 --- a/vendor/github.com/go-acme/lego/certificate/certificates_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package certificate - -import ( - "crypto/rand" - "crypto/rsa" - "encoding/pem" - "net/http" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const certResponseMock = `-----BEGIN CERTIFICATE----- -MIIDEDCCAfigAwIBAgIHPhckqW5fPDANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQD -Ex1QZWJibGUgSW50ZXJtZWRpYXRlIENBIDM5NWU2MTAeFw0xODExMDcxNzQ2NTZa -Fw0yMzExMDcxNzQ2NTZaMBMxETAPBgNVBAMTCGFjbWUud3RmMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwtLNKvZXD20XPUQCWYSK9rUSKxD9Eb0c9fag -bxOxOkLRTgL8LH6yln+bxc3MrHDou4PpDUdeo2CyOQu3CKsTS5mrH3NXYHu0H7p5 -y3riOJTHnfkGKLT9LciGz7GkXd62nvNP57bOf5Sk4P2M+Qbxd0hPTSfu52740LSy -144cnxe2P1aDYehrEp6nYCESuyD/CtUHTo0qwJmzIy163Sp3rSs15BuCPyhySnE3 -BJ8Ggv+qC6D5I1932DfSqyQJ79iq/HRm0Fn84am3KwvRlUfWxabmsUGARXoqCgnE -zcbJVOZKewv0zlQJpfac+b+Imj6Lvt1TGjIz2mVyefYgLx8gwwIDAQABo1QwUjAO -BgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG -A1UdEwEB/wQCMAAwEwYDVR0RBAwwCoIIYWNtZS53dGYwDQYJKoZIhvcNAQELBQAD -ggEBABB/0iYhmfPSQot5RaeeovQnsqYjI5ryQK2cwzW6qcTJfv8N6+p6XkqF1+W4 -jXZjrQP8MvgO9KNWlvx12vhINE6wubk88L+2piAi5uS2QejmZbXpyYB9s+oPqlk9 -IDvfdlVYOqvYAhSx7ggGi+j73mjZVtjAavP6dKuu475ZCeq+NIC15RpbbikWKtYE -HBJ7BW8XQKx67iHGx8ygHTDLbREL80Bck3oUm7wIYGMoNijD6RBl25p4gYl9dzOd -TqGl5hW/1P5hMbgEzHbr4O3BfWqU2g7tV36TASy3jbC3ONFRNNYrpEZ1AL3+cUri -OPPkKtAKAbQkKbUIfsHpBZjKZMU= ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE -AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw -NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl -NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT -SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh -0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen -SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx -HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt -D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu -mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD -AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA -upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm -iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd -QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ -wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv -rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2 -7R4IbHGnj0BJA2vMYC4hSw== ------END CERTIFICATE----- -` - -const issuerMock = `-----BEGIN CERTIFICATE----- -MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE -AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw -NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl -NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT -SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh -0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen -SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx -HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt -D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu -mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD -AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA -upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm -iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd -QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ -wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv -rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2 -7R4IbHGnj0BJA2vMYC4hSw== ------END CERTIFICATE----- -` - -func Test_checkResponse(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { - _, err := w.Write([]byte(certResponseMock)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048}) - - order := acme.Order{ - Status: acme.StatusValid, - Certificate: apiURL + "/certificate", - } - certRes := &Resource{} - bundle := false - - valid, err := certifier.checkResponse(order, certRes, bundle) - require.NoError(t, err) - assert.True(t, valid) - assert.NotNil(t, certRes) - assert.Equal(t, "", certRes.Domain) - assert.Contains(t, certRes.CertStableURL, "/certificate") - assert.Contains(t, certRes.CertURL, "/certificate") - assert.Nil(t, certRes.CSR) - assert.Nil(t, certRes.PrivateKey) - assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate") - assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate") -} - -func Test_checkResponse_issuerRelUp(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`) - _, err := w.Write([]byte(certResponseMock)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - mux.HandleFunc("/issuer", func(w http.ResponseWriter, _ *http.Request) { - p, _ := pem.Decode([]byte(issuerMock)) - _, err := w.Write(p.Bytes) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048}) - - order := acme.Order{ - Status: acme.StatusValid, - Certificate: apiURL + "/certificate", - } - certRes := &Resource{} - bundle := false - - valid, err := certifier.checkResponse(order, certRes, bundle) - require.NoError(t, err) - assert.True(t, valid) - assert.NotNil(t, certRes) - assert.Equal(t, "", certRes.Domain) - assert.Contains(t, certRes.CertStableURL, "/certificate") - assert.Contains(t, certRes.CertURL, "/certificate") - assert.Nil(t, certRes.CSR) - assert.Nil(t, certRes.PrivateKey) - assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate") - assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate") -} - -func Test_checkResponse_embeddedIssuer(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { - _, err := w.Write([]byte(certResponseMock)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048}) - - order := acme.Order{ - Status: acme.StatusValid, - Certificate: apiURL + "/certificate", - } - certRes := &Resource{} - bundle := false - - valid, err := certifier.checkResponse(order, certRes, bundle) - require.NoError(t, err) - assert.True(t, valid) - assert.NotNil(t, certRes) - assert.Equal(t, "", certRes.Domain) - assert.Contains(t, certRes.CertStableURL, "/certificate") - assert.Contains(t, certRes.CertURL, "/certificate") - assert.Nil(t, certRes.CSR) - assert.Nil(t, certRes.PrivateKey) - assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate") - assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate") -} - -func Test_Get(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/acme/cert/test-cert", func(w http.ResponseWriter, _ *http.Request) { - _, err := w.Write([]byte(certResponseMock)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048}) - - certRes, err := certifier.Get(apiURL+"/acme/cert/test-cert", false) - require.NoError(t, err) - - assert.NotNil(t, certRes) - assert.Equal(t, "acme.wtf", certRes.Domain) - assert.Equal(t, apiURL+"/acme/cert/test-cert", certRes.CertStableURL) - assert.Equal(t, apiURL+"/acme/cert/test-cert", certRes.CertURL) - assert.Nil(t, certRes.CSR) - assert.Nil(t, certRes.PrivateKey) - assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate") - assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate") -} - -type resolverMock struct { - error error -} - -func (r *resolverMock) Solve(authorizations []acme.Authorization) error { - return r.error -} diff --git a/vendor/github.com/go-acme/lego/certificate/errors.go b/vendor/github.com/go-acme/lego/certificate/errors.go deleted file mode 100644 index 0fec7c1..0000000 --- a/vendor/github.com/go-acme/lego/certificate/errors.go +++ /dev/null @@ -1,30 +0,0 @@ -package certificate - -import ( - "bytes" - "fmt" - "sort" -) - -// obtainError is returned when there are specific errors available per domain. -type obtainError map[string]error - -func (e obtainError) Error() string { - buffer := bytes.NewBufferString("acme: Error -> One or more domains had a problem:\n") - - var domains []string - for domain := range e { - domains = append(domains, domain) - } - sort.Strings(domains) - - for _, domain := range domains { - buffer.WriteString(fmt.Sprintf("[%s] %s\n", domain, e[domain])) - } - return buffer.String() -} - -type domainError struct { - Domain string - Error error -} diff --git a/vendor/github.com/go-acme/lego/challenge/challenges.go b/vendor/github.com/go-acme/lego/challenge/challenges.go deleted file mode 100644 index b328140..0000000 --- a/vendor/github.com/go-acme/lego/challenge/challenges.go +++ /dev/null @@ -1,44 +0,0 @@ -package challenge - -import ( - "fmt" - - "github.com/go-acme/lego/acme" -) - -// Type is a string that identifies a particular challenge type and version of ACME challenge. -type Type string - -const ( - // HTTP01 is the "http-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.3 - // Note: ChallengePath returns the URL path to fulfill this challenge - HTTP01 = Type("http-01") - - // DNS01 is the "dns-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.4 - // Note: GetRecord returns a DNS record which will fulfill this challenge - DNS01 = Type("dns-01") - - // TLSALPN01 is the "tls-alpn-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05 - TLSALPN01 = Type("tls-alpn-01") -) - -func (t Type) String() string { - return string(t) -} - -func FindChallenge(chlgType Type, authz acme.Authorization) (acme.Challenge, error) { - for _, chlg := range authz.Challenges { - if chlg.Type == string(chlgType) { - return chlg, nil - } - } - - return acme.Challenge{}, fmt.Errorf("[%s] acme: unable to find challenge %s", GetTargetedDomain(authz), chlgType) -} - -func GetTargetedDomain(authz acme.Authorization) string { - if authz.Wildcard { - return "*." + authz.Identifier.Value - } - return authz.Identifier.Value -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/cname.go b/vendor/github.com/go-acme/lego/challenge/dns01/cname.go deleted file mode 100644 index 619c847..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/cname.go +++ /dev/null @@ -1,16 +0,0 @@ -package dns01 - -import "github.com/miekg/dns" - -// Update FQDN with CNAME if any -func updateDomainWithCName(r *dns.Msg, fqdn string) string { - for _, rr := range r.Answer { - if cn, ok := rr.(*dns.CNAME); ok { - if cn.Hdr.Name == fqdn { - return cn.Target - } - } - } - - return fqdn -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge.go b/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge.go deleted file mode 100644 index 9500305..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge.go +++ /dev/null @@ -1,188 +0,0 @@ -package dns01 - -import ( - "crypto/sha256" - "encoding/base64" - "fmt" - "os" - "strconv" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/wait" - "github.com/miekg/dns" -) - -const ( - // DefaultPropagationTimeout default propagation timeout - DefaultPropagationTimeout = 60 * time.Second - - // DefaultPollingInterval default polling interval - DefaultPollingInterval = 2 * time.Second - - // DefaultTTL default TTL - DefaultTTL = 120 -) - -type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error - -type ChallengeOption func(*Challenge) error - -// CondOption Conditional challenge option. -func CondOption(condition bool, opt ChallengeOption) ChallengeOption { - if !condition { - // NoOp options - return func(*Challenge) error { - return nil - } - } - return opt -} - -// Challenge implements the dns-01 challenge -type Challenge struct { - core *api.Core - validate ValidateFunc - provider challenge.Provider - preCheck preCheck - dnsTimeout time.Duration -} - -func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider, opts ...ChallengeOption) *Challenge { - chlg := &Challenge{ - core: core, - validate: validate, - provider: provider, - preCheck: newPreCheck(), - dnsTimeout: 10 * time.Second, - } - - for _, opt := range opts { - err := opt(chlg) - if err != nil { - log.Infof("challenge option error: %v", err) - } - } - - return chlg -} - -// PreSolve just submits the txt record to the dns provider. -// It does not validate record propagation, or do anything at all with the acme server. -func (c *Challenge) PreSolve(authz acme.Authorization) error { - domain := challenge.GetTargetedDomain(authz) - log.Infof("[%s] acme: Preparing to solve DNS-01", domain) - - chlng, err := challenge.FindChallenge(challenge.DNS01, authz) - if err != nil { - return err - } - - if c.provider == nil { - return fmt.Errorf("[%s] acme: no DNS Provider configured", domain) - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth) - if err != nil { - return fmt.Errorf("[%s] acme: error presenting token: %s", domain, err) - } - - return nil -} - -func (c *Challenge) Solve(authz acme.Authorization) error { - domain := challenge.GetTargetedDomain(authz) - log.Infof("[%s] acme: Trying to solve DNS-01", domain) - - chlng, err := challenge.FindChallenge(challenge.DNS01, authz) - if err != nil { - return err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - fqdn, value := GetRecord(authz.Identifier.Value, keyAuth) - - var timeout, interval time.Duration - switch provider := c.provider.(type) { - case challenge.ProviderTimeout: - timeout, interval = provider.Timeout() - default: - timeout, interval = DefaultPropagationTimeout, DefaultPollingInterval - } - - log.Infof("[%s] acme: Checking DNS record propagation using %+v", domain, recursiveNameservers) - - err = wait.For("propagation", timeout, interval, func() (bool, error) { - stop, errP := c.preCheck.call(domain, fqdn, value) - if !stop || errP != nil { - log.Infof("[%s] acme: Waiting for DNS record propagation.", domain) - } - return stop, errP - }) - if err != nil { - return err - } - - chlng.KeyAuthorization = keyAuth - return c.validate(c.core, domain, chlng) -} - -// CleanUp cleans the challenge. -func (c *Challenge) CleanUp(authz acme.Authorization) error { - log.Infof("[%s] acme: Cleaning DNS-01 challenge", challenge.GetTargetedDomain(authz)) - - chlng, err := challenge.FindChallenge(challenge.DNS01, authz) - if err != nil { - return err - } - - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - return c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth) -} - -func (c *Challenge) Sequential() (bool, time.Duration) { - if p, ok := c.provider.(sequential); ok { - return ok, p.Sequential() - } - return false, 0 -} - -type sequential interface { - Sequential() time.Duration -} - -// GetRecord returns a DNS record which will fulfill the `dns-01` challenge -func GetRecord(domain, keyAuth string) (fqdn string, value string) { - keyAuthShaBytes := sha256.Sum256([]byte(keyAuth)) - // base64URL encoding without padding - value = base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size]) - fqdn = fmt.Sprintf("_acme-challenge.%s.", domain) - - if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_CNAME_SUPPORT")); ok { - r, err := dnsQuery(fqdn, dns.TypeCNAME, recursiveNameservers, true) - // Check if the domain has CNAME then return that - if err == nil && r.Rcode == dns.RcodeSuccess { - fqdn = updateDomainWithCName(r, fqdn) - } - } - - return -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual.go b/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual.go deleted file mode 100644 index 85da7d0..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual.go +++ /dev/null @@ -1,59 +0,0 @@ -package dns01 - -import ( - "bufio" - "fmt" - "os" - "time" -) - -const ( - dnsTemplate = `%s %d IN TXT "%s"` -) - -// DNSProviderManual is an implementation of the ChallengeProvider interface -type DNSProviderManual struct{} - -// NewDNSProviderManual returns a DNSProviderManual instance. -func NewDNSProviderManual() (*DNSProviderManual, error) { - return &DNSProviderManual{}, nil -} - -// Present prints instructions for manually creating the TXT record -func (*DNSProviderManual) Present(domain, token, keyAuth string) error { - fqdn, value := GetRecord(domain, keyAuth) - - authZone, err := FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - fmt.Printf("lego: Please create the following TXT record in your %s zone:\n", authZone) - fmt.Printf(dnsTemplate+"\n", fqdn, DefaultTTL, value) - fmt.Printf("lego: Press 'Enter' when you are done\n") - - _, err = bufio.NewReader(os.Stdin).ReadBytes('\n') - - return err -} - -// CleanUp prints instructions for manually removing the TXT record -func (*DNSProviderManual) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := GetRecord(domain, keyAuth) - - authZone, err := FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - fmt.Printf("lego: You can now remove this TXT record from your %s zone:\n", authZone) - fmt.Printf(dnsTemplate+"\n", fqdn, DefaultTTL, "...") - - return nil -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProviderManual) Sequential() time.Duration { - return DefaultPropagationTimeout -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual_test.go b/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual_test.go deleted file mode 100644 index 8802c35..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package dns01 - -import ( - "io" - "io/ioutil" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestDNSProviderManual(t *testing.T) { - backupStdin := os.Stdin - defer func() { os.Stdin = backupStdin }() - - testCases := []struct { - desc string - input string - expectError bool - }{ - { - desc: "Press enter", - input: "ok\n", - }, - { - desc: "Missing enter", - input: "ok", - expectError: true, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - file, err := ioutil.TempFile("", "lego_test") - assert.NoError(t, err) - defer func() { _ = os.Remove(file.Name()) }() - - _, err = io.WriteString(file, test.input) - assert.NoError(t, err) - - _, err = file.Seek(0, io.SeekStart) - assert.NoError(t, err) - - os.Stdin = file - - manualProvider, err := NewDNSProviderManual() - require.NoError(t, err) - - err = manualProvider.Present("example.com", "", "") - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - - err = manualProvider.CleanUp("example.com", "", "") - require.NoError(t, err) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_test.go b/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_test.go deleted file mode 100644 index 651fe8e..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_test.go +++ /dev/null @@ -1,289 +0,0 @@ -package dns01 - -import ( - "crypto/rand" - "crypto/rsa" - "errors" - "net/http" - "testing" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -type providerMock struct { - present, cleanUp error -} - -func (p *providerMock) Present(domain, token, keyAuth string) error { return p.present } -func (p *providerMock) CleanUp(domain, token, keyAuth string) error { return p.cleanUp } - -type providerTimeoutMock struct { - present, cleanUp error - timeout, interval time.Duration -} - -func (p *providerTimeoutMock) Present(domain, token, keyAuth string) error { return p.present } -func (p *providerTimeoutMock) CleanUp(domain, token, keyAuth string) error { return p.cleanUp } -func (p *providerTimeoutMock) Timeout() (time.Duration, time.Duration) { return p.timeout, p.interval } - -func TestChallenge_PreSolve(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - privateKey, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err) - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - testCases := []struct { - desc string - validate ValidateFunc - preCheck WrapPreCheckFunc - provider challenge.Provider - expectError bool - }{ - { - desc: "success", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{}, - }, - { - desc: "validate fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return errors.New("OOPS") }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - present: nil, - cleanUp: nil, - }, - }, - { - desc: "preCheck fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return false, errors.New("OOPS") }, - provider: &providerTimeoutMock{ - timeout: 2 * time.Second, - interval: 500 * time.Millisecond, - }, - }, - { - desc: "present fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - present: errors.New("OOPS"), - }, - expectError: true, - }, - { - desc: "cleanUp fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - cleanUp: errors.New("OOPS"), - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - chlg := NewChallenge(core, test.validate, test.provider, WrapPreCheck(test.preCheck)) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: "example.com", - }, - Challenges: []acme.Challenge{ - {Type: challenge.DNS01.String()}, - }, - } - - err = chlg.PreSolve(authz) - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestChallenge_Solve(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - privateKey, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err) - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - testCases := []struct { - desc string - validate ValidateFunc - preCheck WrapPreCheckFunc - provider challenge.Provider - expectError bool - }{ - { - desc: "success", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{}, - }, - { - desc: "validate fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return errors.New("OOPS") }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - present: nil, - cleanUp: nil, - }, - expectError: true, - }, - { - desc: "preCheck fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return false, errors.New("OOPS") }, - provider: &providerTimeoutMock{ - timeout: 2 * time.Second, - interval: 500 * time.Millisecond, - }, - expectError: true, - }, - { - desc: "present fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - present: errors.New("OOPS"), - }, - }, - { - desc: "cleanUp fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - cleanUp: errors.New("OOPS"), - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - var options []ChallengeOption - if test.preCheck != nil { - options = append(options, WrapPreCheck(test.preCheck)) - } - chlg := NewChallenge(core, test.validate, test.provider, options...) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: "example.com", - }, - Challenges: []acme.Challenge{ - {Type: challenge.DNS01.String()}, - }, - } - - err = chlg.Solve(authz) - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestChallenge_CleanUp(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - privateKey, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err) - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - testCases := []struct { - desc string - validate ValidateFunc - preCheck WrapPreCheckFunc - provider challenge.Provider - expectError bool - }{ - { - desc: "success", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{}, - }, - { - desc: "validate fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return errors.New("OOPS") }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - present: nil, - cleanUp: nil, - }, - }, - { - desc: "preCheck fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return false, errors.New("OOPS") }, - provider: &providerTimeoutMock{ - timeout: 2 * time.Second, - interval: 500 * time.Millisecond, - }, - }, - { - desc: "present fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - present: errors.New("OOPS"), - }, - }, - { - desc: "cleanUp fail", - validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil }, - provider: &providerMock{ - cleanUp: errors.New("OOPS"), - }, - expectError: true, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - chlg := NewChallenge(core, test.validate, test.provider, WrapPreCheck(test.preCheck)) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: "example.com", - }, - Challenges: []acme.Challenge{ - {Type: challenge.DNS01.String()}, - }, - } - - err = chlg.CleanUp(authz) - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/fixtures/resolv.conf.1 b/vendor/github.com/go-acme/lego/challenge/dns01/fixtures/resolv.conf.1 deleted file mode 100644 index 3098f99..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/fixtures/resolv.conf.1 +++ /dev/null @@ -1,5 +0,0 @@ -domain company.com -nameserver 10.200.3.249 -nameserver 10.200.3.250:5353 -nameserver 2001:4860:4860::8844 -nameserver [10.0.0.1]:5353 diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/fqdn.go b/vendor/github.com/go-acme/lego/challenge/dns01/fqdn.go deleted file mode 100644 index c238c8c..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/fqdn.go +++ /dev/null @@ -1,19 +0,0 @@ -package dns01 - -// ToFqdn converts the name into a fqdn appending a trailing dot. -func ToFqdn(name string) string { - n := len(name) - if n == 0 || name[n-1] == '.' { - return name - } - return name + "." -} - -// UnFqdn converts the fqdn into a name removing the trailing dot. -func UnFqdn(name string) string { - n := len(name) - if n != 0 && name[n-1] == '.' { - return name[:n-1] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/fqdn_test.go b/vendor/github.com/go-acme/lego/challenge/dns01/fqdn_test.go deleted file mode 100644 index ab7be2a..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/fqdn_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package dns01 - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestToFqdn(t *testing.T) { - testCases := []struct { - desc string - domain string - expected string - }{ - { - desc: "simple", - domain: "foo.bar.com", - expected: "foo.bar.com.", - }, - { - desc: "already FQDN", - domain: "foo.bar.com.", - expected: "foo.bar.com.", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - fqdn := ToFqdn(test.domain) - assert.Equal(t, test.expected, fqdn) - }) - } -} - -func TestUnFqdn(t *testing.T) { - testCases := []struct { - desc string - fqdn string - expected string - }{ - { - desc: "simple", - fqdn: "foo.bar.com.", - expected: "foo.bar.com", - }, - { - desc: "already domain", - fqdn: "foo.bar.com", - expected: "foo.bar.com", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - domain := UnFqdn(test.fqdn) - - assert.Equal(t, test.expected, domain) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/nameserver.go b/vendor/github.com/go-acme/lego/challenge/dns01/nameserver.go deleted file mode 100644 index 03f1a8d..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/nameserver.go +++ /dev/null @@ -1,232 +0,0 @@ -package dns01 - -import ( - "fmt" - "net" - "strings" - "sync" - "time" - - "github.com/miekg/dns" -) - -const defaultResolvConf = "/etc/resolv.conf" - -// dnsTimeout is used to override the default DNS timeout of 10 seconds. -var dnsTimeout = 10 * time.Second - -var ( - fqdnToZone = map[string]string{} - muFqdnToZone sync.Mutex -) - -var defaultNameservers = []string{ - "google-public-dns-a.google.com:53", - "google-public-dns-b.google.com:53", -} - -// recursiveNameservers are used to pre-check DNS propagation -var recursiveNameservers = getNameservers(defaultResolvConf, defaultNameservers) - -// ClearFqdnCache clears the cache of fqdn to zone mappings. Primarily used in testing. -func ClearFqdnCache() { - muFqdnToZone.Lock() - fqdnToZone = map[string]string{} - muFqdnToZone.Unlock() -} - -func AddDNSTimeout(timeout time.Duration) ChallengeOption { - return func(_ *Challenge) error { - dnsTimeout = timeout - return nil - } -} - -func AddRecursiveNameservers(nameservers []string) ChallengeOption { - return func(_ *Challenge) error { - recursiveNameservers = ParseNameservers(nameservers) - return nil - } -} - -// getNameservers attempts to get systems nameservers before falling back to the defaults -func getNameservers(path string, defaults []string) []string { - config, err := dns.ClientConfigFromFile(path) - if err != nil || len(config.Servers) == 0 { - return defaults - } - - return ParseNameservers(config.Servers) -} - -func ParseNameservers(servers []string) []string { - var resolvers []string - for _, resolver := range servers { - // ensure all servers have a port number - if _, _, err := net.SplitHostPort(resolver); err != nil { - resolvers = append(resolvers, net.JoinHostPort(resolver, "53")) - } else { - resolvers = append(resolvers, resolver) - } - } - return resolvers -} - -// lookupNameservers returns the authoritative nameservers for the given fqdn. -func lookupNameservers(fqdn string) ([]string, error) { - var authoritativeNss []string - - zone, err := FindZoneByFqdn(fqdn) - if err != nil { - return nil, fmt.Errorf("could not determine the zone: %v", err) - } - - r, err := dnsQuery(zone, dns.TypeNS, recursiveNameservers, true) - if err != nil { - return nil, err - } - - for _, rr := range r.Answer { - if ns, ok := rr.(*dns.NS); ok { - authoritativeNss = append(authoritativeNss, strings.ToLower(ns.Ns)) - } - } - - if len(authoritativeNss) > 0 { - return authoritativeNss, nil - } - return nil, fmt.Errorf("could not determine authoritative nameservers") -} - -// FindZoneByFqdn determines the zone apex for the given fqdn -// by recursing up the domain labels until the nameserver returns a SOA record in the answer section. -func FindZoneByFqdn(fqdn string) (string, error) { - return FindZoneByFqdnCustom(fqdn, recursiveNameservers) -} - -// FindZoneByFqdnCustom determines the zone apex for the given fqdn -// by recursing up the domain labels until the nameserver returns a SOA record in the answer section. -func FindZoneByFqdnCustom(fqdn string, nameservers []string) (string, error) { - muFqdnToZone.Lock() - defer muFqdnToZone.Unlock() - - // Do we have it cached? - if zone, ok := fqdnToZone[fqdn]; ok { - return zone, nil - } - - var err error - var in *dns.Msg - - labelIndexes := dns.Split(fqdn) - for _, index := range labelIndexes { - domain := fqdn[index:] - - in, err = dnsQuery(domain, dns.TypeSOA, nameservers, true) - if err != nil { - continue - } - - if in == nil { - continue - } - - switch in.Rcode { - case dns.RcodeSuccess: - // Check if we got a SOA RR in the answer section - - if len(in.Answer) == 0 { - continue - } - - // CNAME records cannot/should not exist at the root of a zone. - // So we skip a domain when a CNAME is found. - if dnsMsgContainsCNAME(in) { - continue - } - - for _, ans := range in.Answer { - if soa, ok := ans.(*dns.SOA); ok { - zone := soa.Hdr.Name - fqdnToZone[fqdn] = zone - return zone, nil - } - } - case dns.RcodeNameError: - // NXDOMAIN - default: - // Any response code other than NOERROR and NXDOMAIN is treated as error - return "", fmt.Errorf("unexpected response code '%s' for %s", dns.RcodeToString[in.Rcode], domain) - } - } - - return "", fmt.Errorf("could not find the start of authority for %s%s", fqdn, formatDNSError(in, err)) -} - -// dnsMsgContainsCNAME checks for a CNAME answer in msg -func dnsMsgContainsCNAME(msg *dns.Msg) bool { - for _, ans := range msg.Answer { - if _, ok := ans.(*dns.CNAME); ok { - return true - } - } - return false -} - -func dnsQuery(fqdn string, rtype uint16, nameservers []string, recursive bool) (*dns.Msg, error) { - m := createDNSMsg(fqdn, rtype, recursive) - - var in *dns.Msg - var err error - - for _, ns := range nameservers { - in, err = sendDNSQuery(m, ns) - if err == nil && len(in.Answer) > 0 { - break - } - } - return in, err -} - -func createDNSMsg(fqdn string, rtype uint16, recursive bool) *dns.Msg { - m := new(dns.Msg) - m.SetQuestion(fqdn, rtype) - m.SetEdns0(4096, false) - - if !recursive { - m.RecursionDesired = false - } - - return m -} - -func sendDNSQuery(m *dns.Msg, ns string) (*dns.Msg, error) { - udp := &dns.Client{Net: "udp", Timeout: dnsTimeout} - in, _, err := udp.Exchange(m, ns) - - if in != nil && in.Truncated { - tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout} - // If the TCP request succeeds, the err will reset to nil - in, _, err = tcp.Exchange(m, ns) - } - - return in, err -} - -func formatDNSError(msg *dns.Msg, err error) string { - var parts []string - - if msg != nil { - parts = append(parts, dns.RcodeToString[msg.Rcode]) - } - - if err != nil { - parts = append(parts, fmt.Sprintf("%v", err)) - } - - if len(parts) > 0 { - return ": " + strings.Join(parts, " ") - } - - return "" -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/nameserver_test.go b/vendor/github.com/go-acme/lego/challenge/dns01/nameserver_test.go deleted file mode 100644 index 37b73c7..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/nameserver_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package dns01 - -import ( - "sort" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestLookupNameserversOK(t *testing.T) { - testCases := []struct { - fqdn string - nss []string - }{ - { - fqdn: "books.google.com.ng.", - nss: []string{"ns1.google.com.", "ns2.google.com.", "ns3.google.com.", "ns4.google.com."}, - }, - { - fqdn: "www.google.com.", - nss: []string{"ns1.google.com.", "ns2.google.com.", "ns3.google.com.", "ns4.google.com."}, - }, - { - fqdn: "physics.georgetown.edu.", - nss: []string{"ns4.georgetown.edu.", "ns5.georgetown.edu.", "ns6.georgetown.edu."}, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.fqdn, func(t *testing.T) { - t.Parallel() - - nss, err := lookupNameservers(test.fqdn) - require.NoError(t, err) - - sort.Strings(nss) - sort.Strings(test.nss) - - assert.EqualValues(t, test.nss, nss) - }) - } -} - -func TestLookupNameserversErr(t *testing.T) { - testCases := []struct { - desc string - fqdn string - error string - }{ - { - desc: "invalid tld", - fqdn: "_null.n0n0.", - error: "could not determine the zone", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - _, err := lookupNameservers(test.fqdn) - require.Error(t, err) - assert.Contains(t, err.Error(), test.error) - }) - } -} - -func TestFindZoneByFqdnCustom(t *testing.T) { - testCases := []struct { - desc string - fqdn string - zone string - nameservers []string - expectedError string - }{ - { - desc: "domain is a CNAME", - fqdn: "mail.google.com.", - zone: "google.com.", - nameservers: recursiveNameservers, - }, - { - desc: "domain is a non-existent subdomain", - fqdn: "foo.google.com.", - zone: "google.com.", - nameservers: recursiveNameservers, - }, - { - desc: "domain is a eTLD", - fqdn: "example.com.ac.", - zone: "ac.", - nameservers: recursiveNameservers, - }, - { - desc: "domain is a cross-zone CNAME", - fqdn: "cross-zone-example.assets.sh.", - zone: "assets.sh.", - nameservers: recursiveNameservers, - }, - { - desc: "NXDOMAIN", - fqdn: "test.loho.jkl.", - zone: "loho.jkl.", - nameservers: []string{"1.1.1.1:53"}, - expectedError: "could not find the start of authority for test.loho.jkl.: NXDOMAIN", - }, - { - desc: "several non existent nameservers", - fqdn: "mail.google.com.", - zone: "google.com.", - nameservers: []string{":7053", ":8053", "1.1.1.1:53"}, - }, - { - desc: "only non existent nameservers", - fqdn: "mail.google.com.", - zone: "google.com.", - nameservers: []string{":7053", ":8053", ":9053"}, - expectedError: "could not find the start of authority for mail.google.com.: read udp", - }, - { - desc: "no nameservers", - fqdn: "test.ldez.com.", - zone: "ldez.com.", - nameservers: []string{}, - expectedError: "could not find the start of authority for test.ldez.com.", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - ClearFqdnCache() - - zone, err := FindZoneByFqdnCustom(test.fqdn, test.nameservers) - if test.expectedError != "" { - require.Error(t, err) - assert.Contains(t, err.Error(), test.expectedError) - } else { - require.NoError(t, err) - assert.Equal(t, test.zone, zone) - } - }) - } -} - -func TestResolveConfServers(t *testing.T) { - var testCases = []struct { - fixture string - expected []string - defaults []string - }{ - { - fixture: "fixtures/resolv.conf.1", - defaults: []string{"127.0.0.1:53"}, - expected: []string{"10.200.3.249:53", "10.200.3.250:5353", "[2001:4860:4860::8844]:53", "[10.0.0.1]:5353"}, - }, - { - fixture: "fixtures/resolv.conf.nonexistant", - defaults: []string{"127.0.0.1:53"}, - expected: []string{"127.0.0.1:53"}, - }, - } - - for _, test := range testCases { - t.Run(test.fixture, func(t *testing.T) { - - result := getNameservers(test.fixture, test.defaults) - - sort.Strings(result) - sort.Strings(test.expected) - - assert.Equal(t, test.expected, result) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/precheck.go b/vendor/github.com/go-acme/lego/challenge/dns01/precheck.go deleted file mode 100644 index 00e0985..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/precheck.go +++ /dev/null @@ -1,127 +0,0 @@ -package dns01 - -import ( - "errors" - "fmt" - "net" - "strings" - - "github.com/miekg/dns" -) - -// PreCheckFunc checks DNS propagation before notifying ACME that the DNS challenge is ready. -type PreCheckFunc func(fqdn, value string) (bool, error) - -// WrapPreCheckFunc wraps a PreCheckFunc in order to do extra operations before or after -// the main check, put it in a loop, etc. -type WrapPreCheckFunc func(domain, fqdn, value string, check PreCheckFunc) (bool, error) - -// WrapPreCheck Allow to define checks before notifying ACME that the DNS challenge is ready. -func WrapPreCheck(wrap WrapPreCheckFunc) ChallengeOption { - return func(chlg *Challenge) error { - chlg.preCheck.checkFunc = wrap - return nil - } -} - -// AddPreCheck Allow to define checks before notifying ACME that the DNS challenge is ready. -// Deprecated: use WrapPreCheck instead. -func AddPreCheck(preCheck PreCheckFunc) ChallengeOption { - // Prevent race condition - check := preCheck - return func(chlg *Challenge) error { - chlg.preCheck.checkFunc = func(_, fqdn, value string, _ PreCheckFunc) (bool, error) { - if check == nil { - return false, errors.New("invalid preCheck: preCheck is nil") - } - return check(fqdn, value) - } - return nil - } -} - -func DisableCompletePropagationRequirement() ChallengeOption { - return func(chlg *Challenge) error { - chlg.preCheck.requireCompletePropagation = false - return nil - } -} - -type preCheck struct { - // checks DNS propagation before notifying ACME that the DNS challenge is ready. - checkFunc WrapPreCheckFunc - // require the TXT record to be propagated to all authoritative name servers - requireCompletePropagation bool -} - -func newPreCheck() preCheck { - return preCheck{ - requireCompletePropagation: true, - } -} - -func (p preCheck) call(domain, fqdn, value string) (bool, error) { - if p.checkFunc == nil { - return p.checkDNSPropagation(fqdn, value) - } - - return p.checkFunc(domain, fqdn, value, p.checkDNSPropagation) -} - -// checkDNSPropagation checks if the expected TXT record has been propagated to all authoritative nameservers. -func (p preCheck) checkDNSPropagation(fqdn, value string) (bool, error) { - // Initial attempt to resolve at the recursive NS - r, err := dnsQuery(fqdn, dns.TypeTXT, recursiveNameservers, true) - if err != nil { - return false, err - } - - if !p.requireCompletePropagation { - return true, nil - } - - if r.Rcode == dns.RcodeSuccess { - fqdn = updateDomainWithCName(r, fqdn) - } - - authoritativeNss, err := lookupNameservers(fqdn) - if err != nil { - return false, err - } - - return checkAuthoritativeNss(fqdn, value, authoritativeNss) -} - -// checkAuthoritativeNss queries each of the given nameservers for the expected TXT record. -func checkAuthoritativeNss(fqdn, value string, nameservers []string) (bool, error) { - for _, ns := range nameservers { - r, err := dnsQuery(fqdn, dns.TypeTXT, []string{net.JoinHostPort(ns, "53")}, false) - if err != nil { - return false, err - } - - if r.Rcode != dns.RcodeSuccess { - return false, fmt.Errorf("NS %s returned %s for %s", ns, dns.RcodeToString[r.Rcode], fqdn) - } - - var records []string - - var found bool - for _, rr := range r.Answer { - if txt, ok := rr.(*dns.TXT); ok { - record := strings.Join(txt.Txt, "") - records = append(records, record) - if record == value { - found = true - break - } - } - } - - if !found { - return false, fmt.Errorf("NS %s did not return the expected TXT record [fqdn: %s, value: %s]: %s", ns, fqdn, value, strings.Join(records, " ,")) - } - } - - return true, nil -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/precheck_test.go b/vendor/github.com/go-acme/lego/challenge/dns01/precheck_test.go deleted file mode 100644 index 05e2049..0000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/precheck_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package dns01 - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCheckDNSPropagation(t *testing.T) { - testCases := []struct { - desc string - fqdn string - value string - expectError bool - }{ - { - desc: "success", - fqdn: "postman-echo.com.", - value: "postman-domain-verification=c85de626cb79d941310696e06558e2e790223802f3697dfbdcaf65510152d52c", - }, - { - desc: "no TXT record", - fqdn: "acme-staging.api.letsencrypt.org.", - value: "fe01=", - expectError: true, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - ClearFqdnCache() - - check := newPreCheck() - - ok, err := check.checkDNSPropagation(test.fqdn, test.value) - if test.expectError { - assert.Errorf(t, err, "PreCheckDNS must failed for %s", test.fqdn) - assert.False(t, ok, "PreCheckDNS must failed for %s", test.fqdn) - } else { - assert.NoErrorf(t, err, "PreCheckDNS failed for %s", test.fqdn) - assert.True(t, ok, "PreCheckDNS failed for %s", test.fqdn) - } - }) - } -} - -func TestCheckAuthoritativeNss(t *testing.T) { - testCases := []struct { - desc string - fqdn, value string - ns []string - expected bool - }{ - { - desc: "TXT RR w/ expected value", - fqdn: "8.8.8.8.asn.routeviews.org.", - value: "151698.8.8.024", - ns: []string{"asnums.routeviews.org."}, - expected: true, - }, - { - desc: "No TXT RR", - fqdn: "ns1.google.com.", - ns: []string{"ns2.google.com."}, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - ClearFqdnCache() - - ok, _ := checkAuthoritativeNss(test.fqdn, test.value, test.ns) - assert.Equal(t, test.expected, ok, test.fqdn) - }) - } -} - -func TestCheckAuthoritativeNssErr(t *testing.T) { - testCases := []struct { - desc string - fqdn, value string - ns []string - error string - }{ - { - desc: "TXT RR /w unexpected value", - fqdn: "8.8.8.8.asn.routeviews.org.", - value: "fe01=", - ns: []string{"asnums.routeviews.org."}, - error: "did not return the expected TXT record", - }, - { - desc: "No TXT RR", - fqdn: "ns1.google.com.", - value: "fe01=", - ns: []string{"ns2.google.com."}, - error: "did not return the expected TXT record", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - ClearFqdnCache() - - _, err := checkAuthoritativeNss(test.fqdn, test.value, test.ns) - require.Error(t, err) - assert.Contains(t, err.Error(), test.error) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge.go b/vendor/github.com/go-acme/lego/challenge/http01/http_challenge.go deleted file mode 100644 index c1cf3d4..0000000 --- a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge.go +++ /dev/null @@ -1,65 +0,0 @@ -package http01 - -import ( - "fmt" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" -) - -type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error - -// ChallengePath returns the URL path for the `http-01` challenge -func ChallengePath(token string) string { - return "/.well-known/acme-challenge/" + token -} - -type Challenge struct { - core *api.Core - validate ValidateFunc - provider challenge.Provider -} - -func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge { - return &Challenge{ - core: core, - validate: validate, - provider: provider, - } -} - -func (c *Challenge) SetProvider(provider challenge.Provider) { - c.provider = provider -} - -func (c *Challenge) Solve(authz acme.Authorization) error { - domain := challenge.GetTargetedDomain(authz) - log.Infof("[%s] acme: Trying to solve HTTP-01", domain) - - chlng, err := challenge.FindChallenge(challenge.HTTP01, authz) - if err != nil { - return err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth) - if err != nil { - return fmt.Errorf("[%s] acme: error presenting token: %v", domain, err) - } - defer func() { - err := c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth) - if err != nil { - log.Warnf("[%s] acme: error cleaning up: %v", domain, err) - } - }() - - chlng.KeyAuthorization = keyAuth - return c.validate(c.core, domain, chlng) -} diff --git a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_server.go b/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_server.go deleted file mode 100644 index 9f44291..0000000 --- a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_server.go +++ /dev/null @@ -1,96 +0,0 @@ -package http01 - -import ( - "fmt" - "net" - "net/http" - "strings" - - "github.com/go-acme/lego/log" -) - -// ProviderServer implements ChallengeProvider for `http-01` challenge -// It may be instantiated without using the NewProviderServer function if -// you want only to use the default values. -type ProviderServer struct { - iface string - port string - done chan bool - listener net.Listener -} - -// NewProviderServer creates a new ProviderServer on the selected interface and port. -// Setting iface and / or port to an empty string will make the server fall back to -// the "any" interface and port 80 respectively. -func NewProviderServer(iface, port string) *ProviderServer { - return &ProviderServer{iface: iface, port: port} -} - -// Present starts a web server and makes the token available at `ChallengePath(token)` for web requests. -func (s *ProviderServer) Present(domain, token, keyAuth string) error { - if s.port == "" { - s.port = "80" - } - - var err error - s.listener, err = net.Listen("tcp", s.GetAddress()) - if err != nil { - return fmt.Errorf("could not start HTTP server for challenge -> %v", err) - } - - s.done = make(chan bool) - go s.serve(domain, token, keyAuth) - return nil -} - -func (s *ProviderServer) GetAddress() string { - return net.JoinHostPort(s.iface, s.port) -} - -// CleanUp closes the HTTP server and removes the token from `ChallengePath(token)` -func (s *ProviderServer) CleanUp(domain, token, keyAuth string) error { - if s.listener == nil { - return nil - } - s.listener.Close() - <-s.done - return nil -} - -func (s *ProviderServer) serve(domain, token, keyAuth string) { - path := ChallengePath(token) - - // The handler validates the HOST header and request type. - // For validation it then writes the token the server returned with the challenge - mux := http.NewServeMux() - mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(r.Host, domain) && r.Method == http.MethodGet { - w.Header().Add("Content-Type", "text/plain") - _, err := w.Write([]byte(keyAuth)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - log.Infof("[%s] Served key authentication", domain) - } else { - log.Warnf("Received request for domain %s with method %s but the domain did not match any challenge. Please ensure your are passing the HOST header properly.", r.Host, r.Method) - _, err := w.Write([]byte("TEST")) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - } - }) - - httpServer := &http.Server{Handler: mux} - - // Once httpServer is shut down - // we don't want any lingering connections, so disable KeepAlives. - httpServer.SetKeepAlivesEnabled(false) - - err := httpServer.Serve(s.listener) - if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - log.Println(err) - } - s.done <- true -} diff --git a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_test.go b/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_test.go deleted file mode 100644 index eff40b2..0000000 --- a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package http01 - -import ( - "crypto/rand" - "crypto/rsa" - "io/ioutil" - "net/http" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestChallenge(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - providerServer := &ProviderServer{port: "23457"} - - validate := func(_ *api.Core, _ string, chlng acme.Challenge) error { - uri := "http://localhost" + providerServer.GetAddress() + ChallengePath(chlng.Token) - - resp, err := http.DefaultClient.Get(uri) - if err != nil { - return err - } - defer resp.Body.Close() - - if want := "text/plain"; resp.Header.Get("Content-Type") != want { - t.Errorf("Get(%q) Content-Type: got %q, want %q", uri, resp.Header.Get("Content-Type"), want) - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - bodyStr := string(body) - - if bodyStr != chlng.KeyAuthorization { - t.Errorf("Get(%q) Body: got %q, want %q", uri, bodyStr, chlng.KeyAuthorization) - } - - return nil - } - - privateKey, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - solver := NewChallenge(core, validate, providerServer) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: "localhost:23457", - }, - Challenges: []acme.Challenge{ - {Type: challenge.HTTP01.String(), Token: "http1"}, - }, - } - - err = solver.Solve(authz) - require.NoError(t, err) -} - -func TestChallengeInvalidPort(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - privateKey, err := rsa.GenerateKey(rand.Reader, 128) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - validate := func(_ *api.Core, _ string, _ acme.Challenge) error { return nil } - - solver := NewChallenge(core, validate, &ProviderServer{port: "123456"}) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: "localhost:123456", - }, - Challenges: []acme.Challenge{ - {Type: challenge.HTTP01.String(), Token: "http2"}, - }, - } - - err = solver.Solve(authz) - require.Error(t, err) - assert.Contains(t, err.Error(), "invalid port") - assert.Contains(t, err.Error(), "123456") -} diff --git a/vendor/github.com/go-acme/lego/challenge/provider.go b/vendor/github.com/go-acme/lego/challenge/provider.go deleted file mode 100644 index d7cc213..0000000 --- a/vendor/github.com/go-acme/lego/challenge/provider.go +++ /dev/null @@ -1,28 +0,0 @@ -package challenge - -import "time" - -// Provider enables implementing a custom challenge -// provider. Present presents the solution to a challenge available to -// be solved. CleanUp will be called by the challenge if Present ends -// in a non-error state. -type Provider interface { - Present(domain, token, keyAuth string) error - CleanUp(domain, token, keyAuth string) error -} - -// ProviderTimeout allows for implementing a -// Provider where an unusually long timeout is required when -// waiting for an ACME challenge to be satisfied, such as when -// checking for DNS record propagation. If an implementor of a -// Provider provides a Timeout method, then the return values -// of the Timeout method will be used when appropriate by the acme -// package. The interval value is the time between checks. -// -// The default values used for timeout and interval are 60 seconds and -// 2 seconds respectively. These are used when no Timeout method is -// defined for the Provider. -type ProviderTimeout interface { - Provider - Timeout() (timeout, interval time.Duration) -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/errors.go b/vendor/github.com/go-acme/lego/challenge/resolver/errors.go deleted file mode 100644 index 9d60914..0000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/errors.go +++ /dev/null @@ -1,25 +0,0 @@ -package resolver - -import ( - "bytes" - "fmt" - "sort" -) - -// obtainError is returned when there are specific errors available per domain. -type obtainError map[string]error - -func (e obtainError) Error() string { - buffer := bytes.NewBufferString("acme: Error -> One or more domains had a problem:\n") - - var domains []string - for domain := range e { - domains = append(domains, domain) - } - sort.Strings(domains) - - for _, domain := range domains { - buffer.WriteString(fmt.Sprintf("[%s] %s\n", domain, e[domain])) - } - return buffer.String() -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/prober.go b/vendor/github.com/go-acme/lego/challenge/resolver/prober.go deleted file mode 100644 index b787caf..0000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/prober.go +++ /dev/null @@ -1,173 +0,0 @@ -package resolver - -import ( - "fmt" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" -) - -// Interface for all challenge solvers to implement. -type solver interface { - Solve(authorization acme.Authorization) error -} - -// Interface for challenges like dns, where we can set a record in advance for ALL challenges. -// This saves quite a bit of time vs creating the records and solving them serially. -type preSolver interface { - PreSolve(authorization acme.Authorization) error -} - -// Interface for challenges like dns, where we can solve all the challenges before to delete them. -type cleanup interface { - CleanUp(authorization acme.Authorization) error -} - -type sequential interface { - Sequential() (bool, time.Duration) -} - -// an authz with the solver we have chosen and the index of the challenge associated with it -type selectedAuthSolver struct { - authz acme.Authorization - solver solver -} - -type Prober struct { - solverManager *SolverManager -} - -func NewProber(solverManager *SolverManager) *Prober { - return &Prober{ - solverManager: solverManager, - } -} - -// Solve Looks through the challenge combinations to find a solvable match. -// Then solves the challenges in series and returns. -func (p *Prober) Solve(authorizations []acme.Authorization) error { - failures := make(obtainError) - - var authSolvers []*selectedAuthSolver - var authSolversSequential []*selectedAuthSolver - - // Loop through the resources, basically through the domains. - // First pass just selects a solver for each authz. - for _, authz := range authorizations { - domain := challenge.GetTargetedDomain(authz) - if authz.Status == acme.StatusValid { - // Boulder might recycle recent validated authz (see issue #267) - log.Infof("[%s] acme: authorization already valid; skipping challenge", domain) - continue - } - - if solvr := p.solverManager.chooseSolver(authz); solvr != nil { - authSolver := &selectedAuthSolver{authz: authz, solver: solvr} - - switch s := solvr.(type) { - case sequential: - if ok, _ := s.Sequential(); ok { - authSolversSequential = append(authSolversSequential, authSolver) - } else { - authSolvers = append(authSolvers, authSolver) - } - default: - authSolvers = append(authSolvers, authSolver) - } - } else { - failures[domain] = fmt.Errorf("[%s] acme: could not determine solvers", domain) - } - } - - parallelSolve(authSolvers, failures) - - sequentialSolve(authSolversSequential, failures) - - // Be careful not to return an empty failures map, - // for even an empty obtainError is a non-nil error value - if len(failures) > 0 { - return failures - } - return nil -} - -func sequentialSolve(authSolvers []*selectedAuthSolver, failures obtainError) { - for i, authSolver := range authSolvers { - // Submit the challenge - domain := challenge.GetTargetedDomain(authSolver.authz) - - if solvr, ok := authSolver.solver.(preSolver); ok { - err := solvr.PreSolve(authSolver.authz) - if err != nil { - failures[domain] = err - cleanUp(authSolver.solver, authSolver.authz) - continue - } - } - - // Solve challenge - err := authSolver.solver.Solve(authSolver.authz) - if err != nil { - failures[domain] = err - cleanUp(authSolver.solver, authSolver.authz) - continue - } - - // Clean challenge - cleanUp(authSolver.solver, authSolver.authz) - - if len(authSolvers)-1 > i { - solvr := authSolver.solver.(sequential) - _, interval := solvr.Sequential() - log.Infof("sequence: wait for %s", interval) - time.Sleep(interval) - } - } -} - -func parallelSolve(authSolvers []*selectedAuthSolver, failures obtainError) { - // For all valid preSolvers, first submit the challenges so they have max time to propagate - for _, authSolver := range authSolvers { - authz := authSolver.authz - if solvr, ok := authSolver.solver.(preSolver); ok { - err := solvr.PreSolve(authz) - if err != nil { - failures[challenge.GetTargetedDomain(authz)] = err - } - } - } - - defer func() { - // Clean all created TXT records - for _, authSolver := range authSolvers { - cleanUp(authSolver.solver, authSolver.authz) - } - }() - - // Finally solve all challenges for real - for _, authSolver := range authSolvers { - authz := authSolver.authz - domain := challenge.GetTargetedDomain(authz) - if failures[domain] != nil { - // already failed in previous loop - continue - } - - err := authSolver.solver.Solve(authz) - if err != nil { - failures[domain] = err - } - } -} - -func cleanUp(solvr solver, authz acme.Authorization) { - if solvr, ok := solvr.(cleanup); ok { - domain := challenge.GetTargetedDomain(authz) - err := solvr.CleanUp(authz) - if err != nil { - log.Warnf("[%s] acme: error cleaning up: %v ", domain, err) - } - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/prober_mock_test.go b/vendor/github.com/go-acme/lego/challenge/resolver/prober_mock_test.go deleted file mode 100644 index 0a594f6..0000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/prober_mock_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package resolver - -import ( - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/challenge" -) - -type preSolverMock struct { - preSolve map[string]error - solve map[string]error - cleanUp map[string]error -} - -func (s *preSolverMock) PreSolve(authorization acme.Authorization) error { - return s.preSolve[authorization.Identifier.Value] -} -func (s *preSolverMock) Solve(authorization acme.Authorization) error { - return s.solve[authorization.Identifier.Value] -} -func (s *preSolverMock) CleanUp(authorization acme.Authorization) error { - return s.cleanUp[authorization.Identifier.Value] -} - -func createStubAuthorizationHTTP01(domain, status string) acme.Authorization { - return acme.Authorization{ - Status: status, - Expires: time.Now(), - Identifier: acme.Identifier{ - Type: challenge.HTTP01.String(), - Value: domain, - }, - Challenges: []acme.Challenge{ - { - Type: challenge.HTTP01.String(), - Validated: time.Now(), - Error: nil, - }, - }, - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/prober_test.go b/vendor/github.com/go-acme/lego/challenge/resolver/prober_test.go deleted file mode 100644 index 0be6653..0000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/prober_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package resolver - -import ( - "errors" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/challenge" - "github.com/stretchr/testify/require" -) - -func TestProber_Solve(t *testing.T) { - testCases := []struct { - desc string - solvers map[challenge.Type]solver - authz []acme.Authorization - expectedError string - }{ - { - desc: "success", - solvers: map[challenge.Type]solver{ - challenge.HTTP01: &preSolverMock{ - preSolve: map[string]error{}, - solve: map[string]error{}, - cleanUp: map[string]error{}, - }, - }, - authz: []acme.Authorization{ - createStubAuthorizationHTTP01("acme.wtf", acme.StatusProcessing), - createStubAuthorizationHTTP01("lego.wtf", acme.StatusProcessing), - createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusProcessing), - }, - }, - { - desc: "already valid", - solvers: map[challenge.Type]solver{ - challenge.HTTP01: &preSolverMock{ - preSolve: map[string]error{}, - solve: map[string]error{}, - cleanUp: map[string]error{}, - }, - }, - authz: []acme.Authorization{ - createStubAuthorizationHTTP01("acme.wtf", acme.StatusValid), - createStubAuthorizationHTTP01("lego.wtf", acme.StatusValid), - createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusValid), - }, - }, - { - desc: "when preSolve fail, auth is flagged as error and skipped", - solvers: map[challenge.Type]solver{ - challenge.HTTP01: &preSolverMock{ - preSolve: map[string]error{ - "acme.wtf": errors.New("preSolve error acme.wtf"), - }, - solve: map[string]error{ - "acme.wtf": errors.New("solve error acme.wtf"), - }, - cleanUp: map[string]error{ - "acme.wtf": errors.New("clean error acme.wtf"), - }, - }, - }, - authz: []acme.Authorization{ - createStubAuthorizationHTTP01("acme.wtf", acme.StatusProcessing), - createStubAuthorizationHTTP01("lego.wtf", acme.StatusProcessing), - createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusProcessing), - }, - expectedError: `acme: Error -> One or more domains had a problem: -[acme.wtf] preSolve error acme.wtf -`, - }, - { - desc: "errors at different stages", - solvers: map[challenge.Type]solver{ - challenge.HTTP01: &preSolverMock{ - preSolve: map[string]error{ - "acme.wtf": errors.New("preSolve error acme.wtf"), - }, - solve: map[string]error{ - "acme.wtf": errors.New("solve error acme.wtf"), - "lego.wtf": errors.New("solve error lego.wtf"), - }, - cleanUp: map[string]error{ - "mydomain.wtf": errors.New("clean error mydomain.wtf"), - }, - }, - }, - authz: []acme.Authorization{ - createStubAuthorizationHTTP01("acme.wtf", acme.StatusProcessing), - createStubAuthorizationHTTP01("lego.wtf", acme.StatusProcessing), - createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusProcessing), - }, - expectedError: `acme: Error -> One or more domains had a problem: -[acme.wtf] preSolve error acme.wtf -[lego.wtf] solve error lego.wtf -`, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - prober := &Prober{ - solverManager: &SolverManager{solvers: test.solvers}, - } - - err := prober.Solve(test.authz) - if test.expectedError != "" { - require.EqualError(t, err, test.expectedError) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager.go b/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager.go deleted file mode 100644 index de6f02d..0000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager.go +++ /dev/null @@ -1,169 +0,0 @@ -package resolver - -import ( - "context" - "errors" - "fmt" - "sort" - "strconv" - "time" - - "github.com/cenkalti/backoff" - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/challenge/http01" - "github.com/go-acme/lego/challenge/tlsalpn01" - "github.com/go-acme/lego/log" -) - -type byType []acme.Challenge - -func (a byType) Len() int { return len(a) } -func (a byType) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byType) Less(i, j int) bool { return a[i].Type > a[j].Type } - -type SolverManager struct { - core *api.Core - solvers map[challenge.Type]solver -} - -func NewSolversManager(core *api.Core) *SolverManager { - return &SolverManager{ - solvers: map[challenge.Type]solver{}, - core: core, - } -} - -// SetHTTP01Provider specifies a custom provider p that can solve the given HTTP-01 challenge. -func (c *SolverManager) SetHTTP01Provider(p challenge.Provider) error { - c.solvers[challenge.HTTP01] = http01.NewChallenge(c.core, validate, p) - return nil -} - -// SetTLSALPN01Provider specifies a custom provider p that can solve the given TLS-ALPN-01 challenge. -func (c *SolverManager) SetTLSALPN01Provider(p challenge.Provider) error { - c.solvers[challenge.TLSALPN01] = tlsalpn01.NewChallenge(c.core, validate, p) - return nil -} - -// SetDNS01Provider specifies a custom provider p that can solve the given DNS-01 challenge. -func (c *SolverManager) SetDNS01Provider(p challenge.Provider, opts ...dns01.ChallengeOption) error { - c.solvers[challenge.DNS01] = dns01.NewChallenge(c.core, validate, p, opts...) - return nil -} - -// Remove Remove a challenge type from the available solvers. -func (c *SolverManager) Remove(chlgType challenge.Type) { - delete(c.solvers, chlgType) -} - -// Checks all challenges from the server in order and returns the first matching solver. -func (c *SolverManager) chooseSolver(authz acme.Authorization) solver { - // Allow to have a deterministic challenge order - sort.Sort(byType(authz.Challenges)) - - domain := challenge.GetTargetedDomain(authz) - for _, chlg := range authz.Challenges { - if solvr, ok := c.solvers[challenge.Type(chlg.Type)]; ok { - log.Infof("[%s] acme: use %s solver", domain, chlg.Type) - return solvr - } - log.Infof("[%s] acme: Could not find solver for: %s", domain, chlg.Type) - } - - return nil -} - -func validate(core *api.Core, domain string, chlg acme.Challenge) error { - chlng, err := core.Challenges.New(chlg.URL) - if err != nil { - return fmt.Errorf("failed to initiate challenge: %v", err) - } - - valid, err := checkChallengeStatus(chlng) - if err != nil { - return err - } - - if valid { - log.Infof("[%s] The server validated our request", domain) - return nil - } - - ra, err := strconv.Atoi(chlng.RetryAfter) - if err != nil { - // The ACME server MUST return a Retry-After. - // If it doesn't, we'll just poll hard. - // Boulder does not implement the ability to retry challenges or the Retry-After header. - // https://github.com/letsencrypt/boulder/blob/master/docs/acme-divergences.md#section-82 - ra = 5 - } - initialInterval := time.Duration(ra) * time.Second - - bo := backoff.NewExponentialBackOff() - bo.InitialInterval = initialInterval - bo.MaxInterval = 10 * initialInterval - bo.MaxElapsedTime = 100 * initialInterval - - ctx, cancel := context.WithCancel(context.Background()) - - // After the path is sent, the ACME server will access our server. - // Repeatedly check the server for an updated status on our request. - operation := func() error { - authz, err := core.Authorizations.Get(chlng.AuthorizationURL) - if err != nil { - cancel() - return err - } - - valid, err := checkAuthorizationStatus(authz) - if err != nil { - cancel() - return err - } - - if valid { - log.Infof("[%s] The server validated our request", domain) - return nil - } - - return errors.New("the server didn't respond to our request") - } - - return backoff.Retry(operation, backoff.WithContext(bo, ctx)) -} - -func checkChallengeStatus(chlng acme.ExtendedChallenge) (bool, error) { - switch chlng.Status { - case acme.StatusValid: - return true, nil - case acme.StatusPending, acme.StatusProcessing: - return false, nil - case acme.StatusInvalid: - return false, chlng.Error - default: - return false, errors.New("the server returned an unexpected state") - } -} - -func checkAuthorizationStatus(authz acme.Authorization) (bool, error) { - switch authz.Status { - case acme.StatusValid: - return true, nil - case acme.StatusPending, acme.StatusProcessing: - return false, nil - case acme.StatusDeactivated, acme.StatusExpired, acme.StatusRevoked: - return false, fmt.Errorf("the authorization state %s", authz.Status) - case acme.StatusInvalid: - for _, chlg := range authz.Challenges { - if chlg.Status == acme.StatusInvalid && chlg.Error != nil { - return false, chlg.Error - } - } - return false, fmt.Errorf("the authorization state %s", authz.Status) - default: - return false, errors.New("the server returned an unexpected state") - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager_test.go b/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager_test.go deleted file mode 100644 index 97bd807..0000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager_test.go +++ /dev/null @@ -1,179 +0,0 @@ -package resolver - -import ( - "crypto/rand" - "crypto/rsa" - "fmt" - "io/ioutil" - "net/http" - "sort" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - jose "gopkg.in/square/go-jose.v2" -) - -func TestByType(t *testing.T) { - challenges := []acme.Challenge{ - {Type: "dns-01"}, {Type: "tlsalpn-01"}, {Type: "http-01"}, - } - - sort.Sort(byType(challenges)) - - expected := []acme.Challenge{ - {Type: "tlsalpn-01"}, {Type: "http-01"}, {Type: "dns-01"}, - } - - assert.Equal(t, expected, challenges) -} - -func TestValidate(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - var statuses []string - - privateKey, _ := rsa.GenerateKey(rand.Reader, 512) - - mux.HandleFunc("/chlg", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - if err := validateNoBody(privateKey, r); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - w.Header().Set("Link", "<"+apiURL+`/my-authz>; rel="up"`) - - st := statuses[0] - statuses = statuses[1:] - - chlg := &acme.Challenge{Type: "http-01", Status: st, URL: "http://example.com/", Token: "token"} - if st == acme.StatusInvalid { - chlg.Error = &acme.ProblemDetails{} - } - - err := tester.WriteJSONResponse(w, chlg) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - mux.HandleFunc("/my-authz", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - st := statuses[0] - statuses = statuses[1:] - - authorization := acme.Authorization{ - Status: st, - Challenges: []acme.Challenge{}, - } - - if st == acme.StatusInvalid { - chlg := acme.Challenge{ - Status: acme.StatusInvalid, - Error: &acme.ProblemDetails{}, - } - authorization.Challenges = append(authorization.Challenges, chlg) - } - - err := tester.WriteJSONResponse(w, authorization) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - testCases := []struct { - name string - statuses []string - want string - }{ - { - name: "POST-unexpected", - statuses: []string{"weird"}, - want: "unexpected", - }, - { - name: "POST-valid", - statuses: []string{acme.StatusValid}, - }, - { - name: "POST-invalid", - statuses: []string{acme.StatusInvalid}, - want: "error", - }, - { - name: "POST-pending-unexpected", - statuses: []string{acme.StatusPending, "weird"}, - want: "unexpected", - }, - { - name: "POST-pending-valid", - statuses: []string{acme.StatusPending, acme.StatusValid}, - }, - { - name: "POST-pending-invalid", - statuses: []string{acme.StatusPending, acme.StatusInvalid}, - want: "error", - }, - } - - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - statuses = test.statuses - - err := validate(core, "example.com", acme.Challenge{Type: "http-01", Token: "token", URL: apiURL + "/chlg"}) - if test.want == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.want) - } - }) - } -} - -// validateNoBody reads the http.Request POST body, parses the JWS and validates it to read the body. -// If there is an error doing this, -// or if the JWS body is not the empty JSON payload "{}" or a POST-as-GET payload "" an error is returned. -// We use this to verify challenge POSTs to the ts below do not send a JWS body. -func validateNoBody(privateKey *rsa.PrivateKey, r *http.Request) error { - reqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - return err - } - - jws, err := jose.ParseSigned(string(reqBody)) - if err != nil { - return err - } - - body, err := jws.Verify(&jose.JSONWebKey{ - Key: privateKey.Public(), - Algorithm: "RSA", - }) - if err != nil { - return err - } - - if bodyStr := string(body); bodyStr != "{}" && bodyStr != "" { - return fmt.Errorf(`expected JWS POST body "{}" or "", got %q`, bodyStr) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge.go b/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge.go deleted file mode 100644 index a3fa7ef..0000000 --- a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge.go +++ /dev/null @@ -1,129 +0,0 @@ -package tlsalpn01 - -import ( - "crypto/rsa" - "crypto/sha256" - "crypto/tls" - "crypto/x509/pkix" - "encoding/asn1" - "fmt" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" -) - -// idPeAcmeIdentifierV1 is the SMI Security for PKIX Certification Extension OID referencing the ACME extension. -// Reference: https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-5.1 -var idPeAcmeIdentifierV1 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31} - -type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error - -type Challenge struct { - core *api.Core - validate ValidateFunc - provider challenge.Provider -} - -func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge { - return &Challenge{ - core: core, - validate: validate, - provider: provider, - } -} - -func (c *Challenge) SetProvider(provider challenge.Provider) { - c.provider = provider -} - -// Solve manages the provider to validate and solve the challenge. -func (c *Challenge) Solve(authz acme.Authorization) error { - domain := authz.Identifier.Value - log.Infof("[%s] acme: Trying to solve TLS-ALPN-01", challenge.GetTargetedDomain(authz)) - - chlng, err := challenge.FindChallenge(challenge.TLSALPN01, authz) - if err != nil { - return err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - err = c.provider.Present(domain, chlng.Token, keyAuth) - if err != nil { - return fmt.Errorf("[%s] acme: error presenting token: %v", challenge.GetTargetedDomain(authz), err) - } - defer func() { - err := c.provider.CleanUp(domain, chlng.Token, keyAuth) - if err != nil { - log.Warnf("[%s] acme: error cleaning up: %v", challenge.GetTargetedDomain(authz), err) - } - }() - - chlng.KeyAuthorization = keyAuth - return c.validate(c.core, domain, chlng) -} - -// ChallengeBlocks returns PEM blocks (certPEMBlock, keyPEMBlock) with the acmeValidation-v1 extension -// and domain name for the `tls-alpn-01` challenge. -func ChallengeBlocks(domain, keyAuth string) ([]byte, []byte, error) { - // Compute the SHA-256 digest of the key authorization. - zBytes := sha256.Sum256([]byte(keyAuth)) - - value, err := asn1.Marshal(zBytes[:sha256.Size]) - if err != nil { - return nil, nil, err - } - - // Add the keyAuth digest as the acmeValidation-v1 extension - // (marked as critical such that it won't be used by non-ACME software). - // Reference: https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-3 - extensions := []pkix.Extension{ - { - Id: idPeAcmeIdentifierV1, - Critical: true, - Value: value, - }, - } - - // Generate a new RSA key for the certificates. - tempPrivateKey, err := certcrypto.GeneratePrivateKey(certcrypto.RSA2048) - if err != nil { - return nil, nil, err - } - - rsaPrivateKey := tempPrivateKey.(*rsa.PrivateKey) - - // Generate the PEM certificate using the provided private key, domain, and extra extensions. - tempCertPEM, err := certcrypto.GeneratePemCert(rsaPrivateKey, domain, extensions) - if err != nil { - return nil, nil, err - } - - // Encode the private key into a PEM format. We'll need to use it to generate the x509 keypair. - rsaPrivatePEM := certcrypto.PEMEncode(rsaPrivateKey) - - return tempCertPEM, rsaPrivatePEM, nil -} - -// ChallengeCert returns a certificate with the acmeValidation-v1 extension -// and domain name for the `tls-alpn-01` challenge. -func ChallengeCert(domain, keyAuth string) (*tls.Certificate, error) { - tempCertPEM, rsaPrivatePEM, err := ChallengeBlocks(domain, keyAuth) - if err != nil { - return nil, err - } - - cert, err := tls.X509KeyPair(tempCertPEM, rsaPrivatePEM) - if err != nil { - return nil, err - } - - return &cert, nil -} diff --git a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_server.go b/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_server.go deleted file mode 100644 index 61e353b..0000000 --- a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_server.go +++ /dev/null @@ -1,95 +0,0 @@ -package tlsalpn01 - -import ( - "crypto/tls" - "fmt" - "net" - "net/http" - "strings" - - "github.com/go-acme/lego/log" -) - -const ( - // ACMETLS1Protocol is the ALPN Protocol ID for the ACME-TLS/1 Protocol. - ACMETLS1Protocol = "acme-tls/1" - - // defaultTLSPort is the port that the ProviderServer will default to - // when no other port is provided. - defaultTLSPort = "443" -) - -// ProviderServer implements ChallengeProvider for `TLS-ALPN-01` challenge. -// It may be instantiated without using the NewProviderServer -// if you want only to use the default values. -type ProviderServer struct { - iface string - port string - listener net.Listener -} - -// NewProviderServer creates a new ProviderServer on the selected interface and port. -// Setting iface and / or port to an empty string will make the server fall back to -// the "any" interface and port 443 respectively. -func NewProviderServer(iface, port string) *ProviderServer { - return &ProviderServer{iface: iface, port: port} -} - -func (s *ProviderServer) GetAddress() string { - return net.JoinHostPort(s.iface, s.port) -} - -// Present generates a certificate with a SHA-256 digest of the keyAuth provided -// as the acmeValidation-v1 extension value to conform to the ACME-TLS-ALPN spec. -func (s *ProviderServer) Present(domain, token, keyAuth string) error { - if s.port == "" { - // Fallback to port 443 if the port was not provided. - s.port = defaultTLSPort - } - - // Generate the challenge certificate using the provided keyAuth and domain. - cert, err := ChallengeCert(domain, keyAuth) - if err != nil { - return err - } - - // Place the generated certificate with the extension into the TLS config - // so that it can serve the correct details. - tlsConf := new(tls.Config) - tlsConf.Certificates = []tls.Certificate{*cert} - - // We must set that the `acme-tls/1` application level protocol is supported - // so that the protocol negotiation can succeed. Reference: - // https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-01#section-5.2 - tlsConf.NextProtos = []string{ACMETLS1Protocol} - - // Create the listener with the created tls.Config. - s.listener, err = tls.Listen("tcp", s.GetAddress(), tlsConf) - if err != nil { - return fmt.Errorf("could not start HTTPS server for challenge -> %v", err) - } - - // Shut the server down when we're finished. - go func() { - err := http.Serve(s.listener, nil) - if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - log.Println(err) - } - }() - - return nil -} - -// CleanUp closes the HTTPS server. -func (s *ProviderServer) CleanUp(domain, token, keyAuth string) error { - if s.listener == nil { - return nil - } - - // Server was created, close it. - if err := s.listener.Close(); err != nil && err != http.ErrServerClosed { - return err - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_test.go b/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_test.go deleted file mode 100644 index 99dfd8c..0000000 --- a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package tlsalpn01 - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "crypto/subtle" - "crypto/tls" - "encoding/asn1" - "net/http" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestChallenge(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - domain := "localhost:23457" - - mockValidate := func(_ *api.Core, _ string, chlng acme.Challenge) error { - conn, err := tls.Dial("tcp", domain, &tls.Config{ - InsecureSkipVerify: true, - }) - require.NoError(t, err, "Expected to connect to challenge server without an error") - - // Expect the server to only return one certificate - connState := conn.ConnectionState() - assert.Len(t, connState.PeerCertificates, 1, "Expected the challenge server to return exactly one certificate") - - remoteCert := connState.PeerCertificates[0] - assert.Len(t, remoteCert.DNSNames, 1, "Expected the challenge certificate to have exactly one DNSNames entry") - assert.Equal(t, domain, remoteCert.DNSNames[0], "challenge certificate DNSName ") - assert.NotEmpty(t, remoteCert.Extensions, "Expected the challenge certificate to contain extensions") - - idx := -1 - for i, ext := range remoteCert.Extensions { - if idPeAcmeIdentifierV1.Equal(ext.Id) { - idx = i - break - } - } - - require.NotEqual(t, -1, idx, "Expected the challenge certificate to contain an extension with the id-pe-acmeIdentifier id,") - - ext := remoteCert.Extensions[idx] - assert.True(t, ext.Critical, "Expected the challenge certificate id-pe-acmeIdentifier extension to be marked as critical") - - zBytes := sha256.Sum256([]byte(chlng.KeyAuthorization)) - value, err := asn1.Marshal(zBytes[:sha256.Size]) - require.NoError(t, err, "Expected marshaling of the keyAuth to return no error") - - if subtle.ConstantTimeCompare(value, ext.Value) != 1 { - t.Errorf("Expected the challenge certificate id-pe-acmeIdentifier extension to contain the SHA-256 digest of the keyAuth, %v, but was %v", zBytes[:], ext.Value) - } - - return nil - } - - privateKey, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - solver := NewChallenge( - core, - mockValidate, - &ProviderServer{port: "23457"}, - ) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: domain, - }, - Challenges: []acme.Challenge{ - {Type: challenge.TLSALPN01.String(), Token: "tlsalpn1"}, - }, - } - - err = solver.Solve(authz) - require.NoError(t, err) -} - -func TestChallengeInvalidPort(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - privateKey, err := rsa.GenerateKey(rand.Reader, 128) - require.NoError(t, err, "Could not generate test key") - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey) - require.NoError(t, err) - - solver := NewChallenge( - core, - func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }, - &ProviderServer{port: "123456"}, - ) - - authz := acme.Authorization{ - Identifier: acme.Identifier{ - Value: "localhost:123456", - }, - Challenges: []acme.Challenge{ - {Type: challenge.TLSALPN01.String(), Token: "tlsalpn1"}, - }, - } - - err = solver.Solve(authz) - require.Error(t, err) - assert.Contains(t, err.Error(), "invalid port") - assert.Contains(t, err.Error(), "123456") -} diff --git a/vendor/github.com/go-acme/lego/cmd/account.go b/vendor/github.com/go-acme/lego/cmd/account.go deleted file mode 100644 index b9990a5..0000000 --- a/vendor/github.com/go-acme/lego/cmd/account.go +++ /dev/null @@ -1,33 +0,0 @@ -package cmd - -import ( - "crypto" - - "github.com/go-acme/lego/registration" -) - -// Account represents a users local saved credentials -type Account struct { - Email string `json:"email"` - Registration *registration.Resource `json:"registration"` - key crypto.PrivateKey -} - -/** Implementation of the registration.User interface **/ - -// GetEmail returns the email address for the account -func (a *Account) GetEmail() string { - return a.Email -} - -// GetPrivateKey returns the private RSA account key. -func (a *Account) GetPrivateKey() crypto.PrivateKey { - return a.key -} - -// GetRegistration returns the server registration -func (a *Account) GetRegistration() *registration.Resource { - return a.Registration -} - -/** End **/ diff --git a/vendor/github.com/go-acme/lego/cmd/accounts_storage.go b/vendor/github.com/go-acme/lego/cmd/accounts_storage.go deleted file mode 100644 index 0a95853..0000000 --- a/vendor/github.com/go-acme/lego/cmd/accounts_storage.go +++ /dev/null @@ -1,243 +0,0 @@ -package cmd - -import ( - "crypto" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "net/url" - "os" - "path/filepath" - "strings" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/registration" - "github.com/urfave/cli" -) - -const ( - baseAccountsRootFolderName = "accounts" - baseKeysFolderName = "keys" - accountFileName = "account.json" -) - -// AccountsStorage A storage for account data. -// -// rootPath: -// -// ./.lego/accounts/ -// │ └── root accounts directory -// └── "path" option -// -// rootUserPath: -// -// ./.lego/accounts/localhost_14000/hubert@hubert.com/ -// │ │ │ └── userID ("email" option) -// │ │ └── CA server ("server" option) -// │ └── root accounts directory -// └── "path" option -// -// keysPath: -// -// ./.lego/accounts/localhost_14000/hubert@hubert.com/keys/ -// │ │ │ │ └── root keys directory -// │ │ │ └── userID ("email" option) -// │ │ └── CA server ("server" option) -// │ └── root accounts directory -// └── "path" option -// -// accountFilePath: -// -// ./.lego/accounts/localhost_14000/hubert@hubert.com/account.json -// │ │ │ │ └── account file -// │ │ │ └── userID ("email" option) -// │ │ └── CA server ("server" option) -// │ └── root accounts directory -// └── "path" option -// -type AccountsStorage struct { - userID string - rootPath string - rootUserPath string - keysPath string - accountFilePath string - ctx *cli.Context -} - -// NewAccountsStorage Creates a new AccountsStorage. -func NewAccountsStorage(ctx *cli.Context) *AccountsStorage { - // TODO: move to account struct? Currently MUST pass email. - email := getEmail(ctx) - - serverURL, err := url.Parse(ctx.GlobalString("server")) - if err != nil { - log.Fatal(err) - } - - rootPath := filepath.Join(ctx.GlobalString("path"), baseAccountsRootFolderName) - serverPath := strings.NewReplacer(":", "_", "/", string(os.PathSeparator)).Replace(serverURL.Host) - accountsPath := filepath.Join(rootPath, serverPath) - rootUserPath := filepath.Join(accountsPath, email) - - return &AccountsStorage{ - userID: email, - rootPath: rootPath, - rootUserPath: rootUserPath, - keysPath: filepath.Join(rootUserPath, baseKeysFolderName), - accountFilePath: filepath.Join(rootUserPath, accountFileName), - ctx: ctx, - } -} - -func (s *AccountsStorage) ExistsAccountFilePath() bool { - accountFile := filepath.Join(s.rootUserPath, accountFileName) - if _, err := os.Stat(accountFile); os.IsNotExist(err) { - return false - } else if err != nil { - log.Fatal(err) - } - return true -} - -func (s *AccountsStorage) GetRootPath() string { - return s.rootPath -} - -func (s *AccountsStorage) GetRootUserPath() string { - return s.rootUserPath -} - -func (s *AccountsStorage) GetUserID() string { - return s.userID -} - -func (s *AccountsStorage) Save(account *Account) error { - jsonBytes, err := json.MarshalIndent(account, "", "\t") - if err != nil { - return err - } - - return ioutil.WriteFile(s.accountFilePath, jsonBytes, filePerm) -} - -func (s *AccountsStorage) LoadAccount(privateKey crypto.PrivateKey) *Account { - fileBytes, err := ioutil.ReadFile(s.accountFilePath) - if err != nil { - log.Fatalf("Could not load file for account %s -> %v", s.userID, err) - } - - var account Account - err = json.Unmarshal(fileBytes, &account) - if err != nil { - log.Fatalf("Could not parse file for account %s -> %v", s.userID, err) - } - - account.key = privateKey - - if account.Registration == nil || account.Registration.Body.Status == "" { - reg, err := tryRecoverRegistration(s.ctx, privateKey) - if err != nil { - log.Fatalf("Could not load account for %s. Registration is nil -> %#v", s.userID, err) - } - - account.Registration = reg - err = s.Save(&account) - if err != nil { - log.Fatalf("Could not save account for %s. Registration is nil -> %#v", s.userID, err) - } - } - - return &account -} - -func (s *AccountsStorage) GetPrivateKey(keyType certcrypto.KeyType) crypto.PrivateKey { - accKeyPath := filepath.Join(s.keysPath, s.userID+".key") - - if _, err := os.Stat(accKeyPath); os.IsNotExist(err) { - log.Printf("No key found for account %s. Generating a %s key.", s.userID, keyType) - s.createKeysFolder() - - privateKey, err := generatePrivateKey(accKeyPath, keyType) - if err != nil { - log.Fatalf("Could not generate RSA private account key for account %s: %v", s.userID, err) - } - - log.Printf("Saved key to %s", accKeyPath) - return privateKey - } - - privateKey, err := loadPrivateKey(accKeyPath) - if err != nil { - log.Fatalf("Could not load RSA private key from file %s: %v", accKeyPath, err) - } - - return privateKey -} - -func (s *AccountsStorage) createKeysFolder() { - if err := createNonExistingFolder(s.keysPath); err != nil { - log.Fatalf("Could not check/create directory for account %s: %v", s.userID, err) - } -} - -func generatePrivateKey(file string, keyType certcrypto.KeyType) (crypto.PrivateKey, error) { - privateKey, err := certcrypto.GeneratePrivateKey(keyType) - if err != nil { - return nil, err - } - - certOut, err := os.Create(file) - if err != nil { - return nil, err - } - defer certOut.Close() - - pemKey := certcrypto.PEMBlock(privateKey) - err = pem.Encode(certOut, pemKey) - if err != nil { - return nil, err - } - - return privateKey, nil -} - -func loadPrivateKey(file string) (crypto.PrivateKey, error) { - keyBytes, err := ioutil.ReadFile(file) - if err != nil { - return nil, err - } - - keyBlock, _ := pem.Decode(keyBytes) - - switch keyBlock.Type { - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(keyBlock.Bytes) - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(keyBlock.Bytes) - } - - return nil, errors.New("unknown private key type") -} - -func tryRecoverRegistration(ctx *cli.Context, privateKey crypto.PrivateKey) (*registration.Resource, error) { - // couldn't load account but got a key. Try to look the account up. - config := lego.NewConfig(&Account{key: privateKey}) - config.CADirURL = ctx.GlobalString("server") - config.UserAgent = fmt.Sprintf("lego-cli/%s", ctx.App.Version) - - client, err := lego.NewClient(config) - if err != nil { - return nil, err - } - - reg, err := client.Registration.ResolveAccountByKey() - if err != nil { - return nil, err - } - return reg, nil -} diff --git a/vendor/github.com/go-acme/lego/cmd/certs_storage.go b/vendor/github.com/go-acme/lego/cmd/certs_storage.go deleted file mode 100644 index 07890b3..0000000 --- a/vendor/github.com/go-acme/lego/cmd/certs_storage.go +++ /dev/null @@ -1,204 +0,0 @@ -package cmd - -import ( - "bytes" - "crypto/x509" - "encoding/json" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/log" - "github.com/urfave/cli" - "golang.org/x/net/idna" -) - -const ( - baseCertificatesFolderName = "certificates" - baseArchivesFolderName = "archives" -) - -// CertificatesStorage a certificates storage. -// -// rootPath: -// -// ./.lego/certificates/ -// │ └── root certificates directory -// └── "path" option -// -// archivePath: -// -// ./.lego/archives/ -// │ └── archived certificates directory -// └── "path" option -// -type CertificatesStorage struct { - rootPath string - archivePath string - pem bool - filename string // Deprecated -} - -// NewCertificatesStorage create a new certificates storage. -func NewCertificatesStorage(ctx *cli.Context) *CertificatesStorage { - return &CertificatesStorage{ - rootPath: filepath.Join(ctx.GlobalString("path"), baseCertificatesFolderName), - archivePath: filepath.Join(ctx.GlobalString("path"), baseArchivesFolderName), - pem: ctx.GlobalBool("pem"), - filename: ctx.GlobalString("filename"), - } -} - -func (s *CertificatesStorage) CreateRootFolder() { - err := createNonExistingFolder(s.rootPath) - if err != nil { - log.Fatalf("Could not check/create path: %v", err) - } -} - -func (s *CertificatesStorage) CreateArchiveFolder() { - err := createNonExistingFolder(s.archivePath) - if err != nil { - log.Fatalf("Could not check/create path: %v", err) - } -} - -func (s *CertificatesStorage) GetRootPath() string { - return s.rootPath -} - -func (s *CertificatesStorage) SaveResource(certRes *certificate.Resource) { - domain := certRes.Domain - - // We store the certificate, private key and metadata in different files - // as web servers would not be able to work with a combined file. - err := s.WriteFile(domain, ".crt", certRes.Certificate) - if err != nil { - log.Fatalf("Unable to save Certificate for domain %s\n\t%v", domain, err) - } - - if certRes.IssuerCertificate != nil { - err = s.WriteFile(domain, ".issuer.crt", certRes.IssuerCertificate) - if err != nil { - log.Fatalf("Unable to save IssuerCertificate for domain %s\n\t%v", domain, err) - } - } - - if certRes.PrivateKey != nil { - // if we were given a CSR, we don't know the private key - err = s.WriteFile(domain, ".key", certRes.PrivateKey) - if err != nil { - log.Fatalf("Unable to save PrivateKey for domain %s\n\t%v", domain, err) - } - - if s.pem { - err = s.WriteFile(domain, ".pem", bytes.Join([][]byte{certRes.Certificate, certRes.PrivateKey}, nil)) - if err != nil { - log.Fatalf("Unable to save Certificate and PrivateKey in .pem for domain %s\n\t%v", domain, err) - } - } - } else if s.pem { - // we don't have the private key; can't write the .pem file - log.Fatalf("Unable to save pem without private key for domain %s\n\t%v; are you using a CSR?", domain, err) - } - - jsonBytes, err := json.MarshalIndent(certRes, "", "\t") - if err != nil { - log.Fatalf("Unable to marshal CertResource for domain %s\n\t%v", domain, err) - } - - err = s.WriteFile(domain, ".json", jsonBytes) - if err != nil { - log.Fatalf("Unable to save CertResource for domain %s\n\t%v", domain, err) - } -} - -func (s *CertificatesStorage) ReadResource(domain string) certificate.Resource { - raw, err := s.ReadFile(domain, ".json") - if err != nil { - log.Fatalf("Error while loading the meta data for domain %s\n\t%v", domain, err) - } - - var resource certificate.Resource - if err = json.Unmarshal(raw, &resource); err != nil { - log.Fatalf("Error while marshaling the meta data for domain %s\n\t%v", domain, err) - } - - return resource -} - -func (s *CertificatesStorage) ExistsFile(domain, extension string) bool { - filename := sanitizedDomain(domain) + extension - filePath := filepath.Join(s.rootPath, filename) - - if _, err := os.Stat(filePath); os.IsNotExist(err) { - return false - } else if err != nil { - log.Fatal(err) - } - return true -} - -func (s *CertificatesStorage) ReadFile(domain, extension string) ([]byte, error) { - filename := sanitizedDomain(domain) + extension - filePath := filepath.Join(s.rootPath, filename) - - return ioutil.ReadFile(filePath) -} - -func (s *CertificatesStorage) ReadCertificate(domain, extension string) ([]*x509.Certificate, error) { - content, err := s.ReadFile(domain, extension) - if err != nil { - return nil, err - } - - // The input may be a bundle or a single certificate. - return certcrypto.ParsePEMBundle(content) -} - -func (s *CertificatesStorage) WriteFile(domain, extension string, data []byte) error { - var baseFileName string - if s.filename != "" { - baseFileName = s.filename - } else { - baseFileName = sanitizedDomain(domain) - } - - filePath := filepath.Join(s.rootPath, baseFileName+extension) - - return ioutil.WriteFile(filePath, data, filePerm) -} - -func (s *CertificatesStorage) MoveToArchive(domain string) error { - matches, err := filepath.Glob(filepath.Join(s.rootPath, sanitizedDomain(domain)+".*")) - if err != nil { - return err - } - - for _, oldFile := range matches { - date := strconv.FormatInt(time.Now().Unix(), 10) - filename := date + "." + filepath.Base(oldFile) - newFile := filepath.Join(s.archivePath, filename) - - err = os.Rename(oldFile, newFile) - if err != nil { - return err - } - } - - return nil -} - -// sanitizedDomain Make sure no funny chars are in the cert names (like wildcards ;)) -func sanitizedDomain(domain string) string { - safe, err := idna.ToASCII(strings.Replace(domain, "*", "_", -1)) - if err != nil { - log.Fatal(err) - } - return safe -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd.go b/vendor/github.com/go-acme/lego/cmd/cmd.go deleted file mode 100644 index 2c63a5a..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd.go +++ /dev/null @@ -1,14 +0,0 @@ -package cmd - -import "github.com/urfave/cli" - -// CreateCommands Creates all CLI commands -func CreateCommands() []cli.Command { - return []cli.Command{ - createRun(), - createRevoke(), - createRenew(), - createDNSHelp(), - createList(), - } -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_before.go b/vendor/github.com/go-acme/lego/cmd/cmd_before.go deleted file mode 100644 index 1871d91..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_before.go +++ /dev/null @@ -1,23 +0,0 @@ -package cmd - -import ( - "github.com/go-acme/lego/log" - "github.com/urfave/cli" -) - -func Before(ctx *cli.Context) error { - if len(ctx.GlobalString("path")) == 0 { - log.Fatal("Could not determine current working directory. Please pass --path.") - } - - err := createNonExistingFolder(ctx.GlobalString("path")) - if err != nil { - log.Fatalf("Could not check/create path: %v", err) - } - - if len(ctx.GlobalString("server")) == 0 { - log.Fatal("Could not determine current working server. Please pass --server.") - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_dnshelp.go b/vendor/github.com/go-acme/lego/cmd/cmd_dnshelp.go deleted file mode 100644 index 37f4d6c..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_dnshelp.go +++ /dev/null @@ -1,48 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "strings" - "text/tabwriter" - - "github.com/urfave/cli" -) - -func createDNSHelp() cli.Command { - return cli.Command{ - Name: "dnshelp", - Usage: "Shows additional help for the '--dns' global option", - Action: dnsHelp, - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "code, c", - Usage: fmt.Sprintf("DNS code: %s", allDNSCodes()), - }, - }, - } -} - -func dnsHelp(ctx *cli.Context) error { - code := ctx.String("code") - if code == "" { - w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) - - fmt.Fprintln(w, `Credentials for DNS providers must be passed through environment variables.`) - fmt.Fprintln(w) - fmt.Fprintln(w, `To display the documentation for a DNS providers:`) - fmt.Fprintln(w) - fmt.Fprintln(w, "\t$ lego dnshelp -c code") - fmt.Fprintln(w) - fmt.Fprintln(w, "All DNS codes:") - fmt.Fprintf(w, "\t%s\n", allDNSCodes()) - fmt.Fprintln(w) - fmt.Fprintln(w, "More information: https://go-acme.github.io/lego/dns") - - return w.Flush() - } - - displayDNSHelp(strings.ToLower(code)) - - return nil -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_list.go b/vendor/github.com/go-acme/lego/cmd/cmd_list.go deleted file mode 100644 index abb9f0a..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_list.go +++ /dev/null @@ -1,121 +0,0 @@ -package cmd - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/url" - "path/filepath" - "strings" - - "github.com/go-acme/lego/certcrypto" - "github.com/urfave/cli" -) - -func createList() cli.Command { - return cli.Command{ - Name: "list", - Usage: "Display certificates and accounts information.", - Action: list, - Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "accounts, a", - Usage: "Display accounts.", - }, - }, - } -} - -func list(ctx *cli.Context) error { - if ctx.Bool("accounts") { - if err := listAccount(ctx); err != nil { - return err - } - } - - return listCertificates(ctx) -} - -func listCertificates(ctx *cli.Context) error { - certsStorage := NewCertificatesStorage(ctx) - - matches, err := filepath.Glob(filepath.Join(certsStorage.GetRootPath(), "*.crt")) - if err != nil { - return err - } - - if len(matches) == 0 { - fmt.Println("No certificates found.") - return nil - } - - fmt.Println("Found the following certs:") - for _, filename := range matches { - if strings.HasSuffix(filename, ".issuer.crt") { - continue - } - - data, err := ioutil.ReadFile(filename) - if err != nil { - return err - } - - pCert, err := certcrypto.ParsePEMCertificate(data) - if err != nil { - return err - } - - fmt.Println(" Certificate Name:", pCert.Subject.CommonName) - fmt.Println(" Domains:", strings.Join(pCert.DNSNames, ", ")) - fmt.Println(" Expiry Date:", pCert.NotAfter) - fmt.Println(" Certificate Path:", filename) - fmt.Println() - } - - return nil -} - -func listAccount(ctx *cli.Context) error { - // fake email, needed by NewAccountsStorage - if err := ctx.GlobalSet("email", "unknown"); err != nil { - return err - } - - accountsStorage := NewAccountsStorage(ctx) - - matches, err := filepath.Glob(filepath.Join(accountsStorage.GetRootPath(), "*", "*", "*.json")) - if err != nil { - return err - } - - if len(matches) == 0 { - fmt.Println("No accounts found.") - return nil - } - - fmt.Println("Found the following accounts:") - for _, filename := range matches { - data, err := ioutil.ReadFile(filename) - if err != nil { - return err - } - - var account Account - err = json.Unmarshal(data, &account) - if err != nil { - return err - } - - uri, err := url.Parse(account.Registration.URI) - if err != nil { - return err - } - - fmt.Println(" Email:", account.Email) - fmt.Println(" Server:", uri.Host) - fmt.Println(" Path:", filepath.Dir(filename)) - fmt.Println() - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_renew.go b/vendor/github.com/go-acme/lego/cmd/cmd_renew.go deleted file mode 100644 index f6fa666..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_renew.go +++ /dev/null @@ -1,226 +0,0 @@ -package cmd - -import ( - "context" - "crypto" - "crypto/x509" - "errors" - "fmt" - "os/exec" - "strings" - "time" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/log" - "github.com/urfave/cli" -) - -func createRenew() cli.Command { - return cli.Command{ - Name: "renew", - Usage: "Renew a certificate", - Action: renew, - Before: func(ctx *cli.Context) error { - // we require either domains or csr, but not both - hasDomains := len(ctx.GlobalStringSlice("domains")) > 0 - hasCsr := len(ctx.GlobalString("csr")) > 0 - if hasDomains && hasCsr { - log.Fatal("Please specify either --domains/-d or --csr/-c, but not both") - } - if !hasDomains && !hasCsr { - log.Fatal("Please specify --domains/-d (or --csr/-c if you already have a CSR)") - } - return nil - }, - Flags: []cli.Flag{ - cli.IntFlag{ - Name: "days", - Value: 30, - Usage: "The number of days left on a certificate to renew it.", - }, - cli.BoolFlag{ - Name: "reuse-key", - Usage: "Used to indicate you want to reuse your current private key for the new certificate.", - }, - cli.BoolFlag{ - Name: "no-bundle", - Usage: "Do not create a certificate bundle by adding the issuers certificate to the new certificate.", - }, - cli.BoolFlag{ - Name: "must-staple", - Usage: "Include the OCSP must staple TLS extension in the CSR and generated certificate. Only works if the CSR is generated by lego.", - }, - cli.StringFlag{ - Name: "renew-hook", - Usage: "Define a hook. The hook is executed only when the certificates are effectively renewed.", - }, - }, - } -} - -func renew(ctx *cli.Context) error { - account, client := setup(ctx, NewAccountsStorage(ctx)) - setupChallenges(ctx, client) - - if account.Registration == nil { - log.Fatalf("Account %s is not registered. Use 'run' to register a new account.\n", account.Email) - } - - certsStorage := NewCertificatesStorage(ctx) - - bundle := !ctx.Bool("no-bundle") - - // CSR - if ctx.GlobalIsSet("csr") { - return renewForCSR(ctx, client, certsStorage, bundle) - } - - // Domains - return renewForDomains(ctx, client, certsStorage, bundle) -} - -func renewForDomains(ctx *cli.Context, client *lego.Client, certsStorage *CertificatesStorage, bundle bool) error { - domains := ctx.GlobalStringSlice("domains") - domain := domains[0] - - // load the cert resource from files. - // We store the certificate, private key and metadata in different files - // as web servers would not be able to work with a combined file. - certificates, err := certsStorage.ReadCertificate(domain, ".crt") - if err != nil { - log.Fatalf("Error while loading the certificate for domain %s\n\t%v", domain, err) - } - - cert := certificates[0] - - if !needRenewal(cert, domain, ctx.Int("days")) { - return nil - } - - // This is just meant to be informal for the user. - timeLeft := cert.NotAfter.Sub(time.Now().UTC()) - log.Infof("[%s] acme: Trying renewal with %d hours remaining", domain, int(timeLeft.Hours())) - - certDomains := certcrypto.ExtractDomains(cert) - - var privateKey crypto.PrivateKey - if ctx.Bool("reuse-key") { - keyBytes, errR := certsStorage.ReadFile(domain, ".key") - if errR != nil { - log.Fatalf("Error while loading the private key for domain %s\n\t%v", domain, errR) - } - - privateKey, errR = certcrypto.ParsePEMPrivateKey(keyBytes) - if errR != nil { - return errR - } - } - - request := certificate.ObtainRequest{ - Domains: merge(certDomains, domains), - Bundle: bundle, - PrivateKey: privateKey, - MustStaple: ctx.Bool("must-staple"), - } - certRes, err := client.Certificate.Obtain(request) - if err != nil { - log.Fatal(err) - } - - certsStorage.SaveResource(certRes) - - return renewHook(ctx) -} - -func renewForCSR(ctx *cli.Context, client *lego.Client, certsStorage *CertificatesStorage, bundle bool) error { - csr, err := readCSRFile(ctx.GlobalString("csr")) - if err != nil { - log.Fatal(err) - } - - domain := csr.Subject.CommonName - - // load the cert resource from files. - // We store the certificate, private key and metadata in different files - // as web servers would not be able to work with a combined file. - certificates, err := certsStorage.ReadCertificate(domain, ".crt") - if err != nil { - log.Fatalf("Error while loading the certificate for domain %s\n\t%v", domain, err) - } - - cert := certificates[0] - - if !needRenewal(cert, domain, ctx.Int("days")) { - return nil - } - - // This is just meant to be informal for the user. - timeLeft := cert.NotAfter.Sub(time.Now().UTC()) - log.Infof("[%s] acme: Trying renewal with %d hours remaining", domain, int(timeLeft.Hours())) - - certRes, err := client.Certificate.ObtainForCSR(*csr, bundle) - if err != nil { - log.Fatal(err) - } - - certsStorage.SaveResource(certRes) - - return renewHook(ctx) -} - -func needRenewal(x509Cert *x509.Certificate, domain string, days int) bool { - if x509Cert.IsCA { - log.Fatalf("[%s] Certificate bundle starts with a CA certificate", domain) - } - - if days >= 0 { - notAfter := int(time.Until(x509Cert.NotAfter).Hours() / 24.0) - if notAfter > days { - log.Printf("[%s] The certificate expires in %d days, the number of days defined to perform the renewal is %d: no renewal.", - domain, notAfter, days) - return false - } - } - - return true -} - -func merge(prevDomains []string, nextDomains []string) []string { - for _, next := range nextDomains { - var found bool - for _, prev := range prevDomains { - if prev == next { - found = true - break - } - } - if !found { - prevDomains = append(prevDomains, next) - } - } - return prevDomains -} - -func renewHook(ctx *cli.Context) error { - hook := ctx.String("renew-hook") - if hook == "" { - return nil - } - - ctxCmd, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - - parts := strings.Fields(hook) - output, err := exec.CommandContext(ctxCmd, parts[0], parts[1:]...).CombinedOutput() - if len(output) > 0 { - fmt.Println(string(output)) - } - - if ctxCmd.Err() == context.DeadlineExceeded { - return errors.New("hook timed out") - } - - return err -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_renew_test.go b/vendor/github.com/go-acme/lego/cmd/cmd_renew_test.go deleted file mode 100644 index d040eef..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_renew_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package cmd - -import ( - "crypto/x509" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func Test_merge(t *testing.T) { - testCases := []struct { - desc string - prevDomains []string - nextDomains []string - expected []string - }{ - { - desc: "all empty", - prevDomains: []string{}, - nextDomains: []string{}, - expected: []string{}, - }, - { - desc: "next empty", - prevDomains: []string{"a", "b", "c"}, - nextDomains: []string{}, - expected: []string{"a", "b", "c"}, - }, - { - desc: "prev empty", - prevDomains: []string{}, - nextDomains: []string{"a", "b", "c"}, - expected: []string{"a", "b", "c"}, - }, - { - desc: "merge append", - prevDomains: []string{"a", "b", "c"}, - nextDomains: []string{"a", "c", "d"}, - expected: []string{"a", "b", "c", "d"}, - }, - { - desc: "merge same", - prevDomains: []string{"a", "b", "c"}, - nextDomains: []string{"a", "b", "c"}, - expected: []string{"a", "b", "c"}, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - actual := merge(test.prevDomains, test.nextDomains) - assert.Equal(t, test.expected, actual) - }) - } -} - -func Test_needRenewal(t *testing.T) { - testCases := []struct { - desc string - x509Cert *x509.Certificate - days int - expected bool - }{ - { - desc: "30 days, NotAfter now", - x509Cert: &x509.Certificate{ - NotAfter: time.Now(), - }, - days: 30, - expected: true, - }, - { - desc: "30 days, NotAfter 31 days", - x509Cert: &x509.Certificate{ - NotAfter: time.Now().Add(31*24*time.Hour + 1*time.Second), - }, - days: 30, - expected: false, - }, - { - desc: "30 days, NotAfter 30 days", - x509Cert: &x509.Certificate{ - NotAfter: time.Now().Add(30 * 24 * time.Hour), - }, - days: 30, - expected: true, - }, - { - desc: "0 days, NotAfter 30 days: only the day of the expiration", - x509Cert: &x509.Certificate{ - NotAfter: time.Now().Add(30 * 24 * time.Hour), - }, - days: 0, - expected: false, - }, - { - desc: "-1 days, NotAfter 30 days: always renew", - x509Cert: &x509.Certificate{ - NotAfter: time.Now().Add(30 * 24 * time.Hour), - }, - days: -1, - expected: true, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - - actual := needRenewal(test.x509Cert, "foo.com", test.days) - - assert.Equal(t, test.expected, actual) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_revoke.go b/vendor/github.com/go-acme/lego/cmd/cmd_revoke.go deleted file mode 100644 index 4468326..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_revoke.go +++ /dev/null @@ -1,62 +0,0 @@ -package cmd - -import ( - "github.com/go-acme/lego/log" - "github.com/urfave/cli" -) - -func createRevoke() cli.Command { - return cli.Command{ - Name: "revoke", - Usage: "Revoke a certificate", - Action: revoke, - Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "keep, k", - Usage: "Keep the certificates after the revocation instead of archiving them.", - }, - }, - } -} - -func revoke(ctx *cli.Context) error { - acc, client := setup(ctx, NewAccountsStorage(ctx)) - - if acc.Registration == nil { - log.Fatalf("Account %s is not registered. Use 'run' to register a new account.\n", acc.Email) - } - - certsStorage := NewCertificatesStorage(ctx) - certsStorage.CreateRootFolder() - - for _, domain := range ctx.GlobalStringSlice("domains") { - log.Printf("Trying to revoke certificate for domain %s", domain) - - certBytes, err := certsStorage.ReadFile(domain, ".crt") - if err != nil { - log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err) - } - - err = client.Certificate.Revoke(certBytes) - if err != nil { - log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err) - } - - log.Println("Certificate was revoked.") - - if ctx.Bool("keep") { - return nil - } - - certsStorage.CreateArchiveFolder() - - err = certsStorage.MoveToArchive(domain) - if err != nil { - return err - } - - log.Println("Certificate was archived for domain:", domain) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/cmd/cmd_run.go b/vendor/github.com/go-acme/lego/cmd/cmd_run.go deleted file mode 100644 index efbe9b3..0000000 --- a/vendor/github.com/go-acme/lego/cmd/cmd_run.go +++ /dev/null @@ -1,163 +0,0 @@ -package cmd - -import ( - "bufio" - "fmt" - "os" - "strings" - - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/registration" - "github.com/urfave/cli" -) - -func createRun() cli.Command { - return cli.Command{ - Name: "run", - Usage: "Register an account, then create and install a certificate", - Before: func(ctx *cli.Context) error { - // we require either domains or csr, but not both - hasDomains := len(ctx.GlobalStringSlice("domains")) > 0 - hasCsr := len(ctx.GlobalString("csr")) > 0 - if hasDomains && hasCsr { - log.Fatal("Please specify either --domains/-d or --csr/-c, but not both") - } - if !hasDomains && !hasCsr { - log.Fatal("Please specify --domains/-d (or --csr/-c if you already have a CSR)") - } - return nil - }, - Action: run, - Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "no-bundle", - Usage: "Do not create a certificate bundle by adding the issuers certificate to the new certificate.", - }, - cli.BoolFlag{ - Name: "must-staple", - Usage: "Include the OCSP must staple TLS extension in the CSR and generated certificate. Only works if the CSR is generated by lego.", - }, - }, - } -} - -func run(ctx *cli.Context) error { - accountsStorage := NewAccountsStorage(ctx) - - account, client := setup(ctx, accountsStorage) - setupChallenges(ctx, client) - - if account.Registration == nil { - reg, err := register(ctx, client) - if err != nil { - log.Fatalf("Could not complete registration\n\t%v", err) - } - - account.Registration = reg - - if err = accountsStorage.Save(account); err != nil { - log.Fatal(err) - } - - fmt.Println("!!!! HEADS UP !!!!") - fmt.Printf(` - Your account credentials have been saved in your Let's Encrypt - configuration directory at "%s". - You should make a secure backup of this folder now. This - configuration directory will also contain certificates and - private keys obtained from Let's Encrypt so making regular - backups of this folder is ideal.`, accountsStorage.GetRootPath()) - } - - certsStorage := NewCertificatesStorage(ctx) - certsStorage.CreateRootFolder() - - cert, err := obtainCertificate(ctx, client) - if err != nil { - // Make sure to return a non-zero exit code if ObtainSANCertificate returned at least one error. - // Due to us not returning partial certificate we can just exit here instead of at the end. - log.Fatalf("Could not obtain certificates:\n\t%v", err) - } - - certsStorage.SaveResource(cert) - - return nil -} - -func handleTOS(ctx *cli.Context, client *lego.Client) bool { - // Check for a global accept override - if ctx.GlobalBool("accept-tos") { - return true - } - - reader := bufio.NewReader(os.Stdin) - log.Printf("Please review the TOS at %s", client.GetToSURL()) - - for { - fmt.Println("Do you accept the TOS? Y/n") - text, err := reader.ReadString('\n') - if err != nil { - log.Fatalf("Could not read from console: %v", err) - } - - text = strings.Trim(text, "\r\n") - switch text { - case "", "y", "Y": - return true - case "n", "N": - return false - default: - fmt.Println("Your input was invalid. Please answer with one of Y/y, n/N or by pressing enter.") - } - } -} - -func register(ctx *cli.Context, client *lego.Client) (*registration.Resource, error) { - accepted := handleTOS(ctx, client) - if !accepted { - log.Fatal("You did not accept the TOS. Unable to proceed.") - } - - if ctx.GlobalBool("eab") { - kid := ctx.GlobalString("kid") - hmacEncoded := ctx.GlobalString("hmac") - - if kid == "" || hmacEncoded == "" { - log.Fatalf("Requires arguments --kid and --hmac.") - } - - return client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{ - TermsOfServiceAgreed: accepted, - Kid: kid, - HmacEncoded: hmacEncoded, - }) - } - - return client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) -} - -func obtainCertificate(ctx *cli.Context, client *lego.Client) (*certificate.Resource, error) { - bundle := !ctx.Bool("no-bundle") - - domains := ctx.GlobalStringSlice("domains") - if len(domains) > 0 { - // obtain a certificate, generating a new private key - request := certificate.ObtainRequest{ - Domains: domains, - Bundle: bundle, - MustStaple: ctx.Bool("must-staple"), - } - return client.Certificate.Obtain(request) - } - - // read the CSR - csr, err := readCSRFile(ctx.GlobalString("csr")) - if err != nil { - return nil, err - } - - // obtain a certificate for this CSR - return client.Certificate.ObtainForCSR(*csr, bundle) -} diff --git a/vendor/github.com/go-acme/lego/cmd/flags.go b/vendor/github.com/go-acme/lego/cmd/flags.go deleted file mode 100644 index 3fac0c1..0000000 --- a/vendor/github.com/go-acme/lego/cmd/flags.go +++ /dev/null @@ -1,114 +0,0 @@ -package cmd - -import ( - "github.com/go-acme/lego/lego" - "github.com/urfave/cli" -) - -func CreateFlags(defaultPath string) []cli.Flag { - return []cli.Flag{ - cli.StringSliceFlag{ - Name: "domains, d", - Usage: "Add a domain to the process. Can be specified multiple times.", - }, - cli.StringFlag{ - Name: "server, s", - Usage: "CA hostname (and optionally :port). The server certificate must be trusted in order to avoid further modifications to the client.", - Value: lego.LEDirectoryProduction, - }, - cli.BoolFlag{ - Name: "accept-tos, a", - Usage: "By setting this flag to true you indicate that you accept the current Let's Encrypt terms of service.", - }, - cli.StringFlag{ - Name: "email, m", - Usage: "Email used for registration and recovery contact.", - }, - cli.StringFlag{ - Name: "csr, c", - Usage: "Certificate signing request filename, if an external CSR is to be used.", - }, - cli.BoolFlag{ - Name: "eab", - Usage: "Use External Account Binding for account registration. Requires --kid and --hmac.", - }, - cli.StringFlag{ - Name: "kid", - Usage: "Key identifier from External CA. Used for External Account Binding.", - }, - cli.StringFlag{ - Name: "hmac", - Usage: "MAC key from External CA. Should be in Base64 URL Encoding without padding format. Used for External Account Binding.", - }, - cli.StringFlag{ - Name: "key-type, k", - Value: "ec384", - Usage: "Key type to use for private keys. Supported: rsa2048, rsa4096, rsa8192, ec256, ec384.", - }, - cli.StringFlag{ - Name: "filename", - Usage: "(deprecated) Filename of the generated certificate.", - }, - cli.StringFlag{ - Name: "path", - Usage: "Directory to use for storing the data.", - Value: defaultPath, - }, - cli.BoolFlag{ - Name: "http", - Usage: "Use the HTTP challenge to solve challenges. Can be mixed with other types of challenges.", - }, - cli.StringFlag{ - Name: "http.port", - Usage: "Set the port and interface to use for HTTP based challenges to listen on.Supported: interface:port or :port.", - Value: ":80", - }, - cli.StringFlag{ - Name: "http.webroot", - Usage: "Set the webroot folder to use for HTTP based challenges to write directly in a file in .well-known/acme-challenge.", - }, - cli.StringSliceFlag{ - Name: "http.memcached-host", - Usage: "Set the memcached host(s) to use for HTTP based challenges. Challenges will be written to all specified hosts.", - }, - cli.BoolFlag{ - Name: "tls", - Usage: "Use the TLS challenge to solve challenges. Can be mixed with other types of challenges.", - }, - cli.StringFlag{ - Name: "tls.port", - Usage: "Set the port and interface to use for TLS based challenges to listen on. Supported: interface:port or :port.", - Value: ":443", - }, - cli.StringFlag{ - Name: "dns", - Usage: "Solve a DNS challenge using the specified provider. Can be mixed with other types of challenges. Run 'lego dnshelp' for help on usage.", - }, - cli.BoolFlag{ - Name: "dns.disable-cp", - Usage: "By setting this flag to true, disables the need to wait the propagation of the TXT record to all authoritative name servers.", - }, - cli.StringSliceFlag{ - Name: "dns.resolvers", - Usage: "Set the resolvers to use for performing recursive DNS queries. Supported: host:port. The default is to use the system resolvers, or Google's DNS resolvers if the system's cannot be determined.", - }, - cli.IntFlag{ - Name: "http-timeout", - Usage: "Set the HTTP timeout value to a specific value in seconds.", - }, - cli.IntFlag{ - Name: "dns-timeout", - Usage: "Set the DNS timeout value to a specific value in seconds. Used only when performing authoritative name servers queries.", - Value: 10, - }, - cli.BoolFlag{ - Name: "pem", - Usage: "Generate a .pem file by concatenating the .key and .crt files together.", - }, - cli.IntFlag{ - Name: "cert.timeout", - Usage: "Set the certificate timeout value to a specific value in seconds. Only used when obtaining certificates.", - Value: 30, - }, - } -} diff --git a/vendor/github.com/go-acme/lego/cmd/lego/main.go b/vendor/github.com/go-acme/lego/cmd/lego/main.go deleted file mode 100644 index f00119e..0000000 --- a/vendor/github.com/go-acme/lego/cmd/lego/main.go +++ /dev/null @@ -1,47 +0,0 @@ -// Let's Encrypt client to go! -// CLI application for generating Let's Encrypt certificates using the ACME package. -package main - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - - "github.com/go-acme/lego/cmd" - "github.com/go-acme/lego/log" - "github.com/urfave/cli" -) - -var ( - version = "dev" -) - -func main() { - app := cli.NewApp() - app.Name = "lego" - app.HelpName = "lego" - app.Usage = "Let's Encrypt client written in Go" - app.EnableBashCompletion = true - - app.Version = version - cli.VersionPrinter = func(c *cli.Context) { - fmt.Printf("lego version %s %s/%s\n", c.App.Version, runtime.GOOS, runtime.GOARCH) - } - - defaultPath := "" - cwd, err := os.Getwd() - if err == nil { - defaultPath = filepath.Join(cwd, ".lego") - } - app.Flags = cmd.CreateFlags(defaultPath) - - app.Before = cmd.Before - - app.Commands = cmd.CreateCommands() - - err = app.Run(os.Args) - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/go-acme/lego/cmd/setup.go b/vendor/github.com/go-acme/lego/cmd/setup.go deleted file mode 100644 index a41aa5a..0000000 --- a/vendor/github.com/go-acme/lego/cmd/setup.go +++ /dev/null @@ -1,129 +0,0 @@ -package cmd - -import ( - "crypto/x509" - "encoding/pem" - "fmt" - "io/ioutil" - "os" - "strings" - "time" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/registration" - "github.com/urfave/cli" -) - -const filePerm os.FileMode = 0600 - -func setup(ctx *cli.Context, accountsStorage *AccountsStorage) (*Account, *lego.Client) { - keyType := getKeyType(ctx) - privateKey := accountsStorage.GetPrivateKey(keyType) - - var account *Account - if accountsStorage.ExistsAccountFilePath() { - account = accountsStorage.LoadAccount(privateKey) - } else { - account = &Account{Email: accountsStorage.GetUserID(), key: privateKey} - } - - client := newClient(ctx, account, keyType) - - return account, client -} - -func newClient(ctx *cli.Context, acc registration.User, keyType certcrypto.KeyType) *lego.Client { - config := lego.NewConfig(acc) - config.CADirURL = ctx.GlobalString("server") - - config.Certificate = lego.CertificateConfig{ - KeyType: keyType, - Timeout: time.Duration(ctx.GlobalInt("cert.timeout")) * time.Second, - } - config.UserAgent = fmt.Sprintf("lego-cli/%s", ctx.App.Version) - - if ctx.GlobalIsSet("http-timeout") { - config.HTTPClient.Timeout = time.Duration(ctx.GlobalInt("http-timeout")) * time.Second - } - - client, err := lego.NewClient(config) - if err != nil { - log.Fatalf("Could not create client: %v", err) - } - - if client.GetExternalAccountRequired() && !ctx.GlobalIsSet("eab") { - log.Fatal("Server requires External Account Binding. Use --eab with --kid and --hmac.") - } - - return client -} - -// getKeyType the type from which private keys should be generated -func getKeyType(ctx *cli.Context) certcrypto.KeyType { - keyType := ctx.GlobalString("key-type") - switch strings.ToUpper(keyType) { - case "RSA2048": - return certcrypto.RSA2048 - case "RSA4096": - return certcrypto.RSA4096 - case "RSA8192": - return certcrypto.RSA8192 - case "EC256": - return certcrypto.EC256 - case "EC384": - return certcrypto.EC384 - } - - log.Fatalf("Unsupported KeyType: %s", keyType) - return "" -} - -func getEmail(ctx *cli.Context) string { - email := ctx.GlobalString("email") - if len(email) == 0 { - log.Fatal("You have to pass an account (email address) to the program using --email or -m") - } - return email -} - -func createNonExistingFolder(path string) error { - if _, err := os.Stat(path); os.IsNotExist(err) { - return os.MkdirAll(path, 0700) - } else if err != nil { - return err - } - return nil -} - -func readCSRFile(filename string) (*x509.CertificateRequest, error) { - bytes, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - raw := bytes - - // see if we can find a PEM-encoded CSR - var p *pem.Block - rest := bytes - for { - // decode a PEM block - p, rest = pem.Decode(rest) - - // did we fail? - if p == nil { - break - } - - // did we get a CSR? - if p.Type == "CERTIFICATE REQUEST" { - raw = p.Bytes - } - } - - // no PEM-encoded CSR - // assume we were given a DER-encoded ASN.1 CSR - // (if this assumption is wrong, parsing these bytes will fail) - return x509.ParseCertificateRequest(raw) -} diff --git a/vendor/github.com/go-acme/lego/cmd/setup_challenges.go b/vendor/github.com/go-acme/lego/cmd/setup_challenges.go deleted file mode 100644 index 3c02389..0000000 --- a/vendor/github.com/go-acme/lego/cmd/setup_challenges.go +++ /dev/null @@ -1,118 +0,0 @@ -package cmd - -import ( - "net" - "strings" - "time" - - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/challenge/http01" - "github.com/go-acme/lego/challenge/tlsalpn01" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/providers/dns" - "github.com/go-acme/lego/providers/http/memcached" - "github.com/go-acme/lego/providers/http/webroot" - "github.com/urfave/cli" -) - -func setupChallenges(ctx *cli.Context, client *lego.Client) { - if !ctx.GlobalBool("http") && !ctx.GlobalBool("tls") && !ctx.GlobalIsSet("dns") { - log.Fatal("No challenge selected. You must specify at least one challenge: `--http`, `--tls`, `--dns`.") - } - - if ctx.GlobalBool("http") { - err := client.Challenge.SetHTTP01Provider(setupHTTPProvider(ctx)) - if err != nil { - log.Fatal(err) - } - } - - if ctx.GlobalBool("tls") { - err := client.Challenge.SetTLSALPN01Provider(setupTLSProvider(ctx)) - if err != nil { - log.Fatal(err) - } - } - - if ctx.GlobalIsSet("dns") { - setupDNS(ctx, client) - } -} - -func setupHTTPProvider(ctx *cli.Context) challenge.Provider { - switch { - case ctx.GlobalIsSet("http.webroot"): - ps, err := webroot.NewHTTPProvider(ctx.GlobalString("http.webroot")) - if err != nil { - log.Fatal(err) - } - return ps - case ctx.GlobalIsSet("http.memcached-host"): - ps, err := memcached.NewMemcachedProvider(ctx.GlobalStringSlice("http.memcached-host")) - if err != nil { - log.Fatal(err) - } - return ps - case ctx.GlobalIsSet("http.port"): - iface := ctx.GlobalString("http.port") - if !strings.Contains(iface, ":") { - log.Fatalf("The --http switch only accepts interface:port or :port for its argument.") - } - - host, port, err := net.SplitHostPort(iface) - if err != nil { - log.Fatal(err) - } - - return http01.NewProviderServer(host, port) - case ctx.GlobalBool("http"): - return http01.NewProviderServer("", "") - default: - log.Fatal("Invalid HTTP challenge options.") - return nil - } -} - -func setupTLSProvider(ctx *cli.Context) challenge.Provider { - switch { - case ctx.GlobalIsSet("tls.port"): - iface := ctx.GlobalString("tls.port") - if !strings.Contains(iface, ":") { - log.Fatalf("The --tls switch only accepts interface:port or :port for its argument.") - } - - host, port, err := net.SplitHostPort(iface) - if err != nil { - log.Fatal(err) - } - - return tlsalpn01.NewProviderServer(host, port) - case ctx.GlobalBool("tls"): - return tlsalpn01.NewProviderServer("", "") - default: - log.Fatal("Invalid HTTP challenge options.") - return nil - } -} - -func setupDNS(ctx *cli.Context, client *lego.Client) { - provider, err := dns.NewDNSChallengeProviderByName(ctx.GlobalString("dns")) - if err != nil { - log.Fatal(err) - } - - servers := ctx.GlobalStringSlice("dns.resolvers") - err = client.Challenge.SetDNS01Provider(provider, - dns01.CondOption(len(servers) > 0, - dns01.AddRecursiveNameservers(dns01.ParseNameservers(ctx.GlobalStringSlice("dns.resolvers")))), - dns01.CondOption(ctx.GlobalBool("dns.disable-cp"), - dns01.DisableCompletePropagationRequirement()), - dns01.CondOption(ctx.GlobalIsSet("dns-timeout"), - dns01.AddDNSTimeout(time.Duration(ctx.GlobalInt("dns-timeout"))*time.Second)), - ) - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/go-acme/lego/cmd/zz_gen_cmd_dnshelp.go b/vendor/github.com/go-acme/lego/cmd/zz_gen_cmd_dnshelp.go deleted file mode 100644 index 2308aa7..0000000 --- a/vendor/github.com/go-acme/lego/cmd/zz_gen_cmd_dnshelp.go +++ /dev/null @@ -1,1290 +0,0 @@ -package cmd - -// CODE GENERATED AUTOMATICALLY -// THIS FILE MUST NOT BE EDITED BY HAND - -import ( - "fmt" - "os" - "sort" - "strings" - "text/tabwriter" - - "github.com/go-acme/lego/log" -) - -func allDNSCodes() string { - providers := []string{ - "manual", - "acme-dns", - "alidns", - "auroradns", - "azure", - "bindman", - "bluecat", - "cloudflare", - "cloudns", - "cloudxns", - "conoha", - "designate", - "digitalocean", - "dnsimple", - "dnsmadeeasy", - "dnspod", - "dode", - "dreamhost", - "duckdns", - "dyn", - "easydns", - "exec", - "exoscale", - "fastdns", - "gandi", - "gandiv5", - "gcloud", - "glesys", - "godaddy", - "hostingde", - "httpreq", - "iij", - "inwx", - "joker", - "lightsail", - "linode", - "linodev4", - "mydnsjp", - "namecheap", - "namedotcom", - "netcup", - "nifcloud", - "ns1", - "oraclecloud", - "otc", - "ovh", - "pdns", - "rackspace", - "rfc2136", - "route53", - "sakuracloud", - "selectel", - "stackpath", - "transip", - "vegadns", - "vscale", - "vultr", - "zoneee", - } - sort.Strings(providers) - return strings.Join(providers, ", ") -} - -func displayDNSHelp(name string) { - w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) - switch name { - - case "acme-dns": - // generated from: providers/dns/acmedns/acmedns.toml - fmt.Fprintln(w, `Configuration for Joohoi's ACME-DNS.`) - fmt.Fprintln(w, `Code: 'acme-dns'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "ACME_DNS_API_BASE": The ACME-DNS API address`) - fmt.Fprintln(w, ` - "ACME_DNS_STORAGE_PATH": The ACME-DNS JSON account data file. A per-domain account will be registered/persisted to this file and used for TXT updates.`) - fmt.Fprintln(w) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/acme-dns`) - - case "alidns": - // generated from: providers/dns/alidns/alidns.toml - fmt.Fprintln(w, `Configuration for Alibaba Cloud DNS.`) - fmt.Fprintln(w, `Code: 'alidns'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "ALICLOUD_ACCESS_KEY": Access key ID`) - fmt.Fprintln(w, ` - "ALICLOUD_SECRET_KEY": Access Key secret`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "ALICLOUD_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "ALICLOUD_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "ALICLOUD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "ALICLOUD_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/alidns`) - - case "auroradns": - // generated from: providers/dns/auroradns/auroradns.toml - fmt.Fprintln(w, `Configuration for Aurora DNS.`) - fmt.Fprintln(w, `Code: 'auroradns'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "AURORA_ENDPOINT": API endpoint URL`) - fmt.Fprintln(w, ` - "AURORA_KEY": User API key`) - fmt.Fprintln(w, ` - "AURORA_USER_ID": User ID`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "AURORA_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "AURORA_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "AURORA_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/auroradns`) - - case "azure": - // generated from: providers/dns/azure/azure.toml - fmt.Fprintln(w, `Configuration for Azure.`) - fmt.Fprintln(w, `Code: 'azure'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "AZURE_CLIENT_ID": Client ID`) - fmt.Fprintln(w, ` - "AZURE_CLIENT_SECRET": Client secret`) - fmt.Fprintln(w, ` - "AZURE_RESOURCE_GROUP": Resource group`) - fmt.Fprintln(w, ` - "AZURE_SUBSCRIPTION_ID": Subscription ID`) - fmt.Fprintln(w, ` - "AZURE_TENANT_ID": Tenant ID`) - fmt.Fprintln(w, ` - "instance metadata service": If the credentials are **not** set via the environment, then it will attempt to get a bearer token via the [instance metadata service](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service).`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "AZURE_METADATA_ENDPOINT": Metadata Service endpoint URL`) - fmt.Fprintln(w, ` - "AZURE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "AZURE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "AZURE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/azure`) - - case "bindman": - // generated from: providers/dns/bindman/bindman.toml - fmt.Fprintln(w, `Configuration for Bindman.`) - fmt.Fprintln(w, `Code: 'bindman'`) - fmt.Fprintln(w, `Since: 'v2.6.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "BINDMAN_MANAGER_ADDRESS": The server URL, should have scheme, hostname, and port (if required) of the Bindman-DNS Manager server`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "BINDMAN_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "BINDMAN_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "BINDMAN_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/bindman`) - - case "bluecat": - // generated from: providers/dns/bluecat/bluecat.toml - fmt.Fprintln(w, `Configuration for Bluecat.`) - fmt.Fprintln(w, `Code: 'bluecat'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "BLUECAT_CONFIG_NAME": Configuration name`) - fmt.Fprintln(w, ` - "BLUECAT_DNS_VIEW": External DNS View Name`) - fmt.Fprintln(w, ` - "BLUECAT_PASSWORD": API password`) - fmt.Fprintln(w, ` - "BLUECAT_SERVER_URL": The server URL, should have scheme, hostname, and port (if required) of the authoritative Bluecat BAM serve`) - fmt.Fprintln(w, ` - "BLUECAT_USER_NAME": API username`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "BLUECAT_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "BLUECAT_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "BLUECAT_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "BLUECAT_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/bluecat`) - - case "cloudflare": - // generated from: providers/dns/cloudflare/cloudflare.toml - fmt.Fprintln(w, `Configuration for Cloudflare.`) - fmt.Fprintln(w, `Code: 'cloudflare'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "CLOUDFLARE_API_KEY": API key`) - fmt.Fprintln(w, ` - "CLOUDFLARE_EMAIL": Account email`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "CLOUDFLARE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "CLOUDFLARE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "CLOUDFLARE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "CLOUDFLARE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/cloudflare`) - - case "cloudns": - // generated from: providers/dns/cloudns/cloudns.toml - fmt.Fprintln(w, `Configuration for ClouDNS.`) - fmt.Fprintln(w, `Code: 'cloudns'`) - fmt.Fprintln(w, `Since: 'v2.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "CLOUDNS_AUTH_ID": The API user ID`) - fmt.Fprintln(w, ` - "CLOUDNS_AUTH_PASSWORD": The password for API user ID`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "CLOUDNS_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "CLOUDNS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "CLOUDNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "CLOUDNS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/cloudns`) - - case "cloudxns": - // generated from: providers/dns/cloudxns/cloudxns.toml - fmt.Fprintln(w, `Configuration for CloudXNS.`) - fmt.Fprintln(w, `Code: 'cloudxns'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "CLOUDXNS_API_KEY": The API key`) - fmt.Fprintln(w, ` - "CLOUDXNS_SECRET_KEY": THe API secret key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "CLOUDXNS_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "CLOUDXNS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "CLOUDXNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "CLOUDXNS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/cloudxns`) - - case "conoha": - // generated from: providers/dns/conoha/conoha.toml - fmt.Fprintln(w, `Configuration for ConoHa.`) - fmt.Fprintln(w, `Code: 'conoha'`) - fmt.Fprintln(w, `Since: 'v1.2.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "CONOHA_API_PASSWORD": The API password`) - fmt.Fprintln(w, ` - "CONOHA_API_USERNAME": The API username`) - fmt.Fprintln(w, ` - "CONOHA_TENANT_ID": Tenant ID`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "CONOHA_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "CONOHA_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "CONOHA_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "CONOHA_REGION": The region`) - fmt.Fprintln(w, ` - "CONOHA_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/conoha`) - - case "designate": - // generated from: providers/dns/designate/designate.toml - fmt.Fprintln(w, `Configuration for Designate DNSaaS for Openstack.`) - fmt.Fprintln(w, `Code: 'designate'`) - fmt.Fprintln(w, `Since: 'v2.2.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "OS_AUTH_URL": Identity endpoint URL`) - fmt.Fprintln(w, ` - "OS_PASSWORD": Password`) - fmt.Fprintln(w, ` - "OS_REGION_NAME": Region name`) - fmt.Fprintln(w, ` - "OS_TENANT_NAME": Tenant name`) - fmt.Fprintln(w, ` - "OS_USERNAME": Username`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DESIGNATE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DESIGNATE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DESIGNATE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/designate`) - - case "digitalocean": - // generated from: providers/dns/digitalocean/digitalocean.toml - fmt.Fprintln(w, `Configuration for Digital Ocean.`) - fmt.Fprintln(w, `Code: 'digitalocean'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DO_AUTH_TOKEN": Authentication token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DO_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DO_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DO_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DO_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/digitalocean`) - - case "dnsimple": - // generated from: providers/dns/dnsimple/dnsimple.toml - fmt.Fprintln(w, `Configuration for DNSimple.`) - fmt.Fprintln(w, `Code: 'dnsimple'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DNSIMPLE_BASE_URL": API endpoint URL`) - fmt.Fprintln(w, ` - "DNSIMPLE_OAUTH_TOKEN": OAuth token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DNSIMPLE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DNSIMPLE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DNSIMPLE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/dnsimple`) - - case "dnsmadeeasy": - // generated from: providers/dns/dnsmadeeasy/dnsmadeeasy.toml - fmt.Fprintln(w, `Configuration for DNS Made Easy.`) - fmt.Fprintln(w, `Code: 'dnsmadeeasy'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DNSMADEEASY_API_KEY": The API key`) - fmt.Fprintln(w, ` - "DNSMADEEASY_API_SECRET": The API Secret key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DNSMADEEASY_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DNSMADEEASY_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DNSMADEEASY_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DNSMADEEASY_SANDBOX": Activate the sandbox (boolean)`) - fmt.Fprintln(w, ` - "DNSMADEEASY_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/dnsmadeeasy`) - - case "dnspod": - // generated from: providers/dns/dnspod/dnspod.toml - fmt.Fprintln(w, `Configuration for DNSPod.`) - fmt.Fprintln(w, `Code: 'dnspod'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DNSPOD_API_KEY": The user token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DNSPOD_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DNSPOD_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DNSPOD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DNSPOD_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/dnspod`) - - case "dode": - // generated from: providers/dns/dode/dode.toml - fmt.Fprintln(w, `Configuration for Domain Offensive (do.de).`) - fmt.Fprintln(w, `Code: 'dode'`) - fmt.Fprintln(w, `Since: 'v2.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DODE_TOKEN": API token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DODE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DODE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DODE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DODE_SEQUENCE_INTERVAL": Interval between iteration`) - fmt.Fprintln(w, ` - "DODE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/dode`) - - case "dreamhost": - // generated from: providers/dns/dreamhost/dreamhost.toml - fmt.Fprintln(w, `Configuration for DreamHost.`) - fmt.Fprintln(w, `Code: 'dreamhost'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DREAMHOST_API_KEY": The API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DREAMHOST_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DREAMHOST_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DREAMHOST_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DREAMHOST_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/dreamhost`) - - case "duckdns": - // generated from: providers/dns/duckdns/duckdns.toml - fmt.Fprintln(w, `Configuration for Duck DNS.`) - fmt.Fprintln(w, `Code: 'duckdns'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DUCKDNS_TOKEN": Account token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DUCKDNS_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DUCKDNS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DUCKDNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DUCKDNS_SEQUENCE_INTERVAL": Interval between iteration`) - fmt.Fprintln(w, ` - "DUCKDNS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/duckdns`) - - case "dyn": - // generated from: providers/dns/dyn/dyn.toml - fmt.Fprintln(w, `Configuration for Dyn.`) - fmt.Fprintln(w, `Code: 'dyn'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "DYN_CUSTOMER_NAME": Customer name`) - fmt.Fprintln(w, ` - "DYN_PASSWORD": Paswword`) - fmt.Fprintln(w, ` - "DYN_USER_NAME": User name`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "DYN_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "DYN_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "DYN_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "DYN_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/dyn`) - - case "easydns": - // generated from: providers/dns/easydns/easydns.toml - fmt.Fprintln(w, `Configuration for EasyDNS.`) - fmt.Fprintln(w, `Code: 'easydns'`) - fmt.Fprintln(w, `Since: 'v2.6.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "EASYDNS_KEY": API Key`) - fmt.Fprintln(w, ` - "EASYDNS_TOKEN": API Token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "EASYDNS_ENDPOINT": The endpoint URL of the API Server`) - fmt.Fprintln(w, ` - "EASYDNS_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "EASYDNS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "EASYDNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "EASYDNS_SEQUENCE_INTERVAL": Time between sequential requests`) - fmt.Fprintln(w, ` - "EASYDNS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/easydns`) - - case "exec": - // generated from: providers/dns/exec/exec.toml - fmt.Fprintln(w, `Configuration for External program.`) - fmt.Fprintln(w, `Code: 'exec'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/exec`) - - case "exoscale": - // generated from: providers/dns/exoscale/exoscale.toml - fmt.Fprintln(w, `Configuration for Exoscale.`) - fmt.Fprintln(w, `Code: 'exoscale'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "EXOSCALE_API_KEY": API key`) - fmt.Fprintln(w, ` - "EXOSCALE_API_SECRET": API secret`) - fmt.Fprintln(w, ` - "EXOSCALE_ENDPOINT": API endpoint URL`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "EXOSCALE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "EXOSCALE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "EXOSCALE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "EXOSCALE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/exoscale`) - - case "fastdns": - // generated from: providers/dns/fastdns/fastdns.toml - fmt.Fprintln(w, `Configuration for FastDNS.`) - fmt.Fprintln(w, `Code: 'fastdns'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "AKAMAI_ACCESS_TOKEN": Access token`) - fmt.Fprintln(w, ` - "AKAMAI_CLIENT_SECRET": Client secret`) - fmt.Fprintln(w, ` - "AKAMAI_CLIENT_TOKEN": Client token`) - fmt.Fprintln(w, ` - "AKAMAI_HOST": API host`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "AKAMAI_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "AKAMAI_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "AKAMAI_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/fastdns`) - - case "gandi": - // generated from: providers/dns/gandi/gandi.toml - fmt.Fprintln(w, `Configuration for Gandi.`) - fmt.Fprintln(w, `Code: 'gandi'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "GANDI_API_KEY": API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "GANDI_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "GANDI_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "GANDI_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "GANDI_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/gandi`) - - case "gandiv5": - // generated from: providers/dns/gandiv5/gandiv5.toml - fmt.Fprintln(w, `Configuration for Gandi Live DNS (v5).`) - fmt.Fprintln(w, `Code: 'gandiv5'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "GANDIV5_API_KEY": API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "GANDIV5_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "GANDIV5_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "GANDIV5_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "GANDIV5_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/gandiv5`) - - case "gcloud": - // generated from: providers/dns/gcloud/gcloud.toml - fmt.Fprintln(w, `Configuration for Google Cloud.`) - fmt.Fprintln(w, `Code: 'gcloud'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "Application Default Credentials": [Documentation](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application)`) - fmt.Fprintln(w, ` - "GCE_PROJECT": Project name`) - fmt.Fprintln(w, ` - "GCE_SERVICE_ACCOUNT": Account`) - fmt.Fprintln(w, ` - "GCE_SERVICE_ACCOUNT_FILE": Account file path`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "GCE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "GCE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "GCE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/gcloud`) - - case "glesys": - // generated from: providers/dns/glesys/glesys.toml - fmt.Fprintln(w, `Configuration for Glesys.`) - fmt.Fprintln(w, `Code: 'glesys'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "GLESYS_API_KEY": API key`) - fmt.Fprintln(w, ` - "GLESYS_API_USER": API user`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "GLESYS_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "GLESYS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "GLESYS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "GLESYS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/glesys`) - - case "godaddy": - // generated from: providers/dns/godaddy/godaddy.toml - fmt.Fprintln(w, `Configuration for Go Daddy.`) - fmt.Fprintln(w, `Code: 'godaddy'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "GODADDY_API_KEY": API key`) - fmt.Fprintln(w, ` - "GODADDY_API_SECRET": API secret`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "GODADDY_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "GODADDY_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "GODADDY_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "GODADDY_SEQUENCE_INTERVAL": Interval between iteration`) - fmt.Fprintln(w, ` - "GODADDY_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/godaddy`) - - case "hostingde": - // generated from: providers/dns/hostingde/hostingde.toml - fmt.Fprintln(w, `Configuration for Hosting.de.`) - fmt.Fprintln(w, `Code: 'hostingde'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "HOSTINGDE_API_KEY": API key`) - fmt.Fprintln(w, ` - "HOSTINGDE_ZONE_NAME": Zone name in ACE format`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "HOSTINGDE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "HOSTINGDE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "HOSTINGDE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "HOSTINGDE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/hostingde`) - - case "httpreq": - // generated from: providers/dns/httpreq/httpreq.toml - fmt.Fprintln(w, `Configuration for HTTP request.`) - fmt.Fprintln(w, `Code: 'httpreq'`) - fmt.Fprintln(w, `Since: 'v2.0.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "HTTPREQ_ENDPOINT": The URL of the server`) - fmt.Fprintln(w, ` - "HTTPREQ_MODE": 'RAW', none`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "HTTPREQ_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "HTTPREQ_PASSWORD": Basic authentication password`) - fmt.Fprintln(w, ` - "HTTPREQ_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "HTTPREQ_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "HTTPREQ_USERNAME": Basic authentication username`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/httpreq`) - - case "iij": - // generated from: providers/dns/iij/iij.toml - fmt.Fprintln(w, `Configuration for Internet Initiative Japan.`) - fmt.Fprintln(w, `Code: 'iij'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "IIJ_API_ACCESS_KEY": API access key`) - fmt.Fprintln(w, ` - "IIJ_API_SECRET_KEY": API secret key`) - fmt.Fprintln(w, ` - "IIJ_DO_SERVICE_CODE": DO service code`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "IIJ_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "IIJ_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "IIJ_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/iij`) - - case "inwx": - // generated from: providers/dns/inwx/inwx.toml - fmt.Fprintln(w, `Configuration for INWX.`) - fmt.Fprintln(w, `Code: 'inwx'`) - fmt.Fprintln(w, `Since: 'v2.0.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "INWX_PASSWORD": Password`) - fmt.Fprintln(w, ` - "INWX_USERNAME": Username`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "INWX_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "INWX_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "INWX_SANDBOX": Activate the sandbox (boolean)`) - fmt.Fprintln(w, ` - "INWX_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/inwx`) - - case "joker": - // generated from: providers/dns/joker/joker.toml - fmt.Fprintln(w, `Configuration for Joker.`) - fmt.Fprintln(w, `Code: 'joker'`) - fmt.Fprintln(w, `Since: 'v2.6.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "JOKER_API_KEY": API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "JOKER_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "JOKER_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "JOKER_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "JOKER_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/joker`) - - case "lightsail": - // generated from: providers/dns/lightsail/lightsail.toml - fmt.Fprintln(w, `Configuration for Amazon Lightsail.`) - fmt.Fprintln(w, `Code: 'lightsail'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "AWS_ACCESS_KEY_ID": Access key ID`) - fmt.Fprintln(w, ` - "AWS_SECRET_ACCESS_KEY": Secret access key`) - fmt.Fprintln(w, ` - "DNS_ZONE": DNS zone`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "LIGHTSAIL_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "LIGHTSAIL_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/lightsail`) - - case "linode": - // generated from: providers/dns/linode/linode.toml - fmt.Fprintln(w, `Configuration for Linode (deprecated).`) - fmt.Fprintln(w, `Code: 'linode'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "LINODE_API_KEY": API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "LINODE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "LINODE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "LINODE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/linode`) - - case "linodev4": - // generated from: providers/dns/linodev4/linodev4.toml - fmt.Fprintln(w, `Configuration for Linode (v4).`) - fmt.Fprintln(w, `Code: 'linodev4'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "LINODE_TOKEN": API token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "LINODE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "LINODE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "LINODE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/linodev4`) - - case "mydnsjp": - // generated from: providers/dns/mydnsjp/mydnsjp.toml - fmt.Fprintln(w, `Configuration for MyDNS.jp.`) - fmt.Fprintln(w, `Code: 'mydnsjp'`) - fmt.Fprintln(w, `Since: 'v1.2.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "MYDNSJP_MASTER_ID": Master ID`) - fmt.Fprintln(w, ` - "MYDNSJP_PASSWORD": Password`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "MYDNSJP_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "MYDNSJP_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "MYDNSJP_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "MYDNSJP_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/mydnsjp`) - - case "namecheap": - // generated from: providers/dns/namecheap/namecheap.toml - fmt.Fprintln(w, `Configuration for Namecheap.`) - fmt.Fprintln(w, `Code: 'namecheap'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "NAMECHEAP_API_KEY": API key`) - fmt.Fprintln(w, ` - "NAMECHEAP_API_USER": API user`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "NAMECHEAP_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "NAMECHEAP_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "NAMECHEAP_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "NAMECHEAP_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/namecheap`) - - case "namedotcom": - // generated from: providers/dns/namedotcom/namedotcom.toml - fmt.Fprintln(w, `Configuration for Name.com.`) - fmt.Fprintln(w, `Code: 'namedotcom'`) - fmt.Fprintln(w, `Since: 'v0.5.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "NAMECOM_API_TOKEN": API token`) - fmt.Fprintln(w, ` - "NAMECOM_USERNAME": Username`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "NAMECOM_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "NAMECOM_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "NAMECOM_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "NAMECOM_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/namedotcom`) - - case "netcup": - // generated from: providers/dns/netcup/netcup.toml - fmt.Fprintln(w, `Configuration for Netcup.`) - fmt.Fprintln(w, `Code: 'netcup'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "NETCUP_API_KEY": API key`) - fmt.Fprintln(w, ` - "NETCUP_API_PASSWORD": API password`) - fmt.Fprintln(w, ` - "NETCUP_CUSTOMER_NUMBER": Customer number`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "NETCUP_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "NETCUP_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "NETCUP_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "NETCUP_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/netcup`) - - case "nifcloud": - // generated from: providers/dns/nifcloud/nifcloud.toml - fmt.Fprintln(w, `Configuration for NIFCloud.`) - fmt.Fprintln(w, `Code: 'nifcloud'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "NIFCLOUD_ACCESS_KEY_ID": Access key`) - fmt.Fprintln(w, ` - "NIFCLOUD_SECRET_ACCESS_KEY": Secret access key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "NIFCLOUD_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "NIFCLOUD_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "NIFCLOUD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "NIFCLOUD_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/nifcloud`) - - case "ns1": - // generated from: providers/dns/ns1/ns1.toml - fmt.Fprintln(w, `Configuration for NS1.`) - fmt.Fprintln(w, `Code: 'ns1'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "NS1_API_KEY": API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "NS1_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "NS1_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "NS1_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "NS1_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/ns1`) - - case "oraclecloud": - // generated from: providers/dns/oraclecloud/oraclecloud.toml - fmt.Fprintln(w, `Configuration for Oracle Cloud.`) - fmt.Fprintln(w, `Code: 'oraclecloud'`) - fmt.Fprintln(w, `Since: 'v2.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "OCI_COMPARTMENT_OCID": Compartment OCID`) - fmt.Fprintln(w, ` - "OCI_PRIVKEY_FILE": Private key file`) - fmt.Fprintln(w, ` - "OCI_PRIVKEY_PASS": Private key password`) - fmt.Fprintln(w, ` - "OCI_PUBKEY_FINGERPRINT": Public key fingerprint`) - fmt.Fprintln(w, ` - "OCI_REGION": Region`) - fmt.Fprintln(w, ` - "OCI_TENANCY_OCID": Tenanct OCID`) - fmt.Fprintln(w, ` - "OCI_USER_OCID": User OCID`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "OCI_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "OCI_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "OCI_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/oraclecloud`) - - case "otc": - // generated from: providers/dns/otc/otc.toml - fmt.Fprintln(w, `Configuration for Open Telekom Cloud.`) - fmt.Fprintln(w, `Code: 'otc'`) - fmt.Fprintln(w, `Since: 'v0.4.1'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "OTC_DOMAIN_NAME": Domain name`) - fmt.Fprintln(w, ` - "OTC_IDENTITY_ENDPOINT": Identity endpoint URL`) - fmt.Fprintln(w, ` - "OTC_PASSWORD": Password`) - fmt.Fprintln(w, ` - "OTC_PROJECT_NAME": Project name`) - fmt.Fprintln(w, ` - "OTC_USER_NAME": User name`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "OTC_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "OTC_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "OTC_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "OTC_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/otc`) - - case "ovh": - // generated from: providers/dns/ovh/ovh.toml - fmt.Fprintln(w, `Configuration for OVH.`) - fmt.Fprintln(w, `Code: 'ovh'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "OVH_APPLICATION_KEY": Application key`) - fmt.Fprintln(w, ` - "OVH_APPLICATION_SECRET": Application secret`) - fmt.Fprintln(w, ` - "OVH_CONSUMER_KEY": Consumer key`) - fmt.Fprintln(w, ` - "OVH_ENDPOINT": Endpoint URL (ovh-eu or ovh-ca)`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "OVH_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "OVH_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "OVH_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "OVH_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/ovh`) - - case "pdns": - // generated from: providers/dns/pdns/pdns.toml - fmt.Fprintln(w, `Configuration for PowerDNS.`) - fmt.Fprintln(w, `Code: 'pdns'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "PDNS_API_KEY": API key`) - fmt.Fprintln(w, ` - "PDNS_API_URL": API url`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "PDNS_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "PDNS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "PDNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "PDNS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/pdns`) - - case "rackspace": - // generated from: providers/dns/rackspace/rackspace.toml - fmt.Fprintln(w, `Configuration for Rackspace.`) - fmt.Fprintln(w, `Code: 'rackspace'`) - fmt.Fprintln(w, `Since: 'v0.4.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "RACKSPACE_API_KEY": API key`) - fmt.Fprintln(w, ` - "RACKSPACE_USER": API user`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "RACKSPACE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "RACKSPACE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "RACKSPACE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "RACKSPACE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/rackspace`) - - case "rfc2136": - // generated from: providers/dns/rfc2136/rfc2136.toml - fmt.Fprintln(w, `Configuration for RFC2136.`) - fmt.Fprintln(w, `Code: 'rfc2136'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "RFC2136_NAMESERVER": Network address in the form "host" or "host:port"`) - fmt.Fprintln(w, ` - "RFC2136_TSIG_ALGORITHM": TSIG algorythm. See [miekg/dns#tsig.go](https://github.com/miekg/dns/blob/master/tsig.go) for supported values. To disable TSIG authentication, leave the 'RFC2136_TSIG*' variables unset.`) - fmt.Fprintln(w, ` - "RFC2136_TSIG_KEY": Name of the secret key as defined in DNS server configuration. To disable TSIG authentication, leave the 'RFC2136_TSIG*' variables unset.`) - fmt.Fprintln(w, ` - "RFC2136_TSIG_SECRET": Secret key payload. To disable TSIG authentication, leave the' RFC2136_TSIG*' variables unset.`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "RFC2136_DNS_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "RFC2136_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "RFC2136_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "RFC2136_SEQUENCE_INTERVAL": Interval between iteration`) - fmt.Fprintln(w, ` - "RFC2136_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/rfc2136`) - - case "route53": - // generated from: providers/dns/route53/route53.toml - fmt.Fprintln(w, `Configuration for Amazon Route 53.`) - fmt.Fprintln(w, `Code: 'route53'`) - fmt.Fprintln(w, `Since: 'v0.3.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "AWS_ACCESS_KEY_ID": Managed by the AWS client`) - fmt.Fprintln(w, ` - "AWS_HOSTED_ZONE_ID": Override the hosted zone ID`) - fmt.Fprintln(w, ` - "AWS_REGION": Managed by the AWS client`) - fmt.Fprintln(w, ` - "AWS_SECRET_ACCESS_KEY": Managed by the AWS client`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "AWS_MAX_RETRIES": The number of maximum returns the service will use to make an individual API request`) - fmt.Fprintln(w, ` - "AWS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "AWS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "AWS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/route53`) - - case "sakuracloud": - // generated from: providers/dns/sakuracloud/sakuracloud.toml - fmt.Fprintln(w, `Configuration for Sakura Cloud.`) - fmt.Fprintln(w, `Code: 'sakuracloud'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "SAKURACLOUD_ACCESS_TOKEN": Access token`) - fmt.Fprintln(w, ` - "SAKURACLOUD_ACCESS_TOKEN_SECRET": Access token secret`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "SAKURACLOUD_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "SAKURACLOUD_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "SAKURACLOUD_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "SAKURACLOUD_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/sakuracloud`) - - case "selectel": - // generated from: providers/dns/selectel/selectel.toml - fmt.Fprintln(w, `Configuration for Selectel.`) - fmt.Fprintln(w, `Code: 'selectel'`) - fmt.Fprintln(w, `Since: 'v1.2.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "SELECTEL_API_TOKEN": API token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "SELECTEL_BASE_URL": API endpoint URL`) - fmt.Fprintln(w, ` - "SELECTEL_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "SELECTEL_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "SELECTEL_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "SELECTEL_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/selectel`) - - case "stackpath": - // generated from: providers/dns/stackpath/stackpath.toml - fmt.Fprintln(w, `Configuration for Stackpath.`) - fmt.Fprintln(w, `Code: 'stackpath'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "STACKPATH_CLIENT_ID": Client ID`) - fmt.Fprintln(w, ` - "STACKPATH_CLIENT_SECRET": Client secret`) - fmt.Fprintln(w, ` - "STACKPATH_STACK_ID": Stack ID`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "STACKPATH_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "STACKPATH_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "STACKPATH_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/stackpath`) - - case "transip": - // generated from: providers/dns/transip/transip.toml - fmt.Fprintln(w, `Configuration for TransIP.`) - fmt.Fprintln(w, `Code: 'transip'`) - fmt.Fprintln(w, `Since: 'v2.0.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "TRANSIP_ACCOUNT_NAME": Account name`) - fmt.Fprintln(w, ` - "TRANSIP_PRIVATE_KEY_PATH": Private key path`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "TRANSIP_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "TRANSIP_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "TRANSIP_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/transip`) - - case "vegadns": - // generated from: providers/dns/vegadns/vegadns.toml - fmt.Fprintln(w, `Configuration for VegaDNS.`) - fmt.Fprintln(w, `Code: 'vegadns'`) - fmt.Fprintln(w, `Since: 'v1.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "SECRET_VEGADNS_KEY": API key`) - fmt.Fprintln(w, ` - "SECRET_VEGADNS_SECRET": API secret`) - fmt.Fprintln(w, ` - "VEGADNS_URL": API endpoint URL`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "VEGADNS_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "VEGADNS_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "VEGADNS_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/vegadns`) - - case "vscale": - // generated from: providers/dns/vscale/vscale.toml - fmt.Fprintln(w, `Configuration for Vscale.`) - fmt.Fprintln(w, `Code: 'vscale'`) - fmt.Fprintln(w, `Since: 'v2.0.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "VSCALE_API_TOKEN": API token`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "VSCALE_BASE_URL": API enddpoint URL`) - fmt.Fprintln(w, ` - "VSCALE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "VSCALE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "VSCALE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "VSCALE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/vscale`) - - case "vultr": - // generated from: providers/dns/vultr/vultr.toml - fmt.Fprintln(w, `Configuration for Vultr.`) - fmt.Fprintln(w, `Code: 'vultr'`) - fmt.Fprintln(w, `Since: 'v0.3.1'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "VULTR_API_KEY": API key`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "VULTR_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "VULTR_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "VULTR_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "VULTR_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/vultr`) - - case "zoneee": - // generated from: providers/dns/zoneee/zoneee.toml - fmt.Fprintln(w, `Configuration for Zone.ee.`) - fmt.Fprintln(w, `Code: 'zoneee'`) - fmt.Fprintln(w, `Since: 'v2.1.0'`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Credentials:`) - fmt.Fprintln(w, ` - "ZONEEE_API_KEY": API key`) - fmt.Fprintln(w, ` - "ZONEEE_API_USER": API user`) - fmt.Fprintln(w) - - fmt.Fprintln(w, `Additional Configuration:`) - fmt.Fprintln(w, ` - "ZONEEE_ENDPOINT": API endpoint URL`) - fmt.Fprintln(w, ` - "ZONEEE_HTTP_TIMEOUT": API request timeout`) - fmt.Fprintln(w, ` - "ZONEEE_POLLING_INTERVAL": Time between DNS propagation check`) - fmt.Fprintln(w, ` - "ZONEEE_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation`) - fmt.Fprintln(w, ` - "ZONEEE_TTL": The TTL of the TXT record used for the DNS challenge`) - - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/zoneee`) - - case "manual": - fmt.Fprintln(w, `Solving the DNS-01 challenge using CLI prompt.`) - default: - log.Fatalf("%q is not yet supported.", name) - } - w.Flush() -} diff --git a/vendor/github.com/go-acme/lego/docs/.gitignore b/vendor/github.com/go-acme/lego/docs/.gitignore deleted file mode 100644 index 7b82297..0000000 --- a/vendor/github.com/go-acme/lego/docs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -themes/ -public/ diff --git a/vendor/github.com/go-acme/lego/docs/Makefile b/vendor/github.com/go-acme/lego/docs/Makefile deleted file mode 100644 index 09d3dad..0000000 --- a/vendor/github.com/go-acme/lego/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -.PHONY: default clean hugo hugo-build - -default: hugo - -clean: - rm -rf public/ - - -hugo-build: clean hugo-themes - hugo --enableGitInfo --source . - -hugo: - hugo server --disableFastRender --enableGitInfo --watch --source . - # hugo server -D - -hugo-themes: - rm -rf themes - mkdir themes - git clone --depth=1 https://github.com/matcornic/hugo-theme-learn.git themes/hugo-theme-learn - rm -rf themes/hugo-theme-learn/.git diff --git a/vendor/github.com/go-acme/lego/docs/archetypes/default.md b/vendor/github.com/go-acme/lego/docs/archetypes/default.md deleted file mode 100644 index 00e77bd..0000000 --- a/vendor/github.com/go-acme/lego/docs/archetypes/default.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: "{{ replace .Name "-" " " | title }}" -date: {{ .Date }} -draft: true ---- - diff --git a/vendor/github.com/go-acme/lego/docs/config.toml b/vendor/github.com/go-acme/lego/docs/config.toml deleted file mode 100644 index b13cf69..0000000 --- a/vendor/github.com/go-acme/lego/docs/config.toml +++ /dev/null @@ -1,67 +0,0 @@ -baseURL = "https://go-acme.github.io/lego/" -languageCode = "en-us" -title = "Lego" - -theme = "hugo-theme-learn" - -# Code higlighting settings -pygmentsCodefences = true -pygmentsCodeFencesGuesSsyntax = false -pygmentsOptions = "" -pygmentsStyle = "monokai" -# The monokai stylesheet is included in the base template. -pygmentsUseClasses = true - -[permalinks] - dns = "/dns/:slug/" - -[params] - # Prefix URL to edit current page. Will display an "Edit this page" button on top right hand corner of every page. - # Useful to give opportunity to people to create merge request for your doc. - # See the config.toml file from this documentation site to have an example. -# editURL = "" - # Author of the site, will be used in meta information - author = "Lego Team" - # Description of the site, will be used in meta information -# description = "" - # Shows a checkmark for visited pages on the menu - showVisitedLinks = true - # Disable search function. It will hide search bar -# disableSearch = false - # Javascript and CSS cache are automatically busted when new version of site is generated. - # Set this to true to disable this behavior (some proxies don't handle well this optimization) -# disableAssetsBusting = false - # Set this to true to disable copy-to-clipboard button for inline code. -# disableInlineCopyToClipBoard = true - # A title for shortcuts in menu is set by default. Set this to true to disable it. -# disableShortcutsTitle = false - # When using mulitlingual website, disable the switch language button. -# disableLanguageSwitchingButton = false - # Hide breadcrumbs in the header and only show the current page title -# disableBreadcrumb = true - # Hide Next and Previous page buttons normally displayed full height beside content -# disableNextPrev = true - # Order sections in menu by "weight" or "title". Default to "weight" -# ordersectionsby = "weight" - # Change default color scheme with a variant one. Can be "red", "blue", "green". - themeVariant = "blue" - -[Languages] -[Languages.en] - title = "Let’s Encrypt client and ACME library written in Go." - weight = 1 - languageName = "English" - -[[Languages.en.menu.shortcuts]] - name = " Github repo" - identifier = "ds" - url = "https://github.com/go-acme/lego" - weight = 10 - -[[Languages.en.menu.shortcuts]] - name = " Issues" - url = "https://github.com/go-acme/lego/issues" - weight = 11 - -[outputs] - home = [ "HTML", "RSS", "JSON"] diff --git a/vendor/github.com/go-acme/lego/docs/content/_index.md b/vendor/github.com/go-acme/lego/docs/content/_index.md deleted file mode 100644 index 55e26c4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/_index.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: "Welcome" -date: 2019-03-03T16:39:46+01:00 -draft: false -chapter: true ---- - -# Lego - -Let's Encrypt client and ACME library written in Go. - -## Features - -- Register with CA -- Obtain certificates, both from scratch or with an existing CSR -- Renew certificates -- Revoke certificates -- Robust implementation of all ACME challenges - - HTTP (http-01) - - DNS (dns-01) - - TLS (tls-alpn-01) -- SAN certificate support -- Comes with multiple optional [DNS providers](dns) -- [Custom challenge solvers](usage/library/writing-a-challenge-solver/) -- Certificate bundling -- OCSP helper function - - -lego introduced support for ACME v2 in [v1.0.0](https://github.com/go-acme/lego/releases/tag/v1.0.0). -If you still need to utilize ACME v1, you can do so by using the [v0.5.0](https://github.com/go-acme/lego/releases/tag/v0.5.0) version. diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/_index.md b/vendor/github.com/go-acme/lego/docs/content/dns/_index.md deleted file mode 100644 index 7078e41..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/_index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: "DNS Providers" -date: 2019-03-03T16:39:46+01:00 -draft: false -weight: 3 ---- - -## Configuration and Credentials - -Credentials and DNS configuration for DNS providers must be passed through environment variables. - -### Environment Variables: Value - -The environment variables can reference a value. - -Here is an example bash command using the CloudFlare DNS provider: - -```bash -$ CLOUDFLARE_EMAIL=foo@bar.com \ -CLOUDFLARE_API_KEY=b9841238feb177a84330febba8a83208921177bffe733 \ -lego --dns cloudflare --domains www.example.com --email me@bar.com run -``` - -### Environment Variables: File - -The environment variables can reference a path to file. - -In this case the name of environment variable must be suffixed by `_FILE`. - -{{% notice note %}} -The file must contain only the value. -{{% /notice %}} - -Here is an example bash command using the CloudFlare DNS provider: - -```bash -$ cat /the/path/to/my/key -b9841238feb177a84330febba8a83208921177bffe733 - -$ cat /the/path/to/my/email -foo@bar.com - -$ CLOUDFLARE_EMAIL_FILE=/the/path/to/my/email \ -CLOUDFLARE_API_KEY=/the/path/to/my/key \ -lego --dns cloudflare --domains www.example.com --email me@bar.com run -``` - -## Experimental Features - -To resolve CNAME when creating dns-01 challenge: -set `LEGO_EXPERIMENTAL_CNAME_SUPPORT` to `true`. - -## DNS Providers - -{{%children style="h2" description="true" %}} \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/manual.md b/vendor/github.com/go-acme/lego/docs/content/dns/manual.md deleted file mode 100644 index 8a9c125..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/manual.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "Manual" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: manual ---- - -Solving the DNS-01 challenge using CLI prompt. - - - -## Example - -```txt -Do you accept the TOS? Y/n - -[INFO] acme: Registering account for test@test.com -!!!! HEADS UP !!!! - - Your account credentials have been saved in your Let's Encrypt - configuration directory at "~/.lego/accounts". - You should make a secure backup of this folder now. This - configuration directory will also contain certificates and - private keys obtained from Let's Encrypt so making regular - backups of this folder is ideal. - -[INFO] [test.com] acme: Obtaining bundled SAN certificate -[INFO] [test.com] AuthURL: https://acme-v02.api.letsencrypt.org/acme/authz/lornkZmVYjsh5wLHpxdQcZDPekGf_TYUM-MTJk3-yrA -[INFO] [test.com] acme: Could not find solver for: tls-alpn-01 -[INFO] [test.com] acme: Could not find solver for: http-01 -[INFO] [test.com] acme: use dns-01 solver -[INFO] [test.com] acme: Preparing to solve DNS-01 -lego: Please create the following TXT record in your test.com. zone: -_acme-challenge.test.com. 120 IN TXT "VP-dby1RBuUOnDZg1n9sF-cwicLsognMzJb0Vx8ttAI" -lego: Press 'Enter' when you are done - -Do you accept the TOS? Y/n - -[INFO] acme: Registering account for test@test.com -!!!! HEADS UP !!!! - - Your account credentials have been saved in your Let's Encrypt - configuration directory at "~/.lego/accounts". - You should make a secure backup of this folder now. This - configuration directory will also contain certificates and - private keys obtained from Let's Encrypt so making regular - backups of this folder is ideal. - -[INFO] [test.com] acme: Obtaining bundled SAN certificate -[INFO] [test.com] AuthURL: https://acme-v02.api.letsencrypt.org/acme/authz/lornkZmVYjsh5wLHpxdQcZDPekGf_TYUM-MTJk3-yrA -[INFO] [test.com] acme: Could not find solver for: tls-alpn-01 -[INFO] [test.com] acme: Could not find solver for: http-01 -[INFO] [test.com] acme: use dns-01 solver -[INFO] [test.com] acme: Preparing to solve DNS-01 -lego: Please create the following TXT record in your test.com. zone: -_acme-challenge.test.com. 120 IN TXT "VP-dby1RBuUOnDZg1n9sF-cwicLsognMzJb0Vx8ttAI" -lego: Press 'Enter' when you are done - -``` \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_acme-dns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_acme-dns.md deleted file mode 100644 index 58e349d..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_acme-dns.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: "Joohoi's ACME-DNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: acme-dns ---- - - - - - -Since: v1.1.0 - -Configuration for [Joohoi's ACME-DNS](https://github.com/joohoi/acme-dns). - - - - -- Code: `acme-dns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `ACME_DNS_API_BASE` | The ACME-DNS API address | -| `ACME_DNS_STORAGE_PATH` | The ACME-DNS JSON account data file. A per-domain account will be registered/persisted to this file and used for TXT updates. | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - - - -## More information - -- [API documentation](https://github.com/joohoi/acme-dns#api) -- [Go client](https://github.com/cpu/goacmedns) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_alidns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_alidns.md deleted file mode 100644 index c4d4835..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_alidns.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Alibaba Cloud DNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: alidns ---- - - - - - -Since: v1.1.0 - -Configuration for [Alibaba Cloud DNS](https://www.alibabacloud.com/product/dns). - - - - -- Code: `alidns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `ALICLOUD_ACCESS_KEY` | Access key ID | -| `ALICLOUD_SECRET_KEY` | Access Key secret | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `ALICLOUD_HTTP_TIMEOUT` | API request timeout | -| `ALICLOUD_POLLING_INTERVAL` | Time between DNS propagation check | -| `ALICLOUD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `ALICLOUD_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.alibabacloud.com/help/doc-detail/42875.htm) -- [Go client](https://github.com/aliyun/alibaba-cloud-sdk-go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_auroradns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_auroradns.md deleted file mode 100644 index 0e9e6d4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_auroradns.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Aurora DNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: auroradns ---- - - - - - -Since: v0.4.0 - -Configuration for [Aurora DNS](https://www.pcextreme.com/aurora/dns). - - - - -- Code: `auroradns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `AURORA_ENDPOINT` | API endpoint URL | -| `AURORA_KEY` | User API key | -| `AURORA_USER_ID` | User ID | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `AURORA_POLLING_INTERVAL` | Time between DNS propagation check | -| `AURORA_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `AURORA_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://libcloud.readthedocs.io/en/latest/dns/drivers/auroradns.html#api-docs) -- [Go client](https://github.com/nrdcg/auroradns) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_azure.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_azure.md deleted file mode 100644 index 70abe1a..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_azure.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: "Azure" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: azure ---- - - - - - -Since: v0.4.0 - -Configuration for [Azure](https://azure.microsoft.com/services/dns/). - - - - -- Code: `azure` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `AZURE_CLIENT_ID` | Client ID | -| `AZURE_CLIENT_SECRET` | Client secret | -| `AZURE_RESOURCE_GROUP` | Resource group | -| `AZURE_SUBSCRIPTION_ID` | Subscription ID | -| `AZURE_TENANT_ID` | Tenant ID | -| `instance metadata service` | If the credentials are **not** set via the environment, then it will attempt to get a bearer token via the [instance metadata service](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service). | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `AZURE_METADATA_ENDPOINT` | Metadata Service endpoint URL | -| `AZURE_POLLING_INTERVAL` | Time between DNS propagation check | -| `AZURE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `AZURE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://docs.microsoft.com/en-us/go/azure/) -- [Go client](https://github.com/Azure/azure-sdk-for-go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_bindman.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_bindman.md deleted file mode 100644 index bd4f552..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_bindman.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "Bindman" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: bindman ---- - - - - - -Since: v2.6.0 - -Configuration for [Bindman](https://github.com/labbsr0x/bindman-dns-webhook). - - - - -- Code: `bindman` - -Here is an example bash command using the Bindman provider: - -```bash -BINDMAN_MANAGER_ADDRESS= \ -lego --dns bindman --domains my.domain.com --email my@email.com run -``` - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `BINDMAN_MANAGER_ADDRESS` | The server URL, should have scheme, hostname, and port (if required) of the Bindman-DNS Manager server | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `BINDMAN_HTTP_TIMEOUT` | API request timeout | -| `BINDMAN_POLLING_INTERVAL` | Time between DNS propagation check | -| `BINDMAN_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://gitlab.isc.org/isc-projects/bind9) -- [Go client](https://github.com/labbsr0x/bindman-dns-webhook) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_bluecat.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_bluecat.md deleted file mode 100644 index 3e53edc..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_bluecat.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Bluecat" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: bluecat ---- - - - - - -Since: v0.5.0 - -Configuration for [Bluecat](https://www.bluecatnetworks.com). - - - - -- Code: `bluecat` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `BLUECAT_CONFIG_NAME` | Configuration name | -| `BLUECAT_DNS_VIEW` | External DNS View Name | -| `BLUECAT_PASSWORD` | API password | -| `BLUECAT_SERVER_URL` | The server URL, should have scheme, hostname, and port (if required) of the authoritative Bluecat BAM serve | -| `BLUECAT_USER_NAME` | API username | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `BLUECAT_HTTP_TIMEOUT` | API request timeout | -| `BLUECAT_POLLING_INTERVAL` | Time between DNS propagation check | -| `BLUECAT_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `BLUECAT_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudflare.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudflare.md deleted file mode 100644 index 774f706..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudflare.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: "Cloudflare" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: cloudflare ---- - - - - - -Since: v0.3.0 - -Configuration for [Cloudflare](https://www.cloudflare.com/dns/). - - - - -- Code: `cloudflare` - -Here is an example bash command using the Cloudflare provider: - -```bash -CLOUDFLARE_EMAIL=foo@bar.com \ -CLOUDFLARE_API_KEY=b9841238feb177a84330febba8a83208921177bffe733 \ -lego --dns cloudflare --domains my.domain.com --email my@email.com run -``` - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `CLOUDFLARE_API_KEY` | API key | -| `CLOUDFLARE_EMAIL` | Account email | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `CLOUDFLARE_HTTP_TIMEOUT` | API request timeout | -| `CLOUDFLARE_POLLING_INTERVAL` | Time between DNS propagation check | -| `CLOUDFLARE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `CLOUDFLARE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://api.cloudflare.com/) -- [Go client](https://github.com/cloudflare/cloudflare-go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudns.md deleted file mode 100644 index 14e792b..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudns.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "ClouDNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: cloudns ---- - - - - - -Since: v2.3.0 - -Configuration for [ClouDNS](https://www.cloudns.net). - - - - -- Code: `cloudns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `CLOUDNS_AUTH_ID` | The API user ID | -| `CLOUDNS_AUTH_PASSWORD` | The password for API user ID | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `CLOUDNS_HTTP_TIMEOUT` | API request timeout | -| `CLOUDNS_POLLING_INTERVAL` | Time between DNS propagation check | -| `CLOUDNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `CLOUDNS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.cloudns.net/wiki/article/42/) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudxns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudxns.md deleted file mode 100644 index 04eba1e..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_cloudxns.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "CloudXNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: cloudxns ---- - - - - - -Since: v0.5.0 - -Configuration for [CloudXNS](https://www.cloudxns.net/). - - - - -- Code: `cloudxns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `CLOUDXNS_API_KEY` | The API key | -| `CLOUDXNS_SECRET_KEY` | THe API secret key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `CLOUDXNS_HTTP_TIMEOUT` | API request timeout | -| `CLOUDXNS_POLLING_INTERVAL` | Time between DNS propagation check | -| `CLOUDXNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `CLOUDXNS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.cloudxns.net/Public/Doc/CloudXNS_api2.0_doc_zh-cn.zip) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_conoha.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_conoha.md deleted file mode 100644 index c13def5..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_conoha.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "ConoHa" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: conoha ---- - - - - - -Since: v1.2.0 - -Configuration for [ConoHa](https://www.conoha.jp/). - - - - -- Code: `conoha` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `CONOHA_API_PASSWORD` | The API password | -| `CONOHA_API_USERNAME` | The API username | -| `CONOHA_TENANT_ID` | Tenant ID | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `CONOHA_HTTP_TIMEOUT` | API request timeout | -| `CONOHA_POLLING_INTERVAL` | Time between DNS propagation check | -| `CONOHA_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `CONOHA_REGION` | The region | -| `CONOHA_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.conoha.jp/docs/) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_designate.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_designate.md deleted file mode 100644 index 50bdee4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_designate.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: "Designate DNSaaS for Openstack" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: designate ---- - - - - - -Since: v2.2.0 - -Configuration for [Designate DNSaaS for Openstack](https://docs.openstack.org/designate/latest/). - - - - -- Code: `designate` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `OS_AUTH_URL` | Identity endpoint URL | -| `OS_PASSWORD` | Password | -| `OS_REGION_NAME` | Region name | -| `OS_TENANT_NAME` | Tenant name | -| `OS_USERNAME` | Username | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DESIGNATE_POLLING_INTERVAL` | Time between DNS propagation check | -| `DESIGNATE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DESIGNATE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://docs.openstack.org/designate/latest/) -- [Go client](https://godoc.org/github.com/gophercloud/gophercloud/openstack/dns/v2) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_digitalocean.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_digitalocean.md deleted file mode 100644 index 72bd525..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_digitalocean.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "Digital Ocean" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: digitalocean ---- - - - - - -Since: v0.3.0 - -Configuration for [Digital Ocean](https://www.digitalocean.com/docs/networking/dns/). - - - - -- Code: `digitalocean` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DO_AUTH_TOKEN` | Authentication token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DO_HTTP_TIMEOUT` | API request timeout | -| `DO_POLLING_INTERVAL` | Time between DNS propagation check | -| `DO_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DO_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developers.digitalocean.com/documentation/v2/#domain-records) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnsimple.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnsimple.md deleted file mode 100644 index 7a7d6ad..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnsimple.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "DNSimple" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: dnsimple ---- - - - - - -Since: v0.3.0 - -Configuration for [DNSimple](https://dnsimple.com/). - - - - -- Code: `dnsimple` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DNSIMPLE_BASE_URL` | API endpoint URL | -| `DNSIMPLE_OAUTH_TOKEN` | OAuth token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DNSIMPLE_POLLING_INTERVAL` | Time between DNS propagation check | -| `DNSIMPLE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DNSIMPLE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developer.dnsimple.com/v2/) -- [Go client](https://github.com/dnsimple/dnsimple-go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnsmadeeasy.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnsmadeeasy.md deleted file mode 100644 index 475a9bc..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnsmadeeasy.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "DNS Made Easy" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: dnsmadeeasy ---- - - - - - -Since: v0.4.0 - -Configuration for [DNS Made Easy](https://dnsmadeeasy.com/). - - - - -- Code: `dnsmadeeasy` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DNSMADEEASY_API_KEY` | The API key | -| `DNSMADEEASY_API_SECRET` | The API Secret key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DNSMADEEASY_HTTP_TIMEOUT` | API request timeout | -| `DNSMADEEASY_POLLING_INTERVAL` | Time between DNS propagation check | -| `DNSMADEEASY_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DNSMADEEASY_SANDBOX` | Activate the sandbox (boolean) | -| `DNSMADEEASY_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://api-docs.dnsmadeeasy.com/) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnspod.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnspod.md deleted file mode 100644 index 824458b..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dnspod.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "DNSPod" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: dnspod ---- - - - - - -Since: v0.4.0 - -Configuration for [DNSPod](http://www.dnspod.com/). - - - - -- Code: `dnspod` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DNSPOD_API_KEY` | The user token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DNSPOD_HTTP_TIMEOUT` | API request timeout | -| `DNSPOD_POLLING_INTERVAL` | Time between DNS propagation check | -| `DNSPOD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DNSPOD_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.dnspod.com/docs/index.html) -- [Go client](https://github.com/decker502/dnspod-go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dode.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dode.md deleted file mode 100644 index dcafe6d..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dode.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Domain Offensive (do.de)" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: dode ---- - - - - - -Since: v2.4.0 - -Configuration for [Domain Offensive (do.de)](https://www.do.de/). - - - - -- Code: `dode` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DODE_TOKEN` | API token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DODE_HTTP_TIMEOUT` | API request timeout | -| `DODE_POLLING_INTERVAL` | Time between DNS propagation check | -| `DODE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DODE_SEQUENCE_INTERVAL` | Interval between iteration | -| `DODE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.do.de/wiki/LetsEncrypt_-_Entwickler) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dreamhost.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dreamhost.md deleted file mode 100644 index d185794..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dreamhost.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "DreamHost" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: dreamhost ---- - - - - - -Since: v1.1.0 - -Configuration for [DreamHost](https://www.dreamhost.com). - - - - -- Code: `dreamhost` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DREAMHOST_API_KEY` | The API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DREAMHOST_HTTP_TIMEOUT` | API request timeout | -| `DREAMHOST_POLLING_INTERVAL` | Time between DNS propagation check | -| `DREAMHOST_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DREAMHOST_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://help.dreamhost.com/hc/en-us/articles/217560167-API_overview) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_duckdns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_duckdns.md deleted file mode 100644 index b1c39ee..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_duckdns.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Duck DNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: duckdns ---- - - - - - -Since: v0.5.0 - -Configuration for [Duck DNS](https://www.duckdns.org/). - - - - -- Code: `duckdns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DUCKDNS_TOKEN` | Account token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DUCKDNS_HTTP_TIMEOUT` | API request timeout | -| `DUCKDNS_POLLING_INTERVAL` | Time between DNS propagation check | -| `DUCKDNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DUCKDNS_SEQUENCE_INTERVAL` | Interval between iteration | -| `DUCKDNS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.duckdns.org/spec.jsp) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dyn.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dyn.md deleted file mode 100644 index 7878ab4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_dyn.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Dyn" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: dyn ---- - - - - - -Since: v0.3.0 - -Configuration for [Dyn](https://dyn.com/). - - - - -- Code: `dyn` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `DYN_CUSTOMER_NAME` | Customer name | -| `DYN_PASSWORD` | Paswword | -| `DYN_USER_NAME` | User name | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `DYN_HTTP_TIMEOUT` | API request timeout | -| `DYN_POLLING_INTERVAL` | Time between DNS propagation check | -| `DYN_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `DYN_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://help.dyn.com/rest/) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_easydns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_easydns.md deleted file mode 100644 index 22f963c..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_easydns.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: "EasyDNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: easydns ---- - - - - - -Since: v2.6.0 - -Configuration for [EasyDNS](https://easydns.com/). - - - - -- Code: `easydns` - -Here is an example bash command using the EasyDNS provider: - -```bash -EASYDNS_TOKEN= \ -EASYDNS_KEY= \ -lego --dns easydns --domains my.domain.com --email my@email.com run -``` - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `EASYDNS_KEY` | API Key | -| `EASYDNS_TOKEN` | API Token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `EASYDNS_ENDPOINT` | The endpoint URL of the API Server | -| `EASYDNS_HTTP_TIMEOUT` | API request timeout | -| `EASYDNS_POLLING_INTERVAL` | Time between DNS propagation check | -| `EASYDNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `EASYDNS_SEQUENCE_INTERVAL` | Time between sequential requests | -| `EASYDNS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - -To test with the sandbox environment set ```EASYDNS_ENDPOINT=https://sandbox.rest.easydns.net``` - - - -## More information - -- [API documentation](http://docs.sandbox.rest.easydns.net) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_exec.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_exec.md deleted file mode 100644 index a893864..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_exec.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: "External program" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: exec ---- - - - - - -Since: v0.5.0 -Solving the DNS-01 challenge using an external program. - - - - -- Code: `exec` - -Here is an example bash command using the External program provider: - -```bash -EXEC_PATH=/the/path/to/myscript.sh \ -lego --dns exec --domains my.domain.com --email my@email.com run -``` - - - - - -## Base Configuration - -| Environment Variable Name | Description | -|---------------------------|---------------------------------------| -| `EXEC_MODE` | `RAW`, none | -| `EXEC_PATH` | The path of the the external program. | - - -## Additional Configuration - -| Environment Variable Name | Description | -|----------------------------|-------------------------------------------| -| `EXEC_POLLING_INTERVAL` | Time between DNS propagation check. | -| `EXEC_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation. | - - -## Description - -The file name of the external program is specified in the environment variable `EXEC_PATH`. - -When it is run by lego, three command-line parameters are passed to it: -The action ("present" or "cleanup"), the fully-qualified domain name and the value for the record. - -For example, requesting a certificate for the domain 'foo.example.com' can be achieved by calling lego as follows: - -```bash -EXEC_PATH=./update-dns.sh \ - lego --dns exec \ - --domains foo.example.com \ - --email invalid@example.com run -``` - -It will then call the program './update-dns.sh' with like this: - -```bash -./update-dns.sh "present" "_acme-challenge.foo.example.com." "MsijOYZxqyjGnFGwhjrhfg-Xgbl5r68WPda0J9EgqqI" -``` - -The program then needs to make sure the record is inserted. -When it returns an error via a non-zero exit code, lego aborts. - -When the record is to be removed again, -the program is called with the first command-line parameter set to `cleanup` instead of `present`. - -If you want to use the raw domain, token, and keyAuth values with your program, you can set `EXEC_MODE=RAW`: - -```bash -EXEC_MODE=RAW \ -EXEC_PATH=./update-dns.sh \ - lego --dns exec \ - --domains foo.example.com \ - --email invalid@example.com run -``` - -It will then call the program `./update-dns.sh` like this: - -```bash -./update-dns.sh "present" "foo.example.com." "--" "some-token" "KxAy-J3NwUmg9ZQuM-gP_Mq1nStaYSaP9tYQs5_-YsE.ksT-qywTd8058G-SHHWA3RAN72Pr0yWtPYmmY5UBpQ8" -``` - -## Commands - -{{% notice note %}} -The `--` is because the token MAY start with a `-`, and the called program may try and interpret a `-` as indicating a flag. -In the case of urfave, which is commonly used, -you can use the `--` delimiter to specify the start of positional arguments, and handle such a string safely. -{{% /notice %}} - -### Present - -| Mode | Command | -|---------|----------------------------------------------------| -| default | `myprogram present -- ` | -| `RAW` | `myprogram present -- ` | - -### Cleanup - -| Mode | Command | -|---------|----------------------------------------------------| -| default | `myprogram cleanup -- ` | -| `RAW` | `myprogram cleanup -- ` | - -### Timeout - -The command have to display propagation timeout and polling interval into Stdout. - -The values must be formatted as JSON, and times are in seconds. -Example: `{"timeout": 30, "interval": 5}` - -If an error occurs or if the command is not provided: -the default display propagation timeout and polling interval are used. - -| Mode | Command | -|---------|----------------------------------------------------| -| default | `myprogram timeout` | -| `RAW` | `myprogram timeout` | - - - - - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_exoscale.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_exoscale.md deleted file mode 100644 index c1108ec..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_exoscale.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "Exoscale" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: exoscale ---- - - - - - -Since: v0.4.0 - -Configuration for [Exoscale](https://www.exoscale.com/). - - - - -- Code: `exoscale` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `EXOSCALE_API_KEY` | API key | -| `EXOSCALE_API_SECRET` | API secret | -| `EXOSCALE_ENDPOINT` | API endpoint URL | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `EXOSCALE_HTTP_TIMEOUT` | API request timeout | -| `EXOSCALE_POLLING_INTERVAL` | Time between DNS propagation check | -| `EXOSCALE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `EXOSCALE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://community.exoscale.com/documentation/dns/api/) -- [Go client](https://github.com/exoscale/egoscale) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_fastdns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_fastdns.md deleted file mode 100644 index e0ed173..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_fastdns.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "FastDNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: fastdns ---- - - - - - -Since: v0.5.0 - -Configuration for [FastDNS](https://www.akamai.com/us/en/products/security/fast-dns.jsp). - - - - -- Code: `fastdns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `AKAMAI_ACCESS_TOKEN` | Access token | -| `AKAMAI_CLIENT_SECRET` | Client secret | -| `AKAMAI_CLIENT_TOKEN` | Client token | -| `AKAMAI_HOST` | API host | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `AKAMAI_POLLING_INTERVAL` | Time between DNS propagation check | -| `AKAMAI_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `AKAMAI_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developer.akamai.com/api/web_performance/fast_dns_record_management/v1.html) -- [Go client](https://github.com/akamai/AkamaiOPEN-edgegrid-golang) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gandi.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gandi.md deleted file mode 100644 index 9ff3b68..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gandi.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "Gandi" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: gandi ---- - - - - - -Since: v0.3.0 - -Configuration for [Gandi](https://www.gandi.net). - - - - -- Code: `gandi` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `GANDI_API_KEY` | API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `GANDI_HTTP_TIMEOUT` | API request timeout | -| `GANDI_POLLING_INTERVAL` | Time between DNS propagation check | -| `GANDI_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `GANDI_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](http://doc.rpc.gandi.net/index.html) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gandiv5.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gandiv5.md deleted file mode 100644 index bf390d5..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gandiv5.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "Gandi Live DNS (v5)" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: gandiv5 ---- - - - - - -Since: v0.5.0 - -Configuration for [Gandi Live DNS (v5)](https://www.gandi.net). - - - - -- Code: `gandiv5` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `GANDIV5_API_KEY` | API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `GANDIV5_HTTP_TIMEOUT` | API request timeout | -| `GANDIV5_POLLING_INTERVAL` | Time between DNS propagation check | -| `GANDIV5_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `GANDIV5_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](http://doc.livedns.gandi.net) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gcloud.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gcloud.md deleted file mode 100644 index 0c42b19..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_gcloud.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "Google Cloud" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: gcloud ---- - - - - - -Since: v0.3.0 - -Configuration for [Google Cloud](https://cloud.google.com). - - - - -- Code: `gcloud` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `Application Default Credentials` | [Documentation](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application) | -| `GCE_PROJECT` | Project name | -| `GCE_SERVICE_ACCOUNT` | Account | -| `GCE_SERVICE_ACCOUNT_FILE` | Account file path | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `GCE_POLLING_INTERVAL` | Time between DNS propagation check | -| `GCE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `GCE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://community.exoscale.com/documentation/dns/api/) -- [Go client](https://github.com/googleapis/google-api-go-client) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_glesys.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_glesys.md deleted file mode 100644 index 0e34ff4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_glesys.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Glesys" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: glesys ---- - - - - - -Since: v0.5.0 - -Configuration for [Glesys](https://glesys.com/). - - - - -- Code: `glesys` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `GLESYS_API_KEY` | API key | -| `GLESYS_API_USER` | API user | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `GLESYS_HTTP_TIMEOUT` | API request timeout | -| `GLESYS_POLLING_INTERVAL` | Time between DNS propagation check | -| `GLESYS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `GLESYS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://github.com/GleSYS/API/wiki/API-Documentation) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_godaddy.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_godaddy.md deleted file mode 100644 index a27f4ac..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_godaddy.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Go Daddy" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: godaddy ---- - - - - - -Since: v0.5.0 - -Configuration for [Go Daddy](https://godaddy.com). - - - - -- Code: `godaddy` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `GODADDY_API_KEY` | API key | -| `GODADDY_API_SECRET` | API secret | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `GODADDY_HTTP_TIMEOUT` | API request timeout | -| `GODADDY_POLLING_INTERVAL` | Time between DNS propagation check | -| `GODADDY_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `GODADDY_SEQUENCE_INTERVAL` | Interval between iteration | -| `GODADDY_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developer.godaddy.com/doc/endpoint/domains) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_hostingde.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_hostingde.md deleted file mode 100644 index a2596dd..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_hostingde.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Hosting.de" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: hostingde ---- - - - - - -Since: v1.1.0 - -Configuration for [Hosting.de](https://www.hosting.de/). - - - - -- Code: `hostingde` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `HOSTINGDE_API_KEY` | API key | -| `HOSTINGDE_ZONE_NAME` | Zone name in ACE format | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `HOSTINGDE_HTTP_TIMEOUT` | API request timeout | -| `HOSTINGDE_POLLING_INTERVAL` | Time between DNS propagation check | -| `HOSTINGDE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `HOSTINGDE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.hosting.de/api/#dns) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_httpreq.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_httpreq.md deleted file mode 100644 index 0896a43..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_httpreq.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: "HTTP request" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: httpreq ---- - - - - - -Since: v2.0.0 - -Configuration for [HTTP request](/dns/httpreq/). - - - - -- Code: `httpreq` - -Here is an example bash command using the HTTP request provider: - -```bash -HTTPREQ_ENDPOINT=http://my.server.com:9090 \ -lego --dns httpreq --domains my.domain.com --email my@email.com run -``` - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `HTTPREQ_ENDPOINT` | The URL of the server | -| `HTTPREQ_MODE` | `RAW`, none | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `HTTPREQ_HTTP_TIMEOUT` | API request timeout | -| `HTTPREQ_PASSWORD` | Basic authentication password | -| `HTTPREQ_POLLING_INTERVAL` | Time between DNS propagation check | -| `HTTPREQ_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `HTTPREQ_USERNAME` | Basic authentication username | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - -## Description - -The server must provide: - -- `POST` `/present` -- `POST` `/cleanup` - -The URL of the server must be define by `HTTPREQ_ENDPOINT`. - -### Mode - -There are 2 modes (`HTTPREQ_MODE`): - -- default mode: -```json -{ - "fqdn": "_acme-challenge.domain.", - "value": "LHDhK3oGRvkiefQnx7OOczTY5Tic_xZ6HcMOc_gmtoM" -} -``` - -- `RAW` -```json -{ - "domain": "domain", - "token": "token", - "keyAuth": "key" -} -``` - -### Authentication - -Basic authentication (optional) can be set with some environment variables: - -- `HTTPREQ_USERNAME` and `HTTPREQ_PASSWORD` -- both values must be set, otherwise basic authentication is not defined. - - - - - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_iij.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_iij.md deleted file mode 100644 index 108656d..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_iij.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Internet Initiative Japan" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: iij ---- - - - - - -Since: v1.1.0 - -Configuration for [Internet Initiative Japan](https://www.iij.ad.jp/en/). - - - - -- Code: `iij` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `IIJ_API_ACCESS_KEY` | API access key | -| `IIJ_API_SECRET_KEY` | API secret key | -| `IIJ_DO_SERVICE_CODE` | DO service code | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `IIJ_POLLING_INTERVAL` | Time between DNS propagation check | -| `IIJ_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `IIJ_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](http://manual.iij.jp/p2/pubapi/http://manual.iij.jp/p2/pubapi/) -- [Go client](https://github.com/iij/doapi) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_inwx.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_inwx.md deleted file mode 100644 index a8a43f2..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_inwx.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "INWX" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: inwx ---- - - - - - -Since: v2.0.0 - -Configuration for [INWX](https://www.inwx.de/en). - - - - -- Code: `inwx` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `INWX_PASSWORD` | Password | -| `INWX_USERNAME` | Username | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `INWX_POLLING_INTERVAL` | Time between DNS propagation check | -| `INWX_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `INWX_SANDBOX` | Activate the sandbox (boolean) | -| `INWX_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.inwx.de/en/help/apidoc) -- [Go client](https://github.com/nrdcg/goinwx) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_joker.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_joker.md deleted file mode 100644 index f41ffb5..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_joker.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "Joker" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: joker ---- - - - - - -Since: v2.6.0 - -Configuration for [Joker](https://joker.com). - - - - -- Code: `joker` - -Here is an example bash command using the Joker provider: - -```bash -JOKER_API_KEY= \ -lego --dns joker --domains my.domain.com --email my@email.com run -``` - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `JOKER_API_KEY` | API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `JOKER_HTTP_TIMEOUT` | API request timeout | -| `JOKER_POLLING_INTERVAL` | Time between DNS propagation check | -| `JOKER_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `JOKER_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://joker.com/faq/category/39/22-dmapi.html) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_lightsail.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_lightsail.md deleted file mode 100644 index 928f966..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_lightsail.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Amazon Lightsail" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: lightsail ---- - - - - - -Since: v0.5.0 - -Configuration for [Amazon Lightsail](https://aws.amazon.com/lightsail/). - - - - -- Code: `lightsail` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `AWS_ACCESS_KEY_ID` | Access key ID | -| `AWS_SECRET_ACCESS_KEY` | Secret access key | -| `DNS_ZONE` | DNS zone | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `LIGHTSAIL_POLLING_INTERVAL` | Time between DNS propagation check | -| `LIGHTSAIL_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - - -- [Go client](https://github.com/aws/aws-sdk-go/aws) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_linode.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_linode.md deleted file mode 100644 index fa790a5..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_linode.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "Linode (deprecated)" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: linode ---- - - - - - -Since: v0.4.0 - -Configuration for [Linode (deprecated)](https://www.linode.com/). - - - - -- Code: `linode` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `LINODE_API_KEY` | API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `LINODE_HTTP_TIMEOUT` | API request timeout | -| `LINODE_POLLING_INTERVAL` | Time between DNS propagation check | -| `LINODE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.linode.com/api/dns) -- [Go client](https://github.com/timewasted/linode) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_linodev4.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_linodev4.md deleted file mode 100644 index 7c8d652..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_linodev4.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: "Linode (v4)" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: linodev4 ---- - - - - - -Since: v1.1.0 - -Configuration for [Linode (v4)](https://www.linode.com/). - - - - -- Code: `linodev4` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `LINODE_TOKEN` | API token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `LINODE_HTTP_TIMEOUT` | API request timeout | -| `LINODE_POLLING_INTERVAL` | Time between DNS propagation check | -| `LINODE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developers.linode.com/api/v4) -- [Go client](https://github.com/linode/linodego) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_mydnsjp.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_mydnsjp.md deleted file mode 100644 index 365cd2f..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_mydnsjp.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "MyDNS.jp" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: mydnsjp ---- - - - - - -Since: v1.2.0 - -Configuration for [MyDNS.jp](https://www.mydns.jp). - - - - -- Code: `mydnsjp` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `MYDNSJP_MASTER_ID` | Master ID | -| `MYDNSJP_PASSWORD` | Password | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `MYDNSJP_HTTP_TIMEOUT` | API request timeout | -| `MYDNSJP_POLLING_INTERVAL` | Time between DNS propagation check | -| `MYDNSJP_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `MYDNSJP_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.mydns.jp/?MENU=030) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_namecheap.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_namecheap.md deleted file mode 100644 index 67c076b..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_namecheap.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Namecheap" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: namecheap ---- - - - - - -Since: v0.3.0 - -Configuration for [Namecheap](https://www.namecheap.com). - - - - -- Code: `namecheap` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `NAMECHEAP_API_KEY` | API key | -| `NAMECHEAP_API_USER` | API user | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `NAMECHEAP_HTTP_TIMEOUT` | API request timeout | -| `NAMECHEAP_POLLING_INTERVAL` | Time between DNS propagation check | -| `NAMECHEAP_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `NAMECHEAP_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.namecheap.com/support/api/methods.aspx) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_namedotcom.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_namedotcom.md deleted file mode 100644 index b4e480b..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_namedotcom.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Name.com" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: namedotcom ---- - - - - - -Since: v0.5.0 - -Configuration for [Name.com](https://www.name.com). - - - - -- Code: `namedotcom` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `NAMECOM_API_TOKEN` | API token | -| `NAMECOM_USERNAME` | Username | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `NAMECOM_HTTP_TIMEOUT` | API request timeout | -| `NAMECOM_POLLING_INTERVAL` | Time between DNS propagation check | -| `NAMECOM_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `NAMECOM_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.name.com/api-docs/DNS) -- [Go client](https://github.com/namedotcom/go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_netcup.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_netcup.md deleted file mode 100644 index bde8e38..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_netcup.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Netcup" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: netcup ---- - - - - - -Since: v1.1.0 - -Configuration for [Netcup](https://www.netcup.eu/). - - - - -- Code: `netcup` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `NETCUP_API_KEY` | API key | -| `NETCUP_API_PASSWORD` | API password | -| `NETCUP_CUSTOMER_NUMBER` | Customer number | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `NETCUP_HTTP_TIMEOUT` | API request timeout | -| `NETCUP_POLLING_INTERVAL` | Time between DNS propagation check | -| `NETCUP_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `NETCUP_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.netcup-wiki.de/wiki/DNS_API) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_nifcloud.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_nifcloud.md deleted file mode 100644 index d2ffeb2..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_nifcloud.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "NIFCloud" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: nifcloud ---- - - - - - -Since: v1.1.0 - -Configuration for [NIFCloud](https://www.nifcloud.com/). - - - - -- Code: `nifcloud` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `NIFCLOUD_ACCESS_KEY_ID` | Access key | -| `NIFCLOUD_SECRET_ACCESS_KEY` | Secret access key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `NIFCLOUD_HTTP_TIMEOUT` | API request timeout | -| `NIFCLOUD_POLLING_INTERVAL` | Time between DNS propagation check | -| `NIFCLOUD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `NIFCLOUD_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://mbaas.nifcloud.com/doc/current/rest/common/format.html) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_ns1.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_ns1.md deleted file mode 100644 index aecd2f0..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_ns1.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "NS1" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: ns1 ---- - - - - - -Since: v0.4.0 - -Configuration for [NS1](https://ns1.com). - - - - -- Code: `ns1` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `NS1_API_KEY` | API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `NS1_HTTP_TIMEOUT` | API request timeout | -| `NS1_POLLING_INTERVAL` | Time between DNS propagation check | -| `NS1_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `NS1_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://ns1.com/api) -- [Go client](https://github.com/ns1/ns1-go) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_oraclecloud.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_oraclecloud.md deleted file mode 100644 index 735b886..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_oraclecloud.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: "Oracle Cloud" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: oraclecloud ---- - - - - - -Since: v2.3.0 - -Configuration for [Oracle Cloud](https://cloud.oracle.com/home). - - - - -- Code: `oraclecloud` - -Here is an example bash command using the Oracle Cloud provider: - -```bash -OCI_PRIVKEY_FILE="~/.oci/oci_api_key.pem" \ -OCI_PRIVKEY_PASS="secret" \ -OCI_TENANCY_OCID="ocid1.tenancy.oc1..secret" \ -OCI_USER_OCID="ocid1.user.oc1..secret" \ -OCI_PUBKEY_FINGERPRINT="00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00" \ -OCI_REGION="us-phoenix-1" \ -OCI_COMPARTMENT_OCID="ocid1.tenancy.oc1..secret" \ -lego --dns oraclecloud --domains my.domain.com --email my@email.com run -``` - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `OCI_COMPARTMENT_OCID` | Compartment OCID | -| `OCI_PRIVKEY_FILE` | Private key file | -| `OCI_PRIVKEY_PASS` | Private key password | -| `OCI_PUBKEY_FINGERPRINT` | Public key fingerprint | -| `OCI_REGION` | Region | -| `OCI_TENANCY_OCID` | Tenanct OCID | -| `OCI_USER_OCID` | User OCID | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `OCI_POLLING_INTERVAL` | Time between DNS propagation check | -| `OCI_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `OCI_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://docs.cloud.oracle.com/iaas/Content/DNS/Concepts/dnszonemanagement.htm) -- [Go client](https://github.com/oracle/oci-go-sdk) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_otc.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_otc.md deleted file mode 100644 index bd04d26..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_otc.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: "Open Telekom Cloud" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: otc ---- - - - - - -Since: v0.4.1 - -Configuration for [Open Telekom Cloud](https://cloud.telekom.de/en). - - - - -- Code: `otc` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `OTC_DOMAIN_NAME` | Domain name | -| `OTC_IDENTITY_ENDPOINT` | Identity endpoint URL | -| `OTC_PASSWORD` | Password | -| `OTC_PROJECT_NAME` | Project name | -| `OTC_USER_NAME` | User name | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `OTC_HTTP_TIMEOUT` | API request timeout | -| `OTC_POLLING_INTERVAL` | Time between DNS propagation check | -| `OTC_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `OTC_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://docs.otc.t-systems.com/en-us/dns/index.html) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_ovh.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_ovh.md deleted file mode 100644 index e42413a..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_ovh.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: "OVH" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: ovh ---- - - - - - -Since: v0.4.0 - -Configuration for [OVH](https://www.ovh.com/). - - - - -- Code: `ovh` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `OVH_APPLICATION_KEY` | Application key | -| `OVH_APPLICATION_SECRET` | Application secret | -| `OVH_CONSUMER_KEY` | Consumer key | -| `OVH_ENDPOINT` | Endpoint URL (ovh-eu or ovh-ca) | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `OVH_HTTP_TIMEOUT` | API request timeout | -| `OVH_POLLING_INTERVAL` | Time between DNS propagation check | -| `OVH_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `OVH_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://eu.api.ovh.com/) -- [Go client](https://github.com/ovh/go-ovh) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_pdns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_pdns.md deleted file mode 100644 index f6a0a59..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_pdns.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: "PowerDNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: pdns ---- - - - - - -Since: v0.4.0 - -Configuration for [PowerDNS](https://www.powerdns.com/). - - - - -- Code: `pdns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `PDNS_API_KEY` | API key | -| `PDNS_API_URL` | API url | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `PDNS_HTTP_TIMEOUT` | API request timeout | -| `PDNS_POLLING_INTERVAL` | Time between DNS propagation check | -| `PDNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `PDNS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - -## Information - -Tested and confirmed to work with PowerDNS authoritative server 3.4.8 and 4.0.1. Refer to [PowerDNS documentation](https://doc.powerdns.com/md/httpapi/README/) instructions on how to enable the built-in API interface. - -PowerDNS Notes: -- PowerDNS API does not currently support SSL, therefore you should take care to ensure that traffic between lego and the PowerDNS API is over a trusted network, VPN etc. -- In order to have the SOA serial automatically increment each time the `_acme-challenge` record is added/modified via the API, set `SOA-EDIT-API` to `INCEPTION-INCREMENT` for the zone in the `domainmetadata` table - - - -## More information - -- [API documentation](https://doc.powerdns.com/md/httpapi/README/) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_rackspace.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_rackspace.md deleted file mode 100644 index dd0798b..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_rackspace.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Rackspace" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: rackspace ---- - - - - - -Since: v0.4.0 - -Configuration for [Rackspace](https://www.rackspace.com/). - - - - -- Code: `rackspace` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `RACKSPACE_API_KEY` | API key | -| `RACKSPACE_USER` | API user | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `RACKSPACE_HTTP_TIMEOUT` | API request timeout | -| `RACKSPACE_POLLING_INTERVAL` | Time between DNS propagation check | -| `RACKSPACE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `RACKSPACE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developer.rackspace.com/docs/cloud-dns/v1/) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_rfc2136.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_rfc2136.md deleted file mode 100644 index feaca62..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_rfc2136.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: "RFC2136" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: rfc2136 ---- - - - - - -Since: v0.3.0 - -Configuration for [RFC2136](https://tools.ietf.org/html/rfc2136). - - - - -- Code: `rfc2136` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `RFC2136_NAMESERVER` | Network address in the form "host" or "host:port" | -| `RFC2136_TSIG_ALGORITHM` | TSIG algorythm. See [miekg/dns#tsig.go](https://github.com/miekg/dns/blob/master/tsig.go) for supported values. To disable TSIG authentication, leave the `RFC2136_TSIG*` variables unset. | -| `RFC2136_TSIG_KEY` | Name of the secret key as defined in DNS server configuration. To disable TSIG authentication, leave the `RFC2136_TSIG*` variables unset. | -| `RFC2136_TSIG_SECRET` | Secret key payload. To disable TSIG authentication, leave the` RFC2136_TSIG*` variables unset. | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `RFC2136_DNS_TIMEOUT` | API request timeout | -| `RFC2136_POLLING_INTERVAL` | Time between DNS propagation check | -| `RFC2136_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `RFC2136_SEQUENCE_INTERVAL` | Interval between iteration | -| `RFC2136_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://tools.ietf.org/html/rfc2136) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_route53.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_route53.md deleted file mode 100644 index eb1f73f..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_route53.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: "Amazon Route 53" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: route53 ---- - - - - - -Since: v0.3.0 - -Configuration for [Amazon Route 53](https://aws.amazon.com/route53/). - - - - -- Code: `route53` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `AWS_ACCESS_KEY_ID` | Managed by the AWS client | -| `AWS_HOSTED_ZONE_ID` | Override the hosted zone ID | -| `AWS_REGION` | Managed by the AWS client | -| `AWS_SECRET_ACCESS_KEY` | Managed by the AWS client | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `AWS_MAX_RETRIES` | The number of maximum returns the service will use to make an individual API request | -| `AWS_POLLING_INTERVAL` | Time between DNS propagation check | -| `AWS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `AWS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - -## Description - -AWS Credentials are automatically detected in the following locations and prioritized in the following order: - -1. Environment variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, [`AWS_SESSION_TOKEN`] -2. Shared credentials file (defaults to `~/.aws/credentials`) -3. Amazon EC2 IAM role - -If `AWS_HOSTED_ZONE_ID` is not set, Lego tries to determine the correct public hosted zone via the FQDN. - -See also: [sessions](https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/sessions.html) - -## Policy - -The following AWS IAM policy document describes the permissions required for lego to complete the DNS challenge. - -```json -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "", - "Effect": "Allow", - "Action": [ - "route53:GetChange", - "route53:ChangeResourceRecordSets", - "route53:ListResourceRecordSets" - ], - "Resource": [ - "arn:aws:route53:::hostedzone/*", - "arn:aws:route53:::change/*" - ] - }, - { - "Sid": "", - "Effect": "Allow", - "Action": "route53:ListHostedZonesByName", - "Resource": "*" - } - ] -} -``` - - - - -## More information - -- [API documentation](https://docs.aws.amazon.com/Route53/latest/APIReference/API_Operations_Amazon_Route_53.html) -- [Go client](https://github.com/aws/aws-sdk-go/aws) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_sakuracloud.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_sakuracloud.md deleted file mode 100644 index 51f8cf9..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_sakuracloud.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Sakura Cloud" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: sakuracloud ---- - - - - - -Since: v1.1.0 - -Configuration for [Sakura Cloud](https://cloud.sakura.ad.jp/). - - - - -- Code: `sakuracloud` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `SAKURACLOUD_ACCESS_TOKEN` | Access token | -| `SAKURACLOUD_ACCESS_TOKEN_SECRET` | Access token secret | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `SAKURACLOUD_HTTP_TIMEOUT` | API request timeout | -| `SAKURACLOUD_POLLING_INTERVAL` | Time between DNS propagation check | -| `SAKURACLOUD_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `SAKURACLOUD_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developer.sakura.ad.jp/cloud/api/1.1/) -- [Go client](https://github.com/sacloud/libsacloud) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_selectel.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_selectel.md deleted file mode 100644 index 7972ca4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_selectel.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Selectel" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: selectel ---- - - - - - -Since: v1.2.0 - -Configuration for [Selectel](https://kb.selectel.com/). - - - - -- Code: `selectel` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `SELECTEL_API_TOKEN` | API token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `SELECTEL_BASE_URL` | API endpoint URL | -| `SELECTEL_HTTP_TIMEOUT` | API request timeout | -| `SELECTEL_POLLING_INTERVAL` | Time between DNS propagation check | -| `SELECTEL_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `SELECTEL_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://kb.selectel.com/23136054.html) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_stackpath.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_stackpath.md deleted file mode 100644 index 920d897..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_stackpath.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Stackpath" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: stackpath ---- - - - - - -Since: v1.1.0 - -Configuration for [Stackpath](https://www.stackpath.com/). - - - - -- Code: `stackpath` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `STACKPATH_CLIENT_ID` | Client ID | -| `STACKPATH_CLIENT_SECRET` | Client secret | -| `STACKPATH_STACK_ID` | Stack ID | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `STACKPATH_POLLING_INTERVAL` | Time between DNS propagation check | -| `STACKPATH_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `STACKPATH_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developer.stackpath.com/en/api/dns/#tag/Zone) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_transip.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_transip.md deleted file mode 100644 index 7cd2791..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_transip.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "TransIP" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: transip ---- - - - - - -Since: v2.0.0 - -Configuration for [TransIP](https://www.transip.nl/). - - - - -- Code: `transip` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `TRANSIP_ACCOUNT_NAME` | Account name | -| `TRANSIP_PRIVATE_KEY_PATH` | Private key path | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `TRANSIP_POLLING_INTERVAL` | Time between DNS propagation check | -| `TRANSIP_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `TRANSIP_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://api.transip.nl/docs/transip.nl/package-Transip.html) -- [Go client](https://github.com/transip/gotransip) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vegadns.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vegadns.md deleted file mode 100644 index b683cc7..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vegadns.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "VegaDNS" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: vegadns ---- - - - - - -Since: v1.1.0 - -Configuration for [VegaDNS](https://github.com/shupp/VegaDNS-API). - - - - -- Code: `vegadns` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `SECRET_VEGADNS_KEY` | API key | -| `SECRET_VEGADNS_SECRET` | API secret | -| `VEGADNS_URL` | API endpoint URL | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `VEGADNS_POLLING_INTERVAL` | Time between DNS propagation check | -| `VEGADNS_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `VEGADNS_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://github.com/shupp/VegaDNS-API) -- [Go client](https://github.com/OpenDNS/vegadns2client) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vscale.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vscale.md deleted file mode 100644 index 579c55f..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vscale.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Vscale" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: vscale ---- - - - - - -Since: v2.0.0 - -Configuration for [Vscale](https://vscale.io/). - - - - -- Code: `vscale` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `VSCALE_API_TOKEN` | API token | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `VSCALE_BASE_URL` | API enddpoint URL | -| `VSCALE_HTTP_TIMEOUT` | API request timeout | -| `VSCALE_POLLING_INTERVAL` | Time between DNS propagation check | -| `VSCALE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `VSCALE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://developers.vscale.io/documentation/api/v1/#api-Domains_Records) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vultr.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vultr.md deleted file mode 100644 index f458a56..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_vultr.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Vultr" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: vultr ---- - - - - - -Since: v0.3.1 - -Configuration for [Vultr](https://www.vultr.com/). - - - - -- Code: `vultr` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `VULTR_API_KEY` | API key | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `VULTR_HTTP_TIMEOUT` | API request timeout | -| `VULTR_POLLING_INTERVAL` | Time between DNS propagation check | -| `VULTR_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `VULTR_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://www.vultr.com/api/#dns) -- [Go client](https://github.com/JamesClonk/vultr) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_zoneee.md b/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_zoneee.md deleted file mode 100644 index f145645..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/dns/zz_gen_zoneee.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Zone.ee" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: zoneee ---- - - - - - -Since: v2.1.0 - -Configuration for [Zone.ee](https://www.zone.ee/). - - - - -- Code: `zoneee` - -{{% notice note %}} -_Please contribute by adding a CLI example._ -{{% /notice %}} - - - - -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -| `ZONEEE_API_KEY` | API key | -| `ZONEEE_API_USER` | API user | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -| `ZONEEE_ENDPOINT` | API endpoint URL | -| `ZONEEE_HTTP_TIMEOUT` | API request timeout | -| `ZONEEE_POLLING_INTERVAL` | Time between DNS propagation check | -| `ZONEEE_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation | -| `ZONEEE_TTL` | The TTL of the TXT record used for the DNS challenge | - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). - - - - -## More information - -- [API documentation](https://api.zone.eu/v2) - - - - diff --git a/vendor/github.com/go-acme/lego/docs/content/installation/_index.md b/vendor/github.com/go-acme/lego/docs/content/installation/_index.md deleted file mode 100644 index cbf9426..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/installation/_index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: "Installation" -date: 2019-03-03T16:39:46+01:00 -weight: 1 -draft: false ---- - -## Binaries - -To get the binary just download the latest release for your OS/Arch from [the release page](https://github.com/go-acme/lego/releases) and put the binary somewhere convenient. -lego does not assume anything about the location you run it from. - -## From Docker - -```bash -docker run goacme/lego -h -``` - -## From package managers - -- [ArchLinux (AUR)](https://aur.archlinux.org/packages/lego): - -```bash -yay -S lego -``` - -**Note**: only the package manager for Arch Linux is officially supported by the lego team. - -## From sources - -To install from sources, just run: - -```bash -go get -u github.com/go-acme/lego/cmd/lego -``` diff --git a/vendor/github.com/go-acme/lego/docs/content/usage/_index.md b/vendor/github.com/go-acme/lego/docs/content/usage/_index.md deleted file mode 100644 index 7a4b3f4..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/usage/_index.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: "Usage" -date: 2019-03-03T16:39:46+01:00 -draft: false -weight: 2 ---- - -{{%children style="h2" description="true" %}} diff --git a/vendor/github.com/go-acme/lego/docs/content/usage/cli/_index.md b/vendor/github.com/go-acme/lego/docs/content/usage/cli/_index.md deleted file mode 100644 index 11174d6..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/usage/cli/_index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: "CLI" -date: 2019-03-03T16:39:46+01:00 -draft: false ---- - -Lego can be use as a CLI. - - - -## Usage - -{{%expand "CLI help" %}} -```slim -NAME: - lego - Let's Encrypt client written in Go - -USAGE: - lego [global options] command [command options] [arguments...] - -COMMANDS: - run Register an account, then create and install a certificate - revoke Revoke a certificate - renew Renew a certificate - dnshelp Shows additional help for the '--dns' global option - list Display certificates and accounts information. - help, h Shows a list of commands or help for one command - -GLOBAL OPTIONS: - --domains value, -d value Add a domain to the process. Can be specified multiple times. - --server value, -s value CA hostname (and optionally :port). The server certificate must be trusted in order to avoid further modifications to the client. (default: "https://acme-v02.api.letsencrypt.org/directory") - --accept-tos, -a By setting this flag to true you indicate that you accept the current Let's Encrypt terms of service. - --email value, -m value Email used for registration and recovery contact. - --csr value, -c value Certificate signing request filename, if an external CSR is to be used. - --eab Use External Account Binding for account registration. Requires --kid and --hmac. - --kid value Key identifier from External CA. Used for External Account Binding. - --hmac value MAC key from External CA. Should be in Base64 URL Encoding without padding format. Used for External Account Binding. - --key-type value, -k value Key type to use for private keys. Supported: rsa2048, rsa4096, rsa8192, ec256, ec384. (default: "ec384") - --filename value (deprecated) Filename of the generated certificate. - --path value Directory to use for storing the data. (default: "./.lego") - --http Use the HTTP challenge to solve challenges. Can be mixed with other types of challenges. - --http.port value Set the port and interface to use for HTTP based challenges to listen on.Supported: interface:port or :port. (default: ":80") - --http.webroot value Set the webroot folder to use for HTTP based challenges to write directly in a file in .well-known/acme-challenge. - --http.memcached-host value Set the memcached host(s) to use for HTTP based challenges. Challenges will be written to all specified hosts. - --tls Use the TLS challenge to solve challenges. Can be mixed with other types of challenges. - --tls.port value Set the port and interface to use for TLS based challenges to listen on. Supported: interface:port or :port. (default: ":443") - --dns value Solve a DNS challenge using the specified provider. Can be mixed with other types of challenges. Run 'lego dnshelp' for help on usage. - --dns.disable-cp By setting this flag to true, disables the need to wait the propagation of the TXT record to all authoritative name servers. - --dns.resolvers value Set the resolvers to use for performing recursive DNS queries. Supported: host:port. The default is to use the system resolvers, or Google's DNS resolvers if the system's cannot be determined. - --http-timeout value Set the HTTP timeout value to a specific value in seconds. (default: 0) - --dns-timeout value Set the DNS timeout value to a specific value in seconds. Used only when performing authoritative name servers queries. (default: 10) - --pem Generate a .pem file by concatenating the .key and .crt files together. - --cert.timeout value Set the certificate timeout value to a specific value in seconds. Only used when obtaining certificates. (default: 30) - --help, -h show help - --version, -v print the version -``` -{{% /expand%}} - - -When using the standard `--path` option, all certificates and account configurations are saved to a folder `.lego` in the current working directory. - - -## Let's Encrypt ACME server - -lego defaults to communicating with the production Let's Encrypt ACME server. -If you'd like to test something without issuing real certificates, consider using the staging endpoint instead: - -```bash -lego --server=https://acme-staging-v02.api.letsencrypt.org/directory … -``` - -## Sudo - -The CLI does not require root permissions but needs to bind to port 80 and 443 for certain challenges. -To run the CLI without sudo, you have four options: - -- Use setcap 'cap_net_bind_service=+ep' /path/to/program -- Pass the `--http.port` or/and the `--tls.port` option and specify a custom port to bind to. In this case you have to forward port 80/443 to these custom ports (see [Port Usage](usage/cli#port-usage)). -- Pass the `--http.webroot` option and specify the path to your webroot folder. In this case the challenge will be written in a file in `.well-known/acme-challenge/` inside your webroot. -- Pass the `--dns` option and specify a DNS provider. - -## Port Usage - -By default lego assumes it is able to bind to ports 80 and 443 to solve challenges. -If this is not possible in your environment, you can use the `--http.port` and `--tls.port` options to instruct -lego to listen on that interface:port for any incoming challenges. - -If you are using this option, make sure you proxy all of the following traffic to these ports. - -**HTTP Port:** All plaintext HTTP requests to port **80** which begin with a request path of `/.well-known/acme-challenge/` for the HTTP challenge. - -**TLS Port:** All TLS handshakes on port **443** for the TLS-ALPN challenge. - -This traffic redirection is only needed as long as lego solves challenges. As soon as you have received your certificates you can deactivate the forwarding. diff --git a/vendor/github.com/go-acme/lego/docs/content/usage/cli/examples.md b/vendor/github.com/go-acme/lego/docs/content/usage/cli/examples.md deleted file mode 100644 index 46e7065..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/usage/cli/examples.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: "Examples" -date: 2019-03-03T16:39:46+01:00 -draft: false ---- - -## CLI Examples - -Assumes the `lego` binary has permission to bind to ports 80 and 443. -You can get a pre-built binary from the [releases](https://github.com/go-acme/lego/releases) page. -If your environment does not allow you to bind to these ports, please read [Port Usage](usage/cli#port-usage). - -### Obtain a certificate - -```bash -lego --email="foo@bar.com" --domains="example.com" --http run -``` - -(Find your certificate in the `.lego` folder of current working directory.) - -### To renew the certificate - -```bash -lego --email="foo@bar.com" --domains="example.com" --http renew -``` - -### To renew the certificate only if it expires within 45 days - -```bash -lego --email="foo@bar.com" --domains="example.com" --http renew --days 45 -``` - -### To renew the certificate (and hook) - -The hook is executed only when the certificates are effectively renewed. - -```bash -lego --email="foo@bar.com" --domains="example.com" --http renew --renew-hook="./myscript.sh" -``` - -### Obtain a certificate using the DNS challenge - -```bash -AWS_REGION=us-east-1 \ -AWS_ACCESS_KEY_ID=my_id \ -AWS_SECRET_ACCESS_KEY=my_key \ -lego --email="foo@bar.com" --domains="example.com" --dns="route53" run -``` - -### Obtain a certificate given a certificate signing request (CSR) generated by something else - -```bash -lego --email="foo@bar.com" --http --csr=/path/to/csr.pem run -``` - -(lego will infer the domains to be validated based on the contents of the CSR, so make sure the CSR's Common Name and optional SubjectAltNames are set correctly.) diff --git a/vendor/github.com/go-acme/lego/docs/content/usage/library/Writing-a-Challenge-Solver.md b/vendor/github.com/go-acme/lego/docs/content/usage/library/Writing-a-Challenge-Solver.md deleted file mode 100644 index 79e6209..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/usage/library/Writing-a-Challenge-Solver.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: "Writing a Challenge Solver" -date: 2019-03-03T16:39:46+01:00 -draft: false ---- - -Lego can solve multiple ACME challenge types out of the box, but sometimes you have custom requirements. - - - -For example, you may want to write a solver for the DNS-01 challenge that works with a different DNS provider (lego already supports CloudFlare, AWS, DigitalOcean, and others). - -The DNS-01 challenge is advantageous when other challenge types are impossible. -For example, the HTTP-01 challenge doesn't work well behind a load balancer or CDN and the TLS-ALPN-01 challenge breaks behind TLS termination. - -But even if using HTTP-01 or TLS-ALPN-01 challenges, you may have specific needs that lego does not consider by default. - -You can write something called a `challenge.Provider` that implements [this interface](https://godoc.org/github.com/go-acme/lego/challenge#Provider): - -```go -type Provider interface { - Present(domain, token, keyAuth string) error - CleanUp(domain, token, keyAuth string) error -} -``` - -This provides the means to solve a challenge. -First you present a token to the ACME server in a way defined by the challenge type you're solving for, then you "clean up" after the challenge finishes. - -## Writing a challenge.Provider - -Pretend we want to write our own DNS-01 challenge provider (other challenge types have different requirements but the same principles apply). - -This will let us prove ownership of domain names parked at a new, imaginary DNS service called BestDNS without having to start our own HTTP server. -BestDNS has an API that, given an authentication token, allows us to manipulate DNS records. - -This simplistic example has only one field to store the auth token, but in reality you may need to keep more state. - -```go -type DNSProviderBestDNS struct { - apiAuthToken string -} -``` - -We should provide a constructor that returns a *pointer* to the `struct`. -This is important in case we need to maintain state in the `struct`. - -```go -func NewDNSProviderBestDNS(apiAuthToken string) (*DNSProviderBestDNS, error) { - return &DNSProviderBestDNS{apiAuthToken: apiAuthToken}, nil -} -``` - -Now we need to implement the interface. -We'll start with the `Present` method. -You'll be passed the `domain` name for which you're proving ownership, a `token`, and a `keyAuth` string. -How your provider uses `token` and `keyAuth`, or if you even use them at all, depends on the challenge type. -For DNS-01, we'll just use `domain` and `keyAuth`. - -```go -func (d *DNSProviderBestDNS) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - // make API request to set a TXT record on fqdn with value and ttl - return nil -} -``` - -After calling `dns01.GetRecord(domain, keyAuth)`, we now have the information we need to make our API request and set the TXT record: -- `fqdn` is the fully qualified domain name on which to set the TXT record. -- `value` is the record's value to set on the record. - -So then you make an API request to the DNS service according to their docs. -Once the TXT record is set on the domain, you may return and the challenge will proceed. - -The ACME server will then verify that you did what it required you to do, and once it is finished, lego will call your `CleanUp` method. -In our case, we want to remove the TXT record we just created. - -```go -func (d *DNSProviderBestDNS) CleanUp(domain, token, keyAuth string) error { - // clean up any state you created in Present, like removing the TXT record -} -``` - -In our case, we'd just make another API request to have the DNS record deleted; no need to keep it and clutter the zone file. - -## Using your new challenge.Provider - -To use your new challenge provider, call [`client.Challenge.SetDNS01Provider`](https://godoc.org/github.com/go-acme/lego/challenge/resolver#SolverManager.SetDNS01Provider) to tell lego, "For this challenge, use this provider". -In our case: - -```go -bestDNS, err := NewDNSProviderBestDNS("my-auth-token") -if err != nil { - return err -} - -client.Challenge.SetDNS01Provider(bestDNS) -``` - -Then, when this client tries to solve the DNS-01 challenge, it will use our new provider, which sets TXT records on a domain name hosted by BestDNS. - -That's really all there is to it. -Go make awesome things! diff --git a/vendor/github.com/go-acme/lego/docs/content/usage/library/_index.md b/vendor/github.com/go-acme/lego/docs/content/usage/library/_index.md deleted file mode 100644 index 06e1caa..0000000 --- a/vendor/github.com/go-acme/lego/docs/content/usage/library/_index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: "Library" -date: 2019-03-03T16:39:46+01:00 -draft: false ---- - -Lego can be use as a Go Library. - - - -## GoDoc - -The GoDoc can be found here: [GoDoc](https://godoc.org/github.com/go-acme/lego/acme) - -## Usage - -A valid, but bare-bones example use of the acme package: - -```go -package main - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "fmt" - "log" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge/http01" - "github.com/go-acme/lego/challenge/tlsalpn01" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/registration" -) - -// You'll need a user or account type that implements acme.User -type MyUser struct { - Email string - Registration *registration.Resource - key crypto.PrivateKey -} - -func (u *MyUser) GetEmail() string { - return u.Email -} -func (u MyUser) GetRegistration() *registration.Resource { - return u.Registration -} -func (u *MyUser) GetPrivateKey() crypto.PrivateKey { - return u.key -} - -func main() { - - // Create a user. New accounts need an email and private key to start. - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - log.Fatal(err) - } - - myUser := MyUser{ - Email: "you@yours.com", - key: privateKey, - } - - config := lego.NewConfig(&myUser) - - // This CA URL is configured for a local dev instance of Boulder running in Docker in a VM. - config.CADirURL = "http://192.168.99.100:4000/directory" - config.Certificate.KeyType = certcrypto.RSA2048 - - // A client facilitates communication with the CA server. - client, err := lego.NewClient(config) - if err != nil { - log.Fatal(err) - } - - // We specify an http port of 5002 and an tls port of 5001 on all interfaces - // because we aren't running as root and can't bind a listener to port 80 and 443 - // (used later when we attempt to pass challenges). Keep in mind that you still - // need to proxy challenge traffic to port 5002 and 5001. - err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "5002")) - if err != nil { - log.Fatal(err) - } - err = client.Challenge.SetTLSALPN01Provider(tlsalpn01.NewProviderServer("", "5001")) - if err != nil { - log.Fatal(err) - } - - // New users will need to register - reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) - if err != nil { - log.Fatal(err) - } - myUser.Registration = reg - - request := certificate.ObtainRequest{ - Domains: []string{"mydomain.com"}, - Bundle: true, - } - certificates, err := client.Certificate.Obtain(request) - if err != nil { - log.Fatal(err) - } - - // Each certificate comes back with the cert bytes, the bytes of the client's - // private key, and a certificate URL. SAVE THESE TO DISK. - fmt.Printf("%#v\n", certificates) - - // ... all done. -} -``` diff --git a/vendor/github.com/go-acme/lego/docs/layouts/partials/logo.html b/vendor/github.com/go-acme/lego/docs/layouts/partials/logo.html deleted file mode 100644 index f91d1dd..0000000 --- a/vendor/github.com/go-acme/lego/docs/layouts/partials/logo.html +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/github.com/go-acme/lego/docs/static/images/logo-white.png b/vendor/github.com/go-acme/lego/docs/static/images/logo-white.png deleted file mode 100644 index 598c5da..0000000 Binary files a/vendor/github.com/go-acme/lego/docs/static/images/logo-white.png and /dev/null differ diff --git a/vendor/github.com/go-acme/lego/docs/static/images/logo.png b/vendor/github.com/go-acme/lego/docs/static/images/logo.png deleted file mode 100644 index bee263a..0000000 Binary files a/vendor/github.com/go-acme/lego/docs/static/images/logo.png and /dev/null differ diff --git a/vendor/github.com/go-acme/lego/e2e/challenges_test.go b/vendor/github.com/go-acme/lego/e2e/challenges_test.go deleted file mode 100644 index 0ca098e..0000000 --- a/vendor/github.com/go-acme/lego/e2e/challenges_test.go +++ /dev/null @@ -1,326 +0,0 @@ -package e2e - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "fmt" - "io/ioutil" - "os" - "testing" - - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge/http01" - "github.com/go-acme/lego/challenge/tlsalpn01" - "github.com/go-acme/lego/e2e/loader" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/registration" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var load = loader.EnvLoader{ - PebbleOptions: &loader.CmdOption{ - HealthCheckURL: "https://localhost:14000/dir", - Args: []string{"-strict", "-config", "fixtures/pebble-config.json"}, - Env: []string{"PEBBLE_VA_NOSLEEP=1", "PEBBLE_WFE_NONCEREJECT=20"}, - }, - LegoOptions: []string{ - "LEGO_CA_CERTIFICATES=./fixtures/certs/pebble.minica.pem", - }, -} - -func TestMain(m *testing.M) { - os.Exit(load.MainTest(m)) -} - -func TestHelp(t *testing.T) { - output, err := load.RunLego("-h") - if err != nil { - fmt.Fprintf(os.Stderr, "%s\n", output) - t.Fatal(err) - } - - fmt.Fprintf(os.Stdout, "%s\n", output) -} - -func TestChallengeHTTP_Run(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-d", "acme.wtf", - "--http", - "--http.port", ":5002", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeTLS_Run_Domains(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-d", "acme.wtf", - "--tls", - "--tls.port", ":5001", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeTLS_Run_CSR(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-csr", "./fixtures/csr.raw", - "--tls", - "--tls.port", ":5001", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeTLS_Run_CSR_PEM(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-csr", "./fixtures/csr.cert", - "--tls", - "--tls.port", ":5001", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeTLS_Run_Revoke(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-d", "lego.wtf", - "-d", "acme.lego.wtf", - "--tls", - "--tls.port", ":5001", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } - - output, err = load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-d", "lego.wtf", - "--tls", - "--tls.port", ":5001", - "revoke") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeTLS_Run_Revoke_Non_ASCII(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-d", "légô.wtf", - "--tls", - "--tls.port", ":5001", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } - - output, err = load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "-s", "https://localhost:14000/dir", - "-d", "légô.wtf", - "--tls", - "--tls.port", ":5001", - "revoke") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeHTTP_Client_Obtain(t *testing.T) { - err := os.Setenv("LEGO_CA_CERTIFICATES", "./fixtures/certs/pebble.minica.pem") - require.NoError(t, err) - defer func() { _ = os.Unsetenv("LEGO_CA_CERTIFICATES") }() - - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - user := &fakeUser{privateKey: privateKey} - config := lego.NewConfig(user) - config.CADirURL = load.PebbleOptions.HealthCheckURL - - client, err := lego.NewClient(config) - require.NoError(t, err) - - err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "5002")) - require.NoError(t, err) - - reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) - require.NoError(t, err) - user.registration = reg - - request := certificate.ObtainRequest{ - Domains: []string{"acme.wtf"}, - Bundle: true, - } - resource, err := client.Certificate.Obtain(request) - require.NoError(t, err) - - require.NotNil(t, resource) - assert.Equal(t, "acme.wtf", resource.Domain) - assert.Regexp(t, `https://localhost:14000/certZ/[\w\d]{14,}`, resource.CertURL) - assert.Regexp(t, `https://localhost:14000/certZ/[\w\d]{14,}`, resource.CertStableURL) - assert.NotEmpty(t, resource.Certificate) - assert.NotEmpty(t, resource.IssuerCertificate) - assert.Empty(t, resource.CSR) -} - -func TestChallengeTLS_Client_Obtain(t *testing.T) { - err := os.Setenv("LEGO_CA_CERTIFICATES", "./fixtures/certs/pebble.minica.pem") - require.NoError(t, err) - defer func() { _ = os.Unsetenv("LEGO_CA_CERTIFICATES") }() - - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - user := &fakeUser{privateKey: privateKey} - config := lego.NewConfig(user) - config.CADirURL = load.PebbleOptions.HealthCheckURL - - client, err := lego.NewClient(config) - require.NoError(t, err) - - err = client.Challenge.SetTLSALPN01Provider(tlsalpn01.NewProviderServer("", "5001")) - require.NoError(t, err) - - reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) - require.NoError(t, err) - user.registration = reg - - request := certificate.ObtainRequest{ - Domains: []string{"acme.wtf"}, - Bundle: true, - PrivateKey: privateKey, - } - resource, err := client.Certificate.Obtain(request) - require.NoError(t, err) - - require.NotNil(t, resource) - assert.Equal(t, "acme.wtf", resource.Domain) - assert.Regexp(t, `https://localhost:14000/certZ/[\w\d]{14,}`, resource.CertURL) - assert.Regexp(t, `https://localhost:14000/certZ/[\w\d]{14,}`, resource.CertStableURL) - assert.NotEmpty(t, resource.Certificate) - assert.NotEmpty(t, resource.IssuerCertificate) - assert.Empty(t, resource.CSR) -} - -func TestChallengeTLS_Client_ObtainForCSR(t *testing.T) { - err := os.Setenv("LEGO_CA_CERTIFICATES", "./fixtures/certs/pebble.minica.pem") - require.NoError(t, err) - defer func() { _ = os.Unsetenv("LEGO_CA_CERTIFICATES") }() - - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - user := &fakeUser{privateKey: privateKey} - config := lego.NewConfig(user) - config.CADirURL = load.PebbleOptions.HealthCheckURL - - client, err := lego.NewClient(config) - require.NoError(t, err) - - err = client.Challenge.SetTLSALPN01Provider(tlsalpn01.NewProviderServer("", "5001")) - require.NoError(t, err) - - reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) - require.NoError(t, err) - user.registration = reg - - csrRaw, err := ioutil.ReadFile("./fixtures/csr.raw") - require.NoError(t, err) - - csr, err := x509.ParseCertificateRequest(csrRaw) - require.NoError(t, err) - - resource, err := client.Certificate.ObtainForCSR(*csr, true) - require.NoError(t, err) - - require.NotNil(t, resource) - assert.Equal(t, "acme.wtf", resource.Domain) - assert.Regexp(t, `https://localhost:14000/certZ/[\w\d]{14,}`, resource.CertURL) - assert.Regexp(t, `https://localhost:14000/certZ/[\w\d]{14,}`, resource.CertStableURL) - assert.NotEmpty(t, resource.Certificate) - assert.NotEmpty(t, resource.IssuerCertificate) - assert.NotEmpty(t, resource.CSR) -} - -type fakeUser struct { - email string - privateKey crypto.PrivateKey - registration *registration.Resource -} - -func (f *fakeUser) GetEmail() string { return f.email } -func (f *fakeUser) GetRegistration() *registration.Resource { return f.registration } -func (f *fakeUser) GetPrivateKey() crypto.PrivateKey { return f.privateKey } diff --git a/vendor/github.com/go-acme/lego/e2e/dnschallenge/dns_challenges_test.go b/vendor/github.com/go-acme/lego/e2e/dnschallenge/dns_challenges_test.go deleted file mode 100644 index ddeb380..0000000 --- a/vendor/github.com/go-acme/lego/e2e/dnschallenge/dns_challenges_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package dnschallenge - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "fmt" - "os" - "testing" - - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/e2e/loader" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/providers/dns" - "github.com/go-acme/lego/registration" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var load = loader.EnvLoader{ - PebbleOptions: &loader.CmdOption{ - HealthCheckURL: "https://localhost:15000/dir", - Args: []string{"-strict", "-config", "fixtures/pebble-config-dns.json", "-dnsserver", "localhost:8053"}, - Env: []string{"PEBBLE_VA_NOSLEEP=1", "PEBBLE_WFE_NONCEREJECT=20"}, - Dir: "../", - }, - LegoOptions: []string{ - "LEGO_CA_CERTIFICATES=../fixtures/certs/pebble.minica.pem", - "EXEC_PATH=../fixtures/update-dns.sh", - }, - ChallSrv: &loader.CmdOption{ - Args: []string{"-http01", ":5012", "-tlsalpn01", ":5011"}, - }, -} - -func TestMain(m *testing.M) { - os.Exit(load.MainTest(m)) -} - -func TestDNSHelp(t *testing.T) { - output, err := load.RunLego("dnshelp") - if err != nil { - fmt.Fprintf(os.Stderr, "%s\n", output) - t.Fatal(err) - } - - fmt.Fprintf(os.Stdout, "%s\n", output) -} - -func TestChallengeDNS_Run(t *testing.T) { - loader.CleanLegoFiles() - - output, err := load.RunLego( - "-m", "hubert@hubert.com", - "--accept-tos", - "--dns", "exec", - "--dns.resolvers", ":8053", - "--dns.disable-cp", - "-s", "https://localhost:15000/dir", - "-d", "*.légo.acme", - "-d", "légo.acme", - "run") - - if len(output) > 0 { - fmt.Fprintf(os.Stdout, "%s\n", output) - } - if err != nil { - t.Fatal(err) - } -} - -func TestChallengeDNS_Client_Obtain(t *testing.T) { - err := os.Setenv("LEGO_CA_CERTIFICATES", "../fixtures/certs/pebble.minica.pem") - require.NoError(t, err) - defer func() { _ = os.Unsetenv("LEGO_CA_CERTIFICATES") }() - - err = os.Setenv("EXEC_PATH", "../fixtures/update-dns.sh") - require.NoError(t, err) - defer func() { _ = os.Unsetenv("EXEC_PATH") }() - - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - require.NoError(t, err, "Could not generate test key") - - user := &fakeUser{privateKey: privateKey} - config := lego.NewConfig(user) - config.CADirURL = "https://localhost:15000/dir" - - client, err := lego.NewClient(config) - require.NoError(t, err) - - provider, err := dns.NewDNSChallengeProviderByName("exec") - require.NoError(t, err) - - err = client.Challenge.SetDNS01Provider(provider, - dns01.AddRecursiveNameservers([]string{":8053"}), - dns01.DisableCompletePropagationRequirement()) - require.NoError(t, err) - - reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) - require.NoError(t, err) - user.registration = reg - - domains := []string{"*.légo.acme", "légo.acme"} - - request := certificate.ObtainRequest{ - Domains: domains, - Bundle: true, - PrivateKey: privateKey, - } - resource, err := client.Certificate.Obtain(request) - require.NoError(t, err) - - require.NotNil(t, resource) - assert.Equal(t, "*.xn--lgo-bma.acme", resource.Domain) - assert.Regexp(t, `https://localhost:15000/certZ/[\w\d]{14,}`, resource.CertURL) - assert.Regexp(t, `https://localhost:15000/certZ/[\w\d]{14,}`, resource.CertStableURL) - assert.NotEmpty(t, resource.Certificate) - assert.NotEmpty(t, resource.IssuerCertificate) - assert.Empty(t, resource.CSR) -} - -type fakeUser struct { - email string - privateKey crypto.PrivateKey - registration *registration.Resource -} - -func (f *fakeUser) GetEmail() string { return f.email } -func (f *fakeUser) GetRegistration() *registration.Resource { return f.registration } -func (f *fakeUser) GetPrivateKey() crypto.PrivateKey { return f.privateKey } diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/README.md b/vendor/github.com/go-acme/lego/e2e/fixtures/certs/README.md deleted file mode 100644 index 7cde76f..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# certs/ - -This directory contains a CA certificate (`pebble.minica.pem`) and a private key -(`pebble.minica.key.pem`) that are used to issue a end-entity certificate (See -`certs/localhost`) for the Pebble HTTPS server. - -To get your **testing code** to use Pebble without HTTPS errors you should -configure your ACME client to trust the `pebble.minica.pem` CA certificate. Your -ACME client should offer a runtime option to specify a list of root CAs that you -can configure to include the `pebble.minica.pem` file. - -**Do not** add this CA certificate to the system trust store or in production -code!!! The CA's private key is **public** and anyone can use it to issue -certificates that will be trusted by a system with the Pebble CA in the trust -store. - -To re-create all of the Pebble certificates run: - - minica -ca-cert pebble.minica.pem \ - -ca-key pebble.minica.key.pem \ - -domains localhost,pebble \ - -ip-addresses 127.0.0.1 - -From the `test/certs/` directory after [installing -MiniCA](https://github.com/jsha/minica#installation) diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/README.md b/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/README.md deleted file mode 100644 index efa49ae..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# certs/localhost - -This directory contains an end-entity (leaf) certificate (`cert.pem`) and -a private key (`key.pem`) for the Pebble HTTPS server. It includes `127.0.0.1` -as an IP address SAN, and `[localhost, pebble]` as DNS SANs. diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/cert.pem b/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/cert.pem deleted file mode 100644 index 2866a2b..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/cert.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDGzCCAgOgAwIBAgIIbEfayDFsBtwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE -AxMVbWluaWNhIHJvb3QgY2EgMjRlMmRiMCAXDTE3MTIwNjE5NDIxMFoYDzIxMDcx -MjA2MTk0MjEwWjAUMRIwEAYDVQQDEwlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQCbFMW3DXXdErvQf2lCZ0qz0DGEWadDoF0O2neM5mVa -VQ7QGW0xc5Qwvn3Tl62C0JtwLpF0pG2BICIN+DHdVaIUwkf77iBS2doH1I3waE1I -8GkV9JrYmFY+j0dA1SwBmqUZNXhLNwZGq1a91nFSI59DZNy/JciqxoPX2K++ojU2 -FPpuXe2t51NmXMsszpa+TDqF/IeskA9A/ws6UIh4Mzhghx7oay2/qqj2IIPjAmJj -i73kdUvtEry3wmlkBvtVH50+FscS9WmPC5h3lDTk5nbzSAXKuFusotuqy3XTgY5B -PiRAwkZbEY43JNfqenQPHo7mNTt29i+NVVrBsnAa5ovrAgMBAAGjYzBhMA4GA1Ud -DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0T -AQH/BAIwADAiBgNVHREEGzAZgglsb2NhbGhvc3SCBnBlYmJsZYcEfwAAATANBgkq -hkiG9w0BAQsFAAOCAQEAYIkXff8H28KS0KyLHtbbSOGU4sujHHVwiVXSATACsNAE -D0Qa8hdtTQ6AUqA6/n8/u1tk0O4rPE/cTpsM3IJFX9S3rZMRsguBP7BSr1Lq/XAB -7JP/CNHt+Z9aKCKcg11wIX9/B9F7pyKM3TdKgOpqXGV6TMuLjg5PlYWI/07lVGFW -/mSJDRs8bSCFmbRtEqc4lpwlrpz+kTTnX6G7JDLfLWYw/xXVqwFfdengcDTHCc8K -wtgGq/Gu6vcoBxIO3jaca+OIkMfxxXmGrcNdseuUCa3RMZ8Qy03DqGu6Y6XQyK4B -W8zIG6H9SVKkAznM2yfYhW8v2ktcaZ95/OBHY97ZIw== ------END CERTIFICATE----- diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/key.pem b/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/key.pem deleted file mode 100644 index 66be6da..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/localhost/key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAmxTFtw113RK70H9pQmdKs9AxhFmnQ6BdDtp3jOZlWlUO0Blt -MXOUML5905etgtCbcC6RdKRtgSAiDfgx3VWiFMJH++4gUtnaB9SN8GhNSPBpFfSa -2JhWPo9HQNUsAZqlGTV4SzcGRqtWvdZxUiOfQ2TcvyXIqsaD19ivvqI1NhT6bl3t -redTZlzLLM6Wvkw6hfyHrJAPQP8LOlCIeDM4YIce6Gstv6qo9iCD4wJiY4u95HVL -7RK8t8JpZAb7VR+dPhbHEvVpjwuYd5Q05OZ280gFyrhbrKLbqst104GOQT4kQMJG -WxGONyTX6np0Dx6O5jU7dvYvjVVawbJwGuaL6wIDAQABAoIBAGW9W/S6lO+DIcoo -PHL+9sg+tq2gb5ZzN3nOI45BfI6lrMEjXTqLG9ZasovFP2TJ3J/dPTnrwZdr8Et/ -357YViwORVFnKLeSCnMGpFPq6YEHj7mCrq+YSURjlRhYgbVPsi52oMOfhrOIJrEG -ZXPAwPRi0Ftqu1omQEqz8qA7JHOkjB2p0i2Xc/uOSJccCmUDMlksRYz8zFe8wHuD -XvUL2k23n2pBZ6wiez6Xjr0wUQ4ESI02x7PmYgA3aqF2Q6ECDwHhjVeQmAuypMF6 -IaTjIJkWdZCW96pPaK1t+5nTNZ+Mg7tpJ/PRE4BkJvqcfHEOOl6wAE8gSk5uVApY -ZRKGmGkCgYEAzF9iRXYo7A/UphL11bR0gqxB6qnQl54iLhqS/E6CVNcmwJ2d9pF8 -5HTfSo1/lOXT3hGV8gizN2S5RmWBrc9HBZ+dNrVo7FYeeBiHu+opbX1X/C1HC0m1 -wJNsyoXeqD1OFc1WbDpHz5iv4IOXzYdOdKiYEcTv5JkqE7jomqBLQk8CgYEAwkG/ -rnwr4ThUo/DG5oH+l0LVnHkrJY+BUSI33g3eQ3eM0MSbfJXGT7snh5puJW0oXP7Z -Gw88nK3Vnz2nTPesiwtO2OkUVgrIgWryIvKHaqrYnapZHuM+io30jbZOVaVTMR9c -X/7/d5/evwXuP7p2DIdZKQKKFgROm1XnhNqVgaUCgYBD/ogHbCR5RVsOVciMbRlG -UGEt3YmUp/vfMuAsKUKbT2mJM+dWHVlb+LZBa4pC06QFgfxNJi/aAhzSGvtmBEww -xsXbaceauZwxgJfIIUPfNZCMSdQVIVTi2Smcx6UofBz6i/Jw14MEwlvhamaa7qVf -kqflYYwelga1wRNCPopLaQKBgQCWsZqZKQqBNMm0Q9yIhN+TR+2d7QFjqeePoRPl -1qxNejhq25ojE607vNv1ff9kWUGuoqSZMUC76r6FQba/JoNbefI4otd7x/GzM9uS -8MHMJazU4okwROkHYwgLxxkNp6rZuJJYheB4VDTfyyH/ng5lubmY7rdgTQcNyZ5I -majRYQKBgAMKJ3RlII0qvAfNFZr4Y2bNIq+60Z+Qu2W5xokIHCFNly3W1XDDKGFe -CCPHSvQljinke3P9gPt2HVdXxcnku9VkTti+JygxuLkVg7E0/SWwrWfGsaMJs+84 -fK+mTZay2d3v24r9WKEKwLykngYPyZw5+BdWU0E+xx5lGUd3U4gG ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/pebble.minica.key.pem b/vendor/github.com/go-acme/lego/e2e/fixtures/certs/pebble.minica.key.pem deleted file mode 100644 index 6a7fcd9..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/pebble.minica.key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAuVoGTaFSWp3Y+N5JC8lOdL8wmWpaM73UaNzhYiqA7ZqijzVk -TTtoQvQFDcUwyXKOdWHONrv1ld3z224Us504jjlbZwI5uoquCOZ2WJbRhmXrRgzk -Fq+/MtoFmPkhtO/DLjjtocgyIirVXN8Yl2APvB5brvRfCm6kktYeecsWfW/O3ikf -gdM7tmocwQiBypiloHOjdd5e2g8cWNw+rqvILSUVNLaLpsi23cxnLqVb424wz9dZ -5dO0REg1gSxtf4N5LSb6iGuAVoFNhzIeKzQ+svDg9x8tx/DGOghJS/jDgmxSY1qo -bTsXhcmWVfat5GJ5PQgLkCSjBBrjeBlOrc4VtQIDAQABAoIBAQCAoRoou6C0ZEDU -DScyN8TrvlcS0LzClaWYFFmRT5/jxOG1cr8l3elwNXpgYQ2Hb6mvim2ajHxVQg/e -oxlYwO4jvWhSJzg63c0DPjS5LAlCNO6+0Wlk2RheSPGDhLlAoPeZ10YKdS1dis5B -Qk4Fl1O0IHlOBCcEzV4GzPOfYDI+X6/f4xY7qz1s+CgoIxjIeiG+1/WpZQpYhobY -7CfSDdYDKtksXi7iQkc5earUAHBqZ1gQTq6e5LVm9AjRzENhMctFgcPs5zOjp2ak -PluixrA8LTAfu9wQzvxDkPl0UarZVxCerw6nlAziILpQ+U6PtoPZj49VpntTc+cq -1qjzkbhBAoGBANElJmFWY2X6LgBpszeqt0ZOSbkFg2bC0wHCJrMlRzUMEn83w9e8 -Z2Fqml9eCC5qxJcyxWDVQeoAX6090m0qgP8xNmGdafcVic2cUlrqtkqhhst2OHCO -MCQEB7cdsjiidNNrOgLbQ3i1bYID8BVLf/TDhEbRgvTewDaz6XPdoSIRAoGBAOLg -RuOec5gn50SrVycx8BLFO8AXjXojpZb1Xg26V5miz1IavSfDcgae/699ppSz+UWi -jGMFr/PokY2JxDVs3PyQLu7ahMzyFHr16Agvp5g5kq056XV+uI/HhqLHOWSQ09DS -1Vrj7FOYpKRzge3/AC7ty9Vr35uMiebpm4/CLFVlAoGALnsIJZfSbWaFdLgJCXUa -WDir77/G7T6dMIXanfPJ+IMfVUCqeLa5bxAHEOzP+qjl2giBjzy18nB00warTnGk -y5I/WMBoPW5++sAkGWqSatGtKGi0sGcZUdfHcy3ZXvbT6eyprtrWCuyfUsbXQ5RM -8rPFIQwNA6jBpSak2ohF+FECgYEAn+6IKncNd6pRfnfmdSvf1+uPxkcUJZCxb2xC -xByjGhvKWE+fHkPJwt8c0SIbZuJEC5Gds0RUF/XPfV4roZm/Yo9ldl02lp7kTxXA -XtzxIP8c5d5YM8qD4l8+Csu0Kq9pkeC+JFddxkRpc8A1TIehInPhZ+6mb6mvoMb3 -MW0pAX0CgYATT74RYuIYWZvx0TK4ZXIKTw2i6HObLF63Y6UwyPXXdEVie/ToYRNH -JIxE1weVpHvnHZvVD6D3yGk39ZsCIt31VvKpatWXlWBm875MbBc6kuIGsYT+mSSj -y9TXaE89E5zfL27nZe15QLJ+Xw8Io6PMLZ/jtC5TYoEixSZ9J8v6HA== ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/pebble.minica.pem b/vendor/github.com/go-acme/lego/e2e/fixtures/certs/pebble.minica.pem deleted file mode 100644 index a69a4c4..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/certs/pebble.minica.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDCTCCAfGgAwIBAgIIJOLbes8sTr4wDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE -AxMVbWluaWNhIHJvb3QgY2EgMjRlMmRiMCAXDTE3MTIwNjE5NDIxMFoYDzIxMTcx -MjA2MTk0MjEwWjAgMR4wHAYDVQQDExVtaW5pY2Egcm9vdCBjYSAyNGUyZGIwggEi -MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC5WgZNoVJandj43kkLyU50vzCZ -alozvdRo3OFiKoDtmqKPNWRNO2hC9AUNxTDJco51Yc42u/WV3fPbbhSznTiOOVtn -Ajm6iq4I5nZYltGGZetGDOQWr78y2gWY+SG078MuOO2hyDIiKtVc3xiXYA+8Hluu -9F8KbqSS1h55yxZ9b87eKR+B0zu2ahzBCIHKmKWgc6N13l7aDxxY3D6uq8gtJRU0 -toumyLbdzGcupVvjbjDP11nl07RESDWBLG1/g3ktJvqIa4BWgU2HMh4rND6y8OD3 -Hy3H8MY6CElL+MOCbFJjWqhtOxeFyZZV9q3kYnk9CAuQJKMEGuN4GU6tzhW1AgMB -AAGjRTBDMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB -BQUHAwIwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkqhkiG9w0BAQsFAAOCAQEAF85v -d40HK1ouDAtWeO1PbnWfGEmC5Xa478s9ddOd9Clvp2McYzNlAFfM7kdcj6xeiNhF -WPIfaGAi/QdURSL/6C1KsVDqlFBlTs9zYfh2g0UXGvJtj1maeih7zxFLvet+fqll -xseM4P9EVJaQxwuK/F78YBt0tCNfivC6JNZMgxKF59h0FBpH70ytUSHXdz7FKwix -Mfn3qEb9BXSk0Q3prNV5sOV3vgjEtB4THfDxSz9z3+DepVnW3vbbqwEbkXdk3j82 -2muVldgOUgTwK8eT+XdofVdntzU/kzygSAtAQwLJfn51fS1GvEcYGBc1bDryIqmF -p9BI7gVKtWSZYegicA== ------END CERTIFICATE----- diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/csr.cert b/vendor/github.com/go-acme/lego/e2e/fixtures/csr.cert deleted file mode 100644 index cece7dd..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/csr.cert +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIICfjCCAWYCAQAwEzERMA8GA1UEAxMIYWNtZS53dGYwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDAhXnho1w9OPHWs4YSMahYbG4Ui1K6hsHytBZfhsz0 -09igSWzHMEFZYHZJVuSr60enuJSZRhgwDjfhQWSUgHgKItLPnlNVYM6RhVaW0WfT -w6CpmE2AuH3WuQbrR2he1Nt0xfUJla+VWOFZuW7GhgBiV5iWBvdLv6Ztgh8eATjo -2vG2R+KuSUzrm6h+sb3nUR28OYunZ3vESjNwnL3/D/1th2rFpe3EA3em1HArJdXN -F4eclciun5Js17AS9tdoHEEZMMBWyViiuz3CQlh+YD2qAvqaubanWNa+r+iijMvd -4HlDHC99LTk6TJoSKoL+E/OGKmntLqmBJ1UrCFgvnw3DAgMBAAGgJjAkBgkqhkiG -9w0BCQ4xFzAVMBMGA1UdEQQMMAqCCGFjbWUud3RmMA0GCSqGSIb3DQEBCwUAA4IB -AQAfBLR8njftxf15V49szNsgNaG7Y5UQFwgl8pyiIaanGvX1DE0BtU1RB/w7itzX -wW5W/wjielEbs1XkI2uz3hkebvHVA1QpA7bbrX01WonS18xCkiRDj8ZqFEG4vEGa -HswzGUfq2v0gCOIPpVGE+8Q2Y7In5zwEfev+5DkHox4/vgwMhyPMI+y7jKtdG/dV -U58SFnt/F1raoSmR6vfDcAFXm/L8LXEkxqqefFbhiRHRqQar1Wr15BH//swmNzEW -5SVCCHcyIqreSua8uPjBcJ8aYVLniX6DMRyYv4ij/PSvSQy9xJDewLqR235WfTd/ -tk4hhJaqizKDpsvB+UFod5o5 ------END CERTIFICATE REQUEST----- diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/csr.raw b/vendor/github.com/go-acme/lego/e2e/fixtures/csr.raw deleted file mode 100644 index f4bb701..0000000 Binary files a/vendor/github.com/go-acme/lego/e2e/fixtures/csr.raw and /dev/null differ diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/pebble-config-dns.json b/vendor/github.com/go-acme/lego/e2e/fixtures/pebble-config-dns.json deleted file mode 100644 index 4834825..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/pebble-config-dns.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "pebble": { - "listenAddress": "0.0.0.0:15000", - "certificate": "fixtures/certs/localhost/cert.pem", - "privateKey": "fixtures/certs/localhost/key.pem", - "httpPort": 5004, - "tlsPort": 5003 - } -} diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/pebble-config.json b/vendor/github.com/go-acme/lego/e2e/fixtures/pebble-config.json deleted file mode 100644 index f2abe6a..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/pebble-config.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "pebble": { - "listenAddress": "0.0.0.0:14000", - "certificate": "fixtures/certs/localhost/cert.pem", - "privateKey": "fixtures/certs/localhost/key.pem", - "httpPort": 5002, - "tlsPort": 5001 - } -} diff --git a/vendor/github.com/go-acme/lego/e2e/fixtures/update-dns.sh b/vendor/github.com/go-acme/lego/e2e/fixtures/update-dns.sh deleted file mode 100755 index 44343c6..0000000 --- a/vendor/github.com/go-acme/lego/e2e/fixtures/update-dns.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash -# Simple DNS challenge exec solver. -# Use challtestsrv https://github.com/letsencrypt/boulder/tree/master/test/challtestsrv - -set -e - -case "$1" in - "present") - echo "Present" - payload="{\"host\":\"$2\", \"value\":\"$3\"}" - echo "payload=${payload}" - curl -s -X POST -d "${payload}" localhost:8055/set-txt - ;; - "cleanup") - echo "cleanup" - payload="{\"host\":\"$2\"}" - echo "payload=${payload}" - curl -s -X POST -d "${payload}" localhost:8055/clear-txt - ;; - *) - echo "OOPS" - ;; -esac diff --git a/vendor/github.com/go-acme/lego/e2e/loader/loader.go b/vendor/github.com/go-acme/lego/e2e/loader/loader.go deleted file mode 100644 index 90211fe..0000000 --- a/vendor/github.com/go-acme/lego/e2e/loader/loader.go +++ /dev/null @@ -1,304 +0,0 @@ -package loader - -import ( - "bytes" - "crypto/tls" - "errors" - "fmt" - "io/ioutil" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" - "time" - - "github.com/go-acme/lego/platform/wait" -) - -const ( - cmdNamePebble = "pebble" - cmdNameChallSrv = "pebble-challtestsrv" -) - -type CmdOption struct { - HealthCheckURL string - Args []string - Env []string - Dir string -} - -type EnvLoader struct { - PebbleOptions *CmdOption - LegoOptions []string - ChallSrv *CmdOption - lego string -} - -func (l *EnvLoader) MainTest(m *testing.M) int { - _, force := os.LookupEnv("LEGO_E2E_TESTS") - if _, ci := os.LookupEnv("CI"); !ci && !force { - fmt.Fprintln(os.Stderr, "skipping test: e2e tests are disabled. (no 'CI' or 'LEGO_E2E_TESTS' env var)") - fmt.Println("PASS") - return 0 - } - - if _, err := exec.LookPath("git"); err != nil { - fmt.Fprintln(os.Stderr, "skipping because git command not found") - fmt.Println("PASS") - return 0 - } - - if l.PebbleOptions != nil { - if _, err := exec.LookPath(cmdNamePebble); err != nil { - fmt.Fprintln(os.Stderr, "skipping because pebble binary not found") - fmt.Println("PASS") - return 0 - } - } - - if l.ChallSrv != nil { - if _, err := exec.LookPath(cmdNameChallSrv); err != nil { - fmt.Fprintln(os.Stderr, "skipping because challtestsrv binary not found") - fmt.Println("PASS") - return 0 - } - } - - pebbleTearDown := l.launchPebble() - defer pebbleTearDown() - - challSrvTearDown := l.launchChallSrv() - defer challSrvTearDown() - - legoBinary, tearDown, err := buildLego() - defer tearDown() - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 1 - } - - l.lego = legoBinary - - if l.PebbleOptions != nil && l.PebbleOptions.HealthCheckURL != "" { - pebbleHealthCheck(l.PebbleOptions) - } - - return m.Run() -} - -func (l *EnvLoader) RunLego(arg ...string) ([]byte, error) { - cmd := exec.Command(l.lego, arg...) - cmd.Env = l.LegoOptions - - fmt.Printf("$ %s\n", strings.Join(cmd.Args, " ")) - - return cmd.CombinedOutput() -} - -func (l *EnvLoader) launchPebble() func() { - if l.PebbleOptions == nil { - return func() {} - } - - pebble, outPebble := l.cmdPebble() - go func() { - err := pebble.Run() - if err != nil { - fmt.Println(err) - } - }() - - return func() { - err := pebble.Process.Kill() - if err != nil { - fmt.Println(err) - } - fmt.Println(outPebble.String()) - } -} - -func (l *EnvLoader) cmdPebble() (*exec.Cmd, *bytes.Buffer) { - cmd := exec.Command(cmdNamePebble, l.PebbleOptions.Args...) - cmd.Env = l.PebbleOptions.Env - - dir, err := filepath.Abs(l.PebbleOptions.Dir) - if err != nil { - panic(err) - } - cmd.Dir = dir - - fmt.Printf("$ %s\n", strings.Join(cmd.Args, " ")) - - var b bytes.Buffer - cmd.Stdout = &b - cmd.Stderr = &b - - return cmd, &b -} - -func pebbleHealthCheck(options *CmdOption) { - client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} - err := wait.For("pebble", 10*time.Second, 500*time.Millisecond, func() (bool, error) { - resp, err := client.Get(options.HealthCheckURL) - if err != nil { - return false, err - } - - if resp.StatusCode != http.StatusOK { - return false, nil - } - - return true, nil - }) - if err != nil { - panic(err) - } -} - -func (l *EnvLoader) launchChallSrv() func() { - if l.ChallSrv == nil { - return func() {} - } - - challtestsrv, outChalSrv := l.cmdChallSrv() - go func() { - err := challtestsrv.Run() - if err != nil { - fmt.Println(err) - } - }() - - return func() { - err := challtestsrv.Process.Kill() - if err != nil { - fmt.Println(err) - } - fmt.Println(outChalSrv.String()) - } -} - -func (l *EnvLoader) cmdChallSrv() (*exec.Cmd, *bytes.Buffer) { - cmd := exec.Command(cmdNameChallSrv, l.ChallSrv.Args...) - - fmt.Printf("$ %s\n", strings.Join(cmd.Args, " ")) - - var b bytes.Buffer - cmd.Stdout = &b - cmd.Stderr = &b - - return cmd, &b -} - -func buildLego() (string, func(), error) { - here, err := os.Getwd() - if err != nil { - return "", func() {}, err - } - defer func() { _ = os.Chdir(here) }() - - buildPath, err := ioutil.TempDir("", "lego_test") - if err != nil { - return "", func() {}, err - } - - projectRoot, err := getProjectRoot() - if err != nil { - return "", func() {}, err - } - - mainFolder := filepath.Join(projectRoot, "cmd", "lego") - - err = os.Chdir(mainFolder) - if err != nil { - return "", func() {}, err - } - - binary := filepath.Join(buildPath, "lego") - - err = build(binary) - if err != nil { - return "", func() {}, err - } - - err = os.Chdir(here) - if err != nil { - return "", func() {}, err - } - - return binary, func() { - _ = os.RemoveAll(buildPath) - CleanLegoFiles() - }, nil -} - -func getProjectRoot() (string, error) { - git := exec.Command("git", "rev-parse", "--show-toplevel") - - output, err := git.CombinedOutput() - if err != nil { - fmt.Fprintf(os.Stderr, "%s\n", output) - return "", err - } - - return strings.TrimSpace(string(output)), nil -} - -func build(binary string) error { - toolPath, err := goToolPath() - if err != nil { - return err - } - cmd := exec.Command(toolPath, "build", "-o", binary) - - output, err := cmd.CombinedOutput() - if err != nil { - fmt.Fprintf(os.Stderr, "%s\n", output) - return err - } - - return nil -} - -func goToolPath() (string, error) { - // inspired by go1.11.1/src/internal/testenv/testenv.go - if os.Getenv("GO_GCFLAGS") != "" { - return "", errors.New("'go build' not compatible with setting $GO_GCFLAGS") - } - - if runtime.GOOS == "darwin" && strings.HasPrefix(runtime.GOARCH, "arm") { - return "", fmt.Errorf("skipping test: 'go build' not available on %s/%s", runtime.GOOS, runtime.GOARCH) - } - - return goTool() -} - -func goTool() (string, error) { - var exeSuffix string - if runtime.GOOS == "windows" { - exeSuffix = ".exe" - } - - path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix) - if _, err := os.Stat(path); err == nil { - return path, nil - } - - goBin, err := exec.LookPath("go" + exeSuffix) - if err != nil { - return "", fmt.Errorf("cannot find go tool: %v", err) - } - - return goBin, nil -} - -func CleanLegoFiles() { - cmd := exec.Command("rm", "-rf", ".lego") - fmt.Printf("$ %s\n", strings.Join(cmd.Args, " ")) - output, err := cmd.CombinedOutput() - if err != nil { - fmt.Println(string(output)) - } -} diff --git a/vendor/github.com/go-acme/lego/e2e/readme.md b/vendor/github.com/go-acme/lego/e2e/readme.md deleted file mode 100644 index b98a40a..0000000 --- a/vendor/github.com/go-acme/lego/e2e/readme.md +++ /dev/null @@ -1,22 +0,0 @@ -# E2E tests - -How to run: - -- Add the following entries to your `/etc/hosts`: -``` -127.0.0.1 acme.wtf -127.0.0.1 lego.wtf -127.0.0.1 acme.lego.wtf -127.0.0.1 légô.wtf -127.0.0.1 xn--lg-bja9b.wtf -``` - -- Install [Pebble](https://github.com/letsencrypt/pebble): -```bash -go get -u github.com/letsencrypt/pebble/... -``` - -- Launch tests: -```bash -make e2e -``` diff --git a/vendor/github.com/go-acme/lego/internal/dnsdocs/dns.go.tmpl b/vendor/github.com/go-acme/lego/internal/dnsdocs/dns.go.tmpl deleted file mode 100644 index 6d127ab..0000000 --- a/vendor/github.com/go-acme/lego/internal/dnsdocs/dns.go.tmpl +++ /dev/null @@ -1,58 +0,0 @@ -package cmd - -// CODE GENERATED AUTOMATICALLY -// THIS FILE MUST NOT BE EDITED BY HAND - -import ( - "fmt" - "os" - "sort" - "strings" - "text/tabwriter" - - "github.com/go-acme/lego/log" -) - -func allDNSCodes() string { - providers := []string{ - "manual", -{{- range $provider := .Providers }} - "{{ $provider.Code }}", -{{- end}} - } - sort.Strings(providers) - return strings.Join(providers, ", ") -} - -func displayDNSHelp(name string) { - w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) - switch name { -{{ range $provider := .Providers }} - case "{{ $provider.Code }}": - // generated from: {{ .GeneratedFrom }} - fmt.Fprintln(w, `Configuration for {{ $provider.Name }}.`) - fmt.Fprintln(w, `Code: '{{ $provider.Code }}'`) - fmt.Fprintln(w, `Since: '{{ $provider.Since }}'`) - fmt.Fprintln(w) -{{if $provider.Configuration }}{{if $provider.Configuration.Credentials }} - fmt.Fprintln(w, `Credentials:`) -{{- range $k, $v := $provider.Configuration.Credentials }} - fmt.Fprintln(w,` - "{{ $k }}": {{ safe $v }}`) -{{- end}} - fmt.Fprintln(w) -{{end}}{{if $provider.Configuration.Additional }} - fmt.Fprintln(w, `Additional Configuration:`) -{{- range $k, $v := $provider.Configuration.Additional }} - fmt.Fprintln(w, ` - "{{ $k }}": {{ safe $v }}`) -{{- end}} -{{end}}{{end}} - fmt.Fprintln(w) - fmt.Fprintln(w, `More information: https://go-acme.github.io/lego/dns/{{ $provider.Code }}`) -{{end}} - case "manual": - fmt.Fprintln(w, `Solving the DNS-01 challenge using CLI prompt.`) - default: - log.Fatalf("%q is not yet supported.", name) - } - w.Flush() -} \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/internal/dnsdocs/dns.md.tmpl b/vendor/github.com/go-acme/lego/internal/dnsdocs/dns.md.tmpl deleted file mode 100644 index cc766f8..0000000 --- a/vendor/github.com/go-acme/lego/internal/dnsdocs/dns.md.tmpl +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: "{{ .Name }}" -date: 2019-03-03T16:39:46+01:00 -draft: false -slug: {{ .Code }} ---- - - - - - -Since: {{ .Since }} -{{if .Description -}} -{{ .Description }} -{{else}} -Configuration for [{{ .Name }}]({{ .URL }}). -{{end}} - - - -- Code: `{{ .Code }}` -{{if .Example }} -Here is an example bash command using the {{ .Name }} provider: - -```bash -{{ .Example -}} -``` -{{else}} -{{ "{{" }}% notice note %}} -_Please contribute by adding a CLI example._ -{{ "{{" }}% /notice %}} -{{end}} - -{{if .Configuration }} -{{if .Configuration.Credentials }} -## Credentials - -| Environment Variable Name | Description | -|-----------------------|-------------| -{{- range $k, $v := .Configuration.Credentials }} -| `{{$k}}` | {{$v}} | -{{- end}} - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). -{{- end}} - -{{if .Configuration.Additional }} -## Additional Configuration - -| Environment Variable Name | Description | -|--------------------------------|-------------| -{{- range $k, $v := .Configuration.Additional }} -| `{{$k}}` | {{$v}} | -{{- end}} - -The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. -More information [here](/lego/dns/#configuration-and-credentials). -{{- end}} -{{- end}} - -{{ .Additional }} - -{{if .Links }} -## More information - -{{if .Links.API -}} -- [API documentation]({{ .Links.API }}) -{{- end}} -{{- if .Links.GoClient }} -- [Go client]({{ .Links.GoClient }}) -{{- end}} - -{{- end}} - - - - diff --git a/vendor/github.com/go-acme/lego/internal/dnsdocs/generator.go b/vendor/github.com/go-acme/lego/internal/dnsdocs/generator.go deleted file mode 100644 index 5158ba6..0000000 --- a/vendor/github.com/go-acme/lego/internal/dnsdocs/generator.go +++ /dev/null @@ -1,136 +0,0 @@ -package main - -//go:generate go run . - -import ( - "bytes" - "go/format" - "log" - "os" - "path/filepath" - "strings" - "text/template" - - "github.com/BurntSushi/toml" -) - -const ( - root = "../../" - dnsPackage = root + "providers/dns" - mdTemplate = root + "internal/dnsdocs/dns.md.tmpl" - cliTemplate = root + "internal/dnsdocs/dns.go.tmpl" - cliOutput = root + "cmd/zz_gen_cmd_dnshelp.go" - docOutput = root + "docs/content/dns" -) - -type Model struct { - Name string // Real name of the DNS provider - Code string // DNS code - Since string // First lego version - URL string // DNS provider URL - Description string // Provider summary - Example string // CLI example - Configuration *Configuration // Environment variables - Links *Links // Links - Additional string // Extra documentation - GeneratedFrom string // Source file -} - -type Configuration struct { - Credentials map[string]string - Additional map[string]string -} - -type Links struct { - API string - GoClient string -} - -type Providers struct { - Providers []Model -} - -func main() { - models := &Providers{} - - err := filepath.Walk(dnsPackage, walker(models)) - if err != nil { - log.Fatal(err) - } - - // generate CLI help - err = generateCLIHelp(models) - if err != nil { - log.Fatal(err) - } -} - -func walker(prs *Providers) func(string, os.FileInfo, error) error { - return func(path string, _ os.FileInfo, err error) error { - if err != nil { - return err - } - - if filepath.Ext(path) == ".toml" { - m := Model{} - - m.GeneratedFrom, err = filepath.Rel(root, path) - if err != nil { - return err - } - - _, err := toml.DecodeFile(path, &m) - if err != nil { - return err - } - - prs.Providers = append(prs.Providers, m) - - // generate documentation - return generateDocumentation(m) - } - - return nil - } -} - -func generateDocumentation(m Model) error { - filename := filepath.Join(docOutput, "zz_gen_"+m.Code+".md") - - file, err := os.Create(filename) - if err != nil { - return err - } - - return template.Must(template.ParseFiles(mdTemplate)).Execute(file, m) -} - -func generateCLIHelp(models *Providers) error { - filename := filepath.Join(cliOutput) - - file, err := os.Create(filename) - if err != nil { - return err - } - - tlt := template.New(filepath.Base(cliTemplate)).Funcs(map[string]interface{}{ - "safe": func(src string) string { - return strings.ReplaceAll(src, "`", "'") - }, - }) - - b := &bytes.Buffer{} - err = template.Must(tlt.ParseFiles(cliTemplate)).Execute(b, models) - if err != nil { - return err - } - - // gofmt - source, err := format.Source(b.Bytes()) - if err != nil { - return err - } - - _, err = file.Write(source) - return err -} diff --git a/vendor/github.com/go-acme/lego/internal/release.go b/vendor/github.com/go-acme/lego/internal/release.go deleted file mode 100644 index b005e15..0000000 --- a/vendor/github.com/go-acme/lego/internal/release.go +++ /dev/null @@ -1,223 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/token" - "io/ioutil" - "log" - "os" - "regexp" - "strconv" - "strings" - "text/template" - - "github.com/urfave/cli" -) - -const sourceFile = "./acme/api/internal/sender/useragent.go" - -const uaTemplate = `package sender - -// CODE GENERATED AUTOMATICALLY -// THIS FILE MUST NOT BE EDITED BY HAND - -const ( - // ourUserAgent is the User-Agent of this underlying library package. - ourUserAgent = "xenolf-acme/{{ .version }}" - - // ourUserAgentComment is part of the UA comment linked to the version status of this underlying library package. - // values: detach|release - // NOTE: Update this with each tagged release. - ourUserAgentComment = "{{ .comment }}" -) - -` - -func main() { - app := cli.NewApp() - app.Name = "lego-releaser" - app.Usage = "Lego releaser" - app.HelpName = "releaser" - app.Commands = []cli.Command{ - { - Name: "release", - Usage: "Update file for a release", - Action: release, - Before: func(ctx *cli.Context) error { - mode := ctx.String("mode") - switch mode { - case "patch", "minor", "major": - return nil - default: - return fmt.Errorf("invalid mode: %s", mode) - } - }, - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "mode, m", - Value: "patch", - Usage: "The release mode: patch|minor|major", - }, - }, - }, - { - Name: "detach", - Usage: "Update file post release", - Action: detach, - }, - } - - err := app.Run(os.Args) - if err != nil { - log.Fatal(err) - } -} - -func release(ctx *cli.Context) error { - mode := ctx.String("mode") - - // Read file - data, err := readUserAgentFile(sourceFile) - if err != nil { - return err - } - - // Bump version - newVersion, err := bumpVersion(data["ourUserAgent"], mode) - if err != nil { - return err - } - - // Write file - comment := "release" // detach|release - return writeUserAgentFile(sourceFile, newVersion, comment) -} - -func detach(_ *cli.Context) error { - // Read file - data, err := readUserAgentFile(sourceFile) - if err != nil { - return err - } - - // Write file - version := strings.TrimPrefix(data["ourUserAgent"], "xenolf-acme/") - comment := "detach" - return writeUserAgentFile(sourceFile, version, comment) -} - -type visitor struct { - data map[string]string -} - -func (v visitor) Visit(n ast.Node) ast.Visitor { - if n == nil { - return nil - } - - switch d := n.(type) { - case *ast.GenDecl: - if d.Tok == token.CONST { - for _, spec := range d.Specs { - valueSpec, ok := spec.(*ast.ValueSpec) - if !ok { - continue - } - if len(valueSpec.Names) != 1 || len(valueSpec.Values) != 1 { - continue - } - - va, ok := valueSpec.Values[0].(*ast.BasicLit) - if !ok { - continue - } - if va.Kind != token.STRING { - continue - } - - s, err := strconv.Unquote(va.Value) - if err != nil { - continue - } - - v.data[valueSpec.Names[0].String()] = s - } - } - default: - // noop - } - return v -} - -func readUserAgentFile(filename string) (map[string]string, error) { - fset := token.NewFileSet() - file, err := parser.ParseFile(fset, filename, nil, parser.AllErrors) - if err != nil { - return nil, err - } - - v := visitor{data: make(map[string]string)} - ast.Walk(v, file) - - return v.data, nil -} - -func writeUserAgentFile(filename string, version string, comment string) error { - tmpl, err := template.New("ua").Parse(uaTemplate) - if err != nil { - return err - } - - b := &bytes.Buffer{} - err = tmpl.Execute(b, map[string]string{ - "version": version, - "comment": comment, - }) - if err != nil { - return err - } - - source, err := format.Source(b.Bytes()) - if err != nil { - return err - } - - return ioutil.WriteFile(filename, source, 0644) -} - -func bumpVersion(userAgent string, mode string) (string, error) { - prevVersion := strings.TrimPrefix(userAgent, "xenolf-acme/") - - allString := regexp.MustCompile(`(\d+)\.(\d+)\.(\d+)`).FindStringSubmatch(prevVersion) - - if len(allString) != 4 { - return "", fmt.Errorf("invalid version format: %s", prevVersion) - } - - switch mode { - case "patch": - patch, err := strconv.Atoi(allString[3]) - if err != nil { - return "", err - } - return fmt.Sprintf("%s.%s.%d", allString[1], allString[2], patch+1), nil - case "minor": - minor, err := strconv.Atoi(allString[2]) - if err != nil { - return "", err - } - return fmt.Sprintf("%s.%d.0", allString[1], minor+1), nil - case "major": - major, err := strconv.Atoi(allString[1]) - if err != nil { - return "", err - } - return fmt.Sprintf("%d.0.0", major+1), nil - default: - return "", fmt.Errorf("invalid mode: %s", mode) - } -} diff --git a/vendor/github.com/go-acme/lego/lego/client.go b/vendor/github.com/go-acme/lego/lego/client.go deleted file mode 100644 index c55dd25..0000000 --- a/vendor/github.com/go-acme/lego/lego/client.go +++ /dev/null @@ -1,74 +0,0 @@ -package lego - -import ( - "errors" - "net/url" - - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge/resolver" - "github.com/go-acme/lego/registration" -) - -// Client is the user-friendly way to ACME -type Client struct { - Certificate *certificate.Certifier - Challenge *resolver.SolverManager - Registration *registration.Registrar - core *api.Core -} - -// NewClient creates a new ACME client on behalf of the user. -// The client will depend on the ACME directory located at CADirURL for the rest of its actions. -// A private key of type keyType (see KeyType constants) will be generated when requesting a new certificate if one isn't provided. -func NewClient(config *Config) (*Client, error) { - if config == nil { - return nil, errors.New("a configuration must be provided") - } - - _, err := url.Parse(config.CADirURL) - if err != nil { - return nil, err - } - - if config.HTTPClient == nil { - return nil, errors.New("the HTTP client cannot be nil") - } - - privateKey := config.User.GetPrivateKey() - if privateKey == nil { - return nil, errors.New("private key was nil") - } - - var kid string - if reg := config.User.GetRegistration(); reg != nil { - kid = reg.URI - } - - core, err := api.New(config.HTTPClient, config.UserAgent, config.CADirURL, kid, privateKey) - if err != nil { - return nil, err - } - - solversManager := resolver.NewSolversManager(core) - - prober := resolver.NewProber(solversManager) - certifier := certificate.NewCertifier(core, prober, certificate.CertifierOptions{KeyType: config.Certificate.KeyType, Timeout: config.Certificate.Timeout}) - - return &Client{ - Certificate: certifier, - Challenge: solversManager, - Registration: registration.NewRegistrar(core, config.User), - core: core, - }, nil -} - -// GetToSURL returns the current ToS URL from the Directory -func (c *Client) GetToSURL() string { - return c.core.GetDirectory().Meta.TermsOfService -} - -// GetExternalAccountRequired returns the External Account Binding requirement of the Directory -func (c *Client) GetExternalAccountRequired() bool { - return c.core.GetDirectory().Meta.ExternalAccountRequired -} diff --git a/vendor/github.com/go-acme/lego/lego/client_config.go b/vendor/github.com/go-acme/lego/lego/client_config.go deleted file mode 100644 index 2421d7f..0000000 --- a/vendor/github.com/go-acme/lego/lego/client_config.go +++ /dev/null @@ -1,104 +0,0 @@ -package lego - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net" - "net/http" - "os" - "time" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/registration" -) - -const ( - // caCertificatesEnvVar is the environment variable name that can be used to - // specify the path to PEM encoded CA Certificates that can be used to - // authenticate an ACME server with a HTTPS certificate not issued by a CA in - // the system-wide trusted root list. - caCertificatesEnvVar = "LEGO_CA_CERTIFICATES" - - // caServerNameEnvVar is the environment variable name that can be used to - // specify the CA server name that can be used to - // authenticate an ACME server with a HTTPS certificate not issued by a CA in - // the system-wide trusted root list. - caServerNameEnvVar = "LEGO_CA_SERVER_NAME" - - // LEDirectoryProduction URL to the Let's Encrypt production - LEDirectoryProduction = "https://acme-v02.api.letsencrypt.org/directory" - - // LEDirectoryStaging URL to the Let's Encrypt staging - LEDirectoryStaging = "https://acme-staging-v02.api.letsencrypt.org/directory" -) - -type Config struct { - CADirURL string - User registration.User - UserAgent string - HTTPClient *http.Client - Certificate CertificateConfig -} - -func NewConfig(user registration.User) *Config { - return &Config{ - CADirURL: LEDirectoryProduction, - User: user, - HTTPClient: createDefaultHTTPClient(), - Certificate: CertificateConfig{ - KeyType: certcrypto.RSA2048, - Timeout: 30 * time.Second, - }, - } -} - -type CertificateConfig struct { - KeyType certcrypto.KeyType - Timeout time.Duration -} - -// createDefaultHTTPClient Creates an HTTP client with a reasonable timeout value -// and potentially a custom *x509.CertPool -// based on the caCertificatesEnvVar environment variable (see the `initCertPool` function) -func createDefaultHTTPClient() *http.Client { - return &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - TLSHandshakeTimeout: 15 * time.Second, - ResponseHeaderTimeout: 15 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - TLSClientConfig: &tls.Config{ - ServerName: os.Getenv(caServerNameEnvVar), - RootCAs: initCertPool(), - }, - }, - } -} - -// initCertPool creates a *x509.CertPool populated with the PEM certificates -// found in the filepath specified in the caCertificatesEnvVar OS environment -// variable. If the caCertificatesEnvVar is not set then initCertPool will -// return nil. If there is an error creating a *x509.CertPool from the provided -// caCertificatesEnvVar value then initCertPool will panic. -func initCertPool() *x509.CertPool { - if customCACertsPath := os.Getenv(caCertificatesEnvVar); customCACertsPath != "" { - customCAs, err := ioutil.ReadFile(customCACertsPath) - if err != nil { - panic(fmt.Sprintf("error reading %s=%q: %v", - caCertificatesEnvVar, customCACertsPath, err)) - } - certPool := x509.NewCertPool() - if ok := certPool.AppendCertsFromPEM(customCAs); !ok { - panic(fmt.Sprintf("error creating x509 cert pool from %s=%q: %v", - caCertificatesEnvVar, customCACertsPath, err)) - } - return certPool - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/lego/client_test.go b/vendor/github.com/go-acme/lego/lego/client_test.go deleted file mode 100644 index 62b1bb3..0000000 --- a/vendor/github.com/go-acme/lego/lego/client_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package lego - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/go-acme/lego/registration" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewClient(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - keyBits := 32 // small value keeps test fast - key, err := rsa.GenerateKey(rand.Reader, keyBits) - require.NoError(t, err, "Could not generate test key") - - user := mockUser{ - email: "test@test.com", - regres: new(registration.Resource), - privatekey: key, - } - - config := NewConfig(user) - config.CADirURL = apiURL + "/dir" - - client, err := NewClient(config) - require.NoError(t, err, "Could not create client") - - assert.NotNil(t, client) -} - -type mockUser struct { - email string - regres *registration.Resource - privatekey *rsa.PrivateKey -} - -func (u mockUser) GetEmail() string { return u.email } -func (u mockUser) GetRegistration() *registration.Resource { return u.regres } -func (u mockUser) GetPrivateKey() crypto.PrivateKey { return u.privatekey } diff --git a/vendor/github.com/go-acme/lego/log/logger.go b/vendor/github.com/go-acme/lego/log/logger.go deleted file mode 100644 index 22ec98f..0000000 --- a/vendor/github.com/go-acme/lego/log/logger.go +++ /dev/null @@ -1,59 +0,0 @@ -package log - -import ( - "log" - "os" -) - -// Logger is an optional custom logger. -var Logger StdLogger = log.New(os.Stdout, "", log.LstdFlags) - -// StdLogger interface for Standard Logger. -type StdLogger interface { - Fatal(args ...interface{}) - Fatalln(args ...interface{}) - Fatalf(format string, args ...interface{}) - Print(args ...interface{}) - Println(args ...interface{}) - Printf(format string, args ...interface{}) -} - -// Fatal writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Fatal(args ...interface{}) { - Logger.Fatal(args...) -} - -// Fatalf writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Fatalf(format string, args ...interface{}) { - Logger.Fatalf(format, args...) -} - -// Print writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Print(args ...interface{}) { - Logger.Print(args...) -} - -// Println writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Println(args ...interface{}) { - Logger.Println(args...) -} - -// Printf writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Printf(format string, args ...interface{}) { - Logger.Printf(format, args...) -} - -// Warnf writes a log entry. -func Warnf(format string, args ...interface{}) { - Printf("[WARN] "+format, args...) -} - -// Infof writes a log entry. -func Infof(format string, args ...interface{}) { - Printf("[INFO] "+format, args...) -} diff --git a/vendor/github.com/go-acme/lego/platform/config/env/env.go b/vendor/github.com/go-acme/lego/platform/config/env/env.go deleted file mode 100644 index f489c65..0000000 --- a/vendor/github.com/go-acme/lego/platform/config/env/env.go +++ /dev/null @@ -1,163 +0,0 @@ -package env - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/log" -) - -// Get environment variables -func Get(names ...string) (map[string]string, error) { - values := map[string]string{} - - var missingEnvVars []string - for _, envVar := range names { - value := GetOrFile(envVar) - if value == "" { - missingEnvVars = append(missingEnvVars, envVar) - } - values[envVar] = value - } - - if len(missingEnvVars) > 0 { - return nil, fmt.Errorf("some credentials information are missing: %s", strings.Join(missingEnvVars, ",")) - } - - return values, nil -} - -// GetWithFallback Get environment variable values -// The first name in each group is use as key in the result map -// -// // LEGO_ONE="ONE" -// // LEGO_TWO="TWO" -// env.GetWithFallback([]string{"LEGO_ONE", "LEGO_TWO"}) -// // => "LEGO_ONE" = "ONE" -// -// ---- -// -// // LEGO_ONE="" -// // LEGO_TWO="TWO" -// env.GetWithFallback([]string{"LEGO_ONE", "LEGO_TWO"}) -// // => "LEGO_ONE" = "TWO" -// -// ---- -// -// // LEGO_ONE="" -// // LEGO_TWO="" -// env.GetWithFallback([]string{"LEGO_ONE", "LEGO_TWO"}) -// // => error -// -func GetWithFallback(groups ...[]string) (map[string]string, error) { - values := map[string]string{} - - var missingEnvVars []string - for _, names := range groups { - if len(names) == 0 { - return nil, errors.New("undefined environment variable names") - } - - value, envVar := getOneWithFallback(names[0], names[1:]...) - if len(value) == 0 { - missingEnvVars = append(missingEnvVars, envVar) - continue - } - values[envVar] = value - } - - if len(missingEnvVars) > 0 { - return nil, fmt.Errorf("some credentials information are missing: %s", strings.Join(missingEnvVars, ",")) - } - - return values, nil -} - -func getOneWithFallback(main string, names ...string) (string, string) { - value := GetOrFile(main) - if len(value) > 0 { - return value, main - } - - for _, name := range names { - value := GetOrFile(name) - if len(value) > 0 { - return value, main - } - } - - return "", main -} - -// GetOrDefaultInt returns the given environment variable value as an integer. -// Returns the default if the envvar cannot be coopered to an int, or is not found. -func GetOrDefaultInt(envVar string, defaultValue int) int { - v, err := strconv.Atoi(GetOrFile(envVar)) - if err != nil { - return defaultValue - } - - return v -} - -// GetOrDefaultSecond returns the given environment variable value as an time.Duration (second). -// Returns the default if the envvar cannot be coopered to an int, or is not found. -func GetOrDefaultSecond(envVar string, defaultValue time.Duration) time.Duration { - v := GetOrDefaultInt(envVar, -1) - if v < 0 { - return defaultValue - } - - return time.Duration(v) * time.Second -} - -// GetOrDefaultString returns the given environment variable value as a string. -// Returns the default if the envvar cannot be find. -func GetOrDefaultString(envVar string, defaultValue string) string { - v := GetOrFile(envVar) - if len(v) == 0 { - return defaultValue - } - - return v -} - -// GetOrDefaultBool returns the given environment variable value as a boolean. -// Returns the default if the envvar cannot be coopered to a boolean, or is not found. -func GetOrDefaultBool(envVar string, defaultValue bool) bool { - v, err := strconv.ParseBool(GetOrFile(envVar)) - if err != nil { - return defaultValue - } - - return v -} - -// GetOrFile Attempts to resolve 'key' as an environment variable. -// Failing that, it will check to see if '_FILE' exists. -// If so, it will attempt to read from the referenced file to populate a value. -func GetOrFile(envVar string) string { - envVarValue := os.Getenv(envVar) - if envVarValue != "" { - return envVarValue - } - - fileVar := envVar + "_FILE" - fileVarValue := os.Getenv(fileVar) - if fileVarValue == "" { - return envVarValue - } - - fileContents, err := ioutil.ReadFile(fileVarValue) - if err != nil { - log.Printf("Failed to read the file %s (defined by env var %s): %s", fileVarValue, fileVar, err) - return "" - } - - return strings.TrimSuffix(string(fileContents), "\n") -} diff --git a/vendor/github.com/go-acme/lego/platform/config/env/env_test.go b/vendor/github.com/go-acme/lego/platform/config/env/env_test.go deleted file mode 100644 index 57ba7ad..0000000 --- a/vendor/github.com/go-acme/lego/platform/config/env/env_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package env - -import ( - "io/ioutil" - "os" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetWithFallback(t *testing.T) { - var1Exist := os.Getenv("TEST_LEGO_VAR_EXIST_1") - var2Exist := os.Getenv("TEST_LEGO_VAR_EXIST_2") - var1Missing := os.Getenv("TEST_LEGO_VAR_MISSING_1") - var2Missing := os.Getenv("TEST_LEGO_VAR_MISSING_2") - - defer func() { - _ = os.Setenv("TEST_LEGO_VAR_EXIST_1", var1Exist) - _ = os.Setenv("TEST_LEGO_VAR_EXIST_2", var2Exist) - _ = os.Setenv("TEST_LEGO_VAR_MISSING_1", var1Missing) - _ = os.Setenv("TEST_LEGO_VAR_MISSING_2", var2Missing) - }() - - err := os.Setenv("TEST_LEGO_VAR_EXIST_1", "VAR1") - require.NoError(t, err) - err = os.Setenv("TEST_LEGO_VAR_EXIST_2", "VAR2") - require.NoError(t, err) - err = os.Unsetenv("TEST_LEGO_VAR_MISSING_1") - require.NoError(t, err) - err = os.Unsetenv("TEST_LEGO_VAR_MISSING_2") - require.NoError(t, err) - - type expected struct { - value map[string]string - error string - } - - testCases := []struct { - desc string - groups [][]string - expected expected - }{ - { - desc: "no groups", - groups: nil, - expected: expected{ - value: map[string]string{}, - }, - }, - { - desc: "empty groups", - groups: [][]string{{}, {}}, - expected: expected{ - error: "undefined environment variable names", - }, - }, - { - desc: "missing env var", - groups: [][]string{{"TEST_LEGO_VAR_MISSING_1"}}, - expected: expected{ - error: "some credentials information are missing: TEST_LEGO_VAR_MISSING_1", - }, - }, - { - desc: "all env var in a groups are missing", - groups: [][]string{{"TEST_LEGO_VAR_MISSING_1", "TEST_LEGO_VAR_MISSING_2"}}, - expected: expected{ - error: "some credentials information are missing: TEST_LEGO_VAR_MISSING_1", - }, - }, - { - desc: "only the first env var have a value", - groups: [][]string{{"TEST_LEGO_VAR_EXIST_1", "TEST_LEGO_VAR_MISSING_1"}}, - expected: expected{ - value: map[string]string{"TEST_LEGO_VAR_EXIST_1": "VAR1"}, - }, - }, - { - desc: "only the second env var have a value", - groups: [][]string{{"TEST_LEGO_VAR_MISSING_1", "TEST_LEGO_VAR_EXIST_1"}}, - expected: expected{ - value: map[string]string{"TEST_LEGO_VAR_MISSING_1": "VAR1"}, - }, - }, - { - desc: "only all env vars have a value", - groups: [][]string{{"TEST_LEGO_VAR_EXIST_1", "TEST_LEGO_VAR_EXIST_2"}}, - expected: expected{ - value: map[string]string{"TEST_LEGO_VAR_EXIST_1": "VAR1"}, - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - value, err := GetWithFallback(test.groups...) - if len(test.expected.error) > 0 { - assert.EqualError(t, err, test.expected.error) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.value, value) - } - }) - } - -} - -func TestGetOrDefaultInt(t *testing.T) { - testCases := []struct { - desc string - envValue string - defaultValue int - expected int - }{ - { - desc: "valid value", - envValue: "100", - defaultValue: 2, - expected: 100, - }, - { - desc: "invalid content, use default value", - envValue: "abc123", - defaultValue: 2, - expected: 2, - }, - { - desc: "valid negative value", - envValue: "-111", - defaultValue: 2, - expected: -111, - }, - { - desc: "float: invalid type, use default value", - envValue: "1.11", - defaultValue: 2, - expected: 2, - }, - } - - const key = "LEGO_ENV_TC" - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer os.Unsetenv(key) - err := os.Setenv(key, test.envValue) - require.NoError(t, err) - - result := GetOrDefaultInt(key, test.defaultValue) - assert.Equal(t, test.expected, result) - }) - } -} - -func TestGetOrDefaultSecond(t *testing.T) { - testCases := []struct { - desc string - envValue string - defaultValue time.Duration - expected time.Duration - }{ - { - desc: "valid value", - envValue: "100", - defaultValue: 2 * time.Second, - expected: 100 * time.Second, - }, - { - desc: "invalid content, use default value", - envValue: "abc123", - defaultValue: 2 * time.Second, - expected: 2 * time.Second, - }, - { - desc: "invalid content, negative value", - envValue: "-111", - defaultValue: 2 * time.Second, - expected: 2 * time.Second, - }, - { - desc: "float: invalid type, use default value", - envValue: "1.11", - defaultValue: 2 * time.Second, - expected: 2 * time.Second, - }, - } - - var key = "LEGO_ENV_TC" - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer os.Unsetenv(key) - err := os.Setenv(key, test.envValue) - require.NoError(t, err) - - result := GetOrDefaultSecond(key, test.defaultValue) - assert.Equal(t, test.expected, result) - }) - } -} - -func TestGetOrDefaultString(t *testing.T) { - testCases := []struct { - desc string - envValue string - defaultValue string - expected string - }{ - { - desc: "missing env var", - defaultValue: "foo", - expected: "foo", - }, - { - desc: "with env var", - envValue: "bar", - defaultValue: "foo", - expected: "bar", - }, - } - - var key = "LEGO_ENV_TC" - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer os.Unsetenv(key) - err := os.Setenv(key, test.envValue) - require.NoError(t, err) - - actual := GetOrDefaultString(key, test.defaultValue) - assert.Equal(t, test.expected, actual) - }) - } -} - -func TestGetOrDefaultBool(t *testing.T) { - testCases := []struct { - desc string - envValue string - defaultValue bool - expected bool - }{ - { - desc: "missing env var", - defaultValue: true, - expected: true, - }, - { - desc: "with env var", - envValue: "true", - defaultValue: false, - expected: true, - }, - { - desc: "invalid value", - envValue: "foo", - defaultValue: false, - expected: false, - }, - } - - var key = "LEGO_ENV_TC" - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer os.Unsetenv(key) - err := os.Setenv(key, test.envValue) - require.NoError(t, err) - - actual := GetOrDefaultBool(key, test.defaultValue) - assert.Equal(t, test.expected, actual) - }) - } -} - -func TestGetOrFile_ReadsEnvVars(t *testing.T) { - err := os.Setenv("TEST_LEGO_ENV_VAR", "lego_env") - require.NoError(t, err) - defer os.Unsetenv("TEST_LEGO_ENV_VAR") - - value := GetOrFile("TEST_LEGO_ENV_VAR") - - assert.Equal(t, "lego_env", value) -} - -func TestGetOrFile_ReadsFiles(t *testing.T) { - varEnvFileName := "TEST_LEGO_ENV_VAR_FILE" - varEnvName := "TEST_LEGO_ENV_VAR" - - testCases := []struct { - desc string - fileContent []byte - }{ - { - desc: "simple", - fileContent: []byte("lego_file"), - }, - { - desc: "with an empty last line", - fileContent: []byte("lego_file\n"), - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - err := os.Unsetenv(varEnvFileName) - require.NoError(t, err) - err = os.Unsetenv(varEnvName) - require.NoError(t, err) - - file, err := ioutil.TempFile("", "lego") - require.NoError(t, err) - defer os.Remove(file.Name()) - - err = ioutil.WriteFile(file.Name(), []byte("lego_file\n"), 0644) - require.NoError(t, err) - - err = os.Setenv(varEnvFileName, file.Name()) - require.NoError(t, err) - defer os.Unsetenv(varEnvFileName) - - value := GetOrFile(varEnvName) - - assert.Equal(t, "lego_file", value) - }) - } -} - -func TestGetOrFile_PrefersEnvVars(t *testing.T) { - varEnvFileName := "TEST_LEGO_ENV_VAR_FILE" - varEnvName := "TEST_LEGO_ENV_VAR" - - err := os.Unsetenv(varEnvFileName) - require.NoError(t, err) - err = os.Unsetenv(varEnvName) - require.NoError(t, err) - - file, err := ioutil.TempFile("", "lego") - require.NoError(t, err) - defer os.Remove(file.Name()) - - err = ioutil.WriteFile(file.Name(), []byte("lego_file"), 0644) - require.NoError(t, err) - - err = os.Setenv(varEnvFileName, file.Name()) - require.NoError(t, err) - defer os.Unsetenv(varEnvFileName) - - err = os.Setenv(varEnvName, "lego_env") - require.NoError(t, err) - defer os.Unsetenv(varEnvName) - - value := GetOrFile(varEnvName) - - assert.Equal(t, "lego_env", value) -} diff --git a/vendor/github.com/go-acme/lego/platform/tester/api.go b/vendor/github.com/go-acme/lego/platform/tester/api.go deleted file mode 100644 index 13f3c82..0000000 --- a/vendor/github.com/go-acme/lego/platform/tester/api.go +++ /dev/null @@ -1,62 +0,0 @@ -package tester - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - - "github.com/go-acme/lego/acme" -) - -// SetupFakeAPI Minimal stub ACME server for validation. -func SetupFakeAPI() (*http.ServeMux, string, func()) { - mux := http.NewServeMux() - ts := httptest.NewServer(mux) - - mux.HandleFunc("/dir", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - err := WriteJSONResponse(w, acme.Directory{ - NewNonceURL: ts.URL + "/nonce", - NewAccountURL: ts.URL + "/account", - NewOrderURL: ts.URL + "/newOrder", - RevokeCertURL: ts.URL + "/revokeCert", - KeyChangeURL: ts.URL + "/keyChange", - }) - - mux.HandleFunc("/nonce", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodHead { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - w.Header().Add("Replay-Nonce", "12345") - w.Header().Add("Retry-After", "0") - }) - - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - return mux, ts.URL, ts.Close -} - -// WriteJSONResponse marshals the body as JSON and writes it to the response. -func WriteJSONResponse(w http.ResponseWriter, body interface{}) error { - bs, err := json.Marshal(body) - if err != nil { - return err - } - - w.Header().Set("Content-Type", "application/json") - if _, err := w.Write(bs); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/platform/tester/env.go b/vendor/github.com/go-acme/lego/platform/tester/env.go deleted file mode 100644 index 943842d..0000000 --- a/vendor/github.com/go-acme/lego/platform/tester/env.go +++ /dev/null @@ -1,147 +0,0 @@ -package tester - -import ( - "fmt" - "os" -) - -// EnvTest Environment variables manager for tests. -type EnvTest struct { - keys []string - values map[string]string - - liveTestHook func() bool - liveTestExtraHook func() bool - - domain string - domainKey string -} - -// NewEnvTest Creates an EnvTest. -func NewEnvTest(keys ...string) *EnvTest { - values := make(map[string]string) - for _, key := range keys { - value := os.Getenv(key) - if value != "" { - values[key] = value - } - } - - return &EnvTest{ - keys: keys, - values: values, - } -} - -// WithDomain Defines the name of the environment variable used to define the domain related to the DNS request. -// If the domain is defined, it was considered mandatory to define a test as a "live" test. -func (e *EnvTest) WithDomain(key string) *EnvTest { - e.domainKey = key - e.domain = os.Getenv(key) - return e -} - -// WithLiveTestRequirements Defines the environment variables required to define a test as a "live" test. -// Replaces the default behavior (all keys are required). -func (e *EnvTest) WithLiveTestRequirements(keys ...string) *EnvTest { - var countValuedVars int - - for _, key := range keys { - if e.domainKey != key && !e.isManagedKey(key) { - panic(fmt.Sprintf("Unauthorized action, the env var %s is not managed or it's not the key of the domain.", key)) - } - - if _, ok := e.values[key]; ok { - countValuedVars++ - } - } - - live := countValuedVars != 0 && len(keys) == countValuedVars - - e.liveTestHook = func() bool { - return live - } - - return e -} - -// WithLiveTestExtra Allows to define an additional condition to flag a test as "live" test. -// This does not replace the default behavior. -func (e *EnvTest) WithLiveTestExtra(extra func() bool) *EnvTest { - e.liveTestExtraHook = extra - return e -} - -// GetDomain Gets the domain value associated with the DNS challenge (linked to WithDomain method). -func (e *EnvTest) GetDomain() string { - return e.domain -} - -// IsLiveTest Checks whether environment variables allow running a "live" test. -func (e *EnvTest) IsLiveTest() bool { - liveTest := e.liveTestExtra() - - if e.liveTestHook != nil { - return liveTest && e.liveTestHook() - } - - liveTest = liveTest && len(e.values) == len(e.keys) - - if liveTest && len(e.domainKey) > 0 && len(e.domain) == 0 { - return false - } - - return liveTest -} - -// RestoreEnv Restores the environment variables to the initial state. -func (e *EnvTest) RestoreEnv() { - for key, value := range e.values { - os.Setenv(key, value) - } -} - -// ClearEnv Deletes all environment variables related to the test. -func (e *EnvTest) ClearEnv() { - for _, key := range e.keys { - os.Unsetenv(key) - } -} - -// GetValue Gets the stored value of an environment variable. -func (e *EnvTest) GetValue(key string) string { - return e.values[key] -} - -func (e *EnvTest) liveTestExtra() bool { - if e.liveTestExtraHook == nil { - return true - } - - return e.liveTestExtraHook() -} - -// Apply Sets/Unsets environment variables. -// Not related to the main environment variables. -func (e *EnvTest) Apply(envVars map[string]string) { - for key, value := range envVars { - if !e.isManagedKey(key) { - panic(fmt.Sprintf("Unauthorized action, the env var %s is not managed.", key)) - } - - if len(value) == 0 { - os.Unsetenv(key) - } else { - os.Setenv(key, value) - } - } -} - -func (e *EnvTest) isManagedKey(varName string) bool { - for _, key := range e.keys { - if key == varName { - return true - } - } - return false -} diff --git a/vendor/github.com/go-acme/lego/platform/tester/env_test.go b/vendor/github.com/go-acme/lego/platform/tester/env_test.go deleted file mode 100644 index 2785c5d..0000000 --- a/vendor/github.com/go-acme/lego/platform/tester/env_test.go +++ /dev/null @@ -1,347 +0,0 @@ -package tester_test - -import ( - "os" - "strings" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" -) - -const ( - envNamespace = "LEGO_TEST_" - envVar01 = envNamespace + "01" - envVar02 = envNamespace + "02" - envVarDomain = envNamespace + "DOMAIN" -) - -func TestMain(m *testing.M) { - exitCode := m.Run() - clearEnv() - os.Exit(exitCode) -} - -func applyEnv(envVars map[string]string) { - for key, value := range envVars { - if len(value) == 0 { - os.Unsetenv(key) - } else { - os.Setenv(key, value) - } - } -} - -func clearEnv() { - environ := os.Environ() - for _, key := range environ { - if strings.HasPrefix(key, envNamespace) { - os.Unsetenv(strings.Split(key, "=")[0]) - } - } - os.Unsetenv("EXTRA_LEGO_TEST") -} - -func TestEnvTest(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - envTestSetup func() *tester.EnvTest - expected func(t *testing.T, envTest *tester.EnvTest) - }{ - { - desc: "simple", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "missing env var", - envVars: map[string]string{ - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithDomain", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - envVarDomain: "D", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02).WithDomain(envVarDomain) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetValue(envVarDomain)) - assert.Equal(t, "D", envTest.GetDomain()) - }, - }, - { - desc: "WithDomain missing env var", - envVars: map[string]string{ - envVar01: "A", - envVarDomain: "D", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02).WithDomain(envVarDomain) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetValue(envVarDomain)) - assert.Equal(t, "D", envTest.GetDomain()) - }, - }, - { - desc: "WithDomain missing domain", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02).WithDomain(envVarDomain) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetValue(envVarDomain)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02).WithLiveTestRequirements(envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements non required var missing", - envVars: map[string]string{ - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02).WithLiveTestRequirements(envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements required var missing", - envVars: map[string]string{ - envVar01: "A", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02).WithLiveTestRequirements(envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements WithDomain", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - envVarDomain: "D", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithDomain(envVarDomain). - WithLiveTestRequirements(envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetValue(envVarDomain)) - assert.Equal(t, "D", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements WithDomain without domain", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithDomain(envVarDomain). - WithLiveTestRequirements(envVar02) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetValue(envVarDomain)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestExtra true", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithLiveTestExtra(func() bool { return true }) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestExtra false", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithLiveTestExtra(func() bool { return false }) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements WithLiveTestExtra true", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithLiveTestRequirements(envVar02). - WithLiveTestExtra(func() bool { return true }) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.True(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements WithLiveTestExtra false", - envVars: map[string]string{ - envVar01: "A", - envVar02: "B", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithLiveTestRequirements(envVar02). - WithLiveTestExtra(func() bool { return false }) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "B", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - { - desc: "WithLiveTestRequirements require env var missing WithLiveTestExtra true", - envVars: map[string]string{ - envVar01: "A", - }, - envTestSetup: func() *tester.EnvTest { - return tester.NewEnvTest(envVar01, envVar02). - WithLiveTestRequirements(envVar02). - WithLiveTestExtra(func() bool { return true }) - }, - expected: func(t *testing.T, envTest *tester.EnvTest) { - assert.False(t, envTest.IsLiveTest()) - assert.Equal(t, "A", envTest.GetValue(envVar01)) - assert.Equal(t, "", envTest.GetValue(envVar02)) - assert.Equal(t, "", envTest.GetDomain()) - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer clearEnv() - applyEnv(test.envVars) - - envTest := test.envTestSetup() - - test.expected(t, envTest) - }) - } -} - -func TestEnvTest_RestoreEnv(t *testing.T) { - os.Setenv(envVar01, "A") - os.Setenv(envVar02, "B") - - envTest := tester.NewEnvTest(envVar01, envVar02) - - clearEnv() - - envTest.RestoreEnv() - - assert.Equal(t, "A", os.Getenv(envVar01)) - assert.Equal(t, "B", os.Getenv(envVar02)) -} - -func TestEnvTest_ClearEnv(t *testing.T) { - os.Setenv(envVar01, "A") - os.Setenv(envVar02, "B") - os.Setenv("EXTRA_LEGO_TEST", "X") - - envTest := tester.NewEnvTest(envVar01, envVar02) - - envTest.ClearEnv() - - assert.Equal(t, "", os.Getenv(envVar01)) - assert.Equal(t, "", os.Getenv(envVar02)) - assert.Equal(t, "X", os.Getenv("EXTRA_LEGO_TEST")) -} diff --git a/vendor/github.com/go-acme/lego/platform/wait/wait.go b/vendor/github.com/go-acme/lego/platform/wait/wait.go deleted file mode 100644 index 97af5dc..0000000 --- a/vendor/github.com/go-acme/lego/platform/wait/wait.go +++ /dev/null @@ -1,33 +0,0 @@ -package wait - -import ( - "fmt" - "time" - - "github.com/go-acme/lego/log" -) - -// For polls the given function 'f', once every 'interval', up to 'timeout'. -func For(msg string, timeout, interval time.Duration, f func() (bool, error)) error { - log.Infof("Wait for %s [timeout: %s, interval: %s]", msg, timeout, interval) - - var lastErr string - timeUp := time.After(timeout) - for { - select { - case <-timeUp: - return fmt.Errorf("time limit exceeded: last error: %s", lastErr) - default: - } - - stop, err := f() - if stop { - return nil - } - if err != nil { - lastErr = err.Error() - } - - time.Sleep(interval) - } -} diff --git a/vendor/github.com/go-acme/lego/platform/wait/wait_test.go b/vendor/github.com/go-acme/lego/platform/wait/wait_test.go deleted file mode 100644 index fc6673c..0000000 --- a/vendor/github.com/go-acme/lego/platform/wait/wait_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package wait - -import ( - "testing" - "time" -) - -func TestForTimeout(t *testing.T) { - c := make(chan error) - go func() { - err := For("", 3*time.Second, 1*time.Second, func() (bool, error) { - return false, nil - }) - c <- err - }() - - timeout := time.After(4 * time.Second) - select { - case <-timeout: - t.Fatal("timeout exceeded") - case err := <-c: - if err == nil { - t.Errorf("expected timeout error; got %v", err) - } - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.go b/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.go deleted file mode 100644 index 3edac78..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.go +++ /dev/null @@ -1,162 +0,0 @@ -// Package acmedns implements a DNS provider for solving DNS-01 challenges using Joohoi's acme-dns project. -// For more information see the ACME-DNS homepage: https://github.com/joohoi/acme-dns -package acmedns - -import ( - "errors" - "fmt" - - "github.com/cpu/goacmedns" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - // envNamespace is the prefix for ACME-DNS environment variables. - envNamespace = "ACME_DNS_" - // apiBaseEnvVar is the environment variable name for the ACME-DNS API address - // (e.g. https://acmedns.your-domain.com). - apiBaseEnvVar = envNamespace + "API_BASE" - // storagePathEnvVar is the environment variable name for the ACME-DNS JSON account data file. - // A per-domain account will be registered/persisted to this file and used for TXT updates. - storagePathEnvVar = envNamespace + "STORAGE_PATH" -) - -// acmeDNSClient is an interface describing the goacmedns.Client functions the DNSProvider uses. -// It makes it easier for tests to shim a mock Client into the DNSProvider. -type acmeDNSClient interface { - // UpdateTXTRecord updates the provided account's TXT record - // to the given value or returns an error. - UpdateTXTRecord(goacmedns.Account, string) error - // RegisterAccount registers and returns a new account - // with the given allowFrom restriction or returns an error. - RegisterAccount([]string) (goacmedns.Account, error) -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface for -// an ACME-DNS server. -type DNSProvider struct { - client acmeDNSClient - storage goacmedns.Storage -} - -// NewDNSProvider creates an ACME-DNS provider using file based account storage. -// Its configuration is loaded from the environment by reading apiBaseEnvVar and storagePathEnvVar. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(apiBaseEnvVar, storagePathEnvVar) - if err != nil { - return nil, fmt.Errorf("acme-dns: %v", err) - } - - client := goacmedns.NewClient(values[apiBaseEnvVar]) - storage := goacmedns.NewFileStorage(values[storagePathEnvVar], 0600) - return NewDNSProviderClient(client, storage) -} - -// NewDNSProviderClient creates an ACME-DNS DNSProvider with the given acmeDNSClient and goacmedns.Storage. -func NewDNSProviderClient(client acmeDNSClient, storage goacmedns.Storage) (*DNSProvider, error) { - if client == nil { - return nil, errors.New("ACME-DNS Client must be not nil") - } - - if storage == nil { - return nil, errors.New("ACME-DNS Storage must be not nil") - } - - return &DNSProvider{ - client: client, - storage: storage, - }, nil -} - -// ErrCNAMERequired is returned by Present when the Domain indicated had no -// existing ACME-DNS account in the Storage and additional setup is required. -// The user must create a CNAME in the DNS zone for Domain that aliases FQDN -// to Target in order to complete setup for the ACME-DNS account that was created. -type ErrCNAMERequired struct { - // The Domain that is being issued for. - Domain string - // The alias of the CNAME (left hand DNS label). - FQDN string - // The RDATA of the CNAME (right hand side, canonical name). - Target string -} - -// Error returns a descriptive message for the ErrCNAMERequired instance telling -// the user that a CNAME needs to be added to the DNS zone of c.Domain before -// the ACME-DNS hook will work. The CNAME to be created should be of the form: -// {{ c.FQDN }} CNAME {{ c.Target }} -func (e ErrCNAMERequired) Error() string { - return fmt.Sprintf("acme-dns: new account created for %q. "+ - "To complete setup for %q you must provision the following "+ - "CNAME in your DNS zone and re-run this provider when it is "+ - "in place:\n"+ - "%s CNAME %s.", - e.Domain, e.Domain, e.FQDN, e.Target) -} - -// Present creates a TXT record to fulfill the DNS-01 challenge. -// If there is an existing account for the domain in the provider's storage -// then it will be used to set the challenge response TXT record with the ACME-DNS server and issuance will continue. -// If there is not an account for the given domain present in the DNSProvider storage -// one will be created and registered with the ACME DNS server and an ErrCNAMERequired error is returned. -// This will halt issuance and indicate to the user that a one-time manual setup is required for the domain. -func (d *DNSProvider) Present(domain, _, keyAuth string) error { - // Compute the challenge response FQDN and TXT value for the domain based - // on the keyAuth. - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // Check if credentials were previously saved for this domain. - account, err := d.storage.Fetch(domain) - // Errors other than goacmeDNS.ErrDomainNotFound are unexpected. - if err != nil && err != goacmedns.ErrDomainNotFound { - return err - } - if err == goacmedns.ErrDomainNotFound { - // The account did not exist. Create a new one and return an error - // indicating the required one-time manual CNAME setup. - return d.register(domain, fqdn) - } - - // Update the acme-dns TXT record. - return d.client.UpdateTXTRecord(account, value) -} - -// CleanUp removes the record matching the specified parameters. It is not -// implemented for the ACME-DNS provider. -func (d *DNSProvider) CleanUp(_, _, _ string) error { - // ACME-DNS doesn't support the notion of removing a record. - // For users of ACME-DNS it is expected the stale records remain in-place. - return nil -} - -// register creates a new ACME-DNS account for the given domain. -// If account creation works as expected a ErrCNAMERequired error is returned describing -// the one-time manual CNAME setup required to complete setup of the ACME-DNS hook for the domain. -// If any other error occurs it is returned as-is. -func (d *DNSProvider) register(domain, fqdn string) error { - // TODO(@cpu): Read CIDR whitelists from the environment - newAcct, err := d.client.RegisterAccount(nil) - if err != nil { - return err - } - - // Store the new account in the storage and call save to persist the data. - err = d.storage.Put(domain, newAcct) - if err != nil { - return err - } - err = d.storage.Save() - if err != nil { - return err - } - - // Stop issuance by returning an error. - // The user needs to perform a manual one-time CNAME setup in their DNS zone - // to complete the setup of the new account we created. - return ErrCNAMERequired{ - Domain: domain, - FQDN: fqdn, - Target: newAcct.FullDomain, - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.toml b/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.toml deleted file mode 100644 index 2fb4a0d..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.toml +++ /dev/null @@ -1,16 +0,0 @@ -Name = "Joohoi's ACME-DNS" -Description = '''''' -URL = "https://github.com/joohoi/acme-dns" -Code = "acme-dns" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - ACME_DNS_API_BASE = "The ACME-DNS API address" - ACME_DNS_STORAGE_PATH = "The ACME-DNS JSON account data file. A per-domain account will be registered/persisted to this file and used for TXT updates." - -[Links] - API = "https://github.com/joohoi/acme-dns#api" - GoClient = "https://github.com/cpu/goacmedns" diff --git a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns_test.go b/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns_test.go deleted file mode 100644 index 07b554b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns_test.go +++ /dev/null @@ -1,278 +0,0 @@ -package acmedns - -import ( - "errors" - "testing" - - "github.com/cpu/goacmedns" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var ( - // errorClientErr is used by the Client mocks that return an error. - errorClientErr = errors.New("errorClient always errors") - // errorStorageErr is used by the Storage mocks that return an error. - errorStorageErr = errors.New("errorStorage always errors") -) - -const ( - // Fixed test data for unit tests. - egDomain = "threeletter.agency" - egFQDN = "_acme-challenge." + egDomain + "." - egKeyAuth = "⚷" -) - -var egTestAccount = goacmedns.Account{ - FullDomain: "acme-dns." + egDomain, - SubDomain: "random-looking-junk." + egDomain, - Username: "spooky.mulder", - Password: "trustno1", -} - -// mockClient is a mock implementing the acmeDNSClient interface that always -// returns a fixed goacmedns.Account from calls to Register. -type mockClient struct { - mockAccount goacmedns.Account -} - -// UpdateTXTRecord does nothing. -func (c mockClient) UpdateTXTRecord(_ goacmedns.Account, _ string) error { - return nil -} - -// RegisterAccount returns c.mockAccount and no errors. -func (c mockClient) RegisterAccount(_ []string) (goacmedns.Account, error) { - return c.mockAccount, nil -} - -// mockUpdateClient is a mock implementing the acmeDNSClient interface that -// tracks the calls to UpdateTXTRecord in the records map. -type mockUpdateClient struct { - mockClient - records map[goacmedns.Account]string -} - -// UpdateTXTRecord saves a record value to c.records for the given acct. -func (c mockUpdateClient) UpdateTXTRecord(acct goacmedns.Account, value string) error { - c.records[acct] = value - return nil -} - -// errorRegisterClient is a mock implementing the acmeDNSClient interface that always -// returns errors from errorUpdateClient. -type errorUpdateClient struct { - mockClient -} - -// UpdateTXTRecord always returns an error. -func (c errorUpdateClient) UpdateTXTRecord(_ goacmedns.Account, _ string) error { - return errorClientErr -} - -// errorRegisterClient is a mock implementing the acmeDNSClient interface that always -// returns errors from RegisterAccount. -type errorRegisterClient struct { - mockClient -} - -// RegisterAccount always returns an error. -func (c errorRegisterClient) RegisterAccount(_ []string) (goacmedns.Account, error) { - return goacmedns.Account{}, errorClientErr -} - -// mockStorage is a mock implementing the goacmedns.Storage interface that -// returns static account data and ignores Save. -type mockStorage struct { - accounts map[string]goacmedns.Account -} - -// Save does nothing. -func (m mockStorage) Save() error { - return nil -} - -// Put stores an account for the given domain in m.accounts. -func (m mockStorage) Put(domain string, acct goacmedns.Account) error { - m.accounts[domain] = acct - return nil -} - -// Fetch retrieves an account for the given domain from m.accounts or returns -// goacmedns.ErrDomainNotFound. -func (m mockStorage) Fetch(domain string) (goacmedns.Account, error) { - if acct, ok := m.accounts[domain]; ok { - return acct, nil - } - return goacmedns.Account{}, goacmedns.ErrDomainNotFound -} - -// errorPutStorage is a mock implementing the goacmedns.Storage interface that -// always returns errors from Put. -type errorPutStorage struct { - mockStorage -} - -// Put always errors. -func (e errorPutStorage) Put(_ string, _ goacmedns.Account) error { - return errorStorageErr -} - -// errorSaveStorage is a mock implementing the goacmedns.Storage interface that -// always returns errors from Save. -type errorSaveStorage struct { - mockStorage -} - -// Save always errors. -func (e errorSaveStorage) Save() error { - return errorStorageErr -} - -// errorFetchStorage is a mock implementing the goacmedns.Storage interface that -// always returns errors from Fetch. -type errorFetchStorage struct { - mockStorage -} - -// Fetch always errors. -func (e errorFetchStorage) Fetch(_ string) (goacmedns.Account, error) { - return goacmedns.Account{}, errorStorageErr -} - -// TestPresent tests that the ACME-DNS Present function for updating a DNS-01 -// challenge response TXT record works as expected. -func TestPresent(t *testing.T) { - // validAccountStorage is a mockStorage configured to return the egTestAccount. - validAccountStorage := mockStorage{ - map[string]goacmedns.Account{ - egDomain: egTestAccount, - }, - } - // validUpdateClient is a mockClient configured with the egTestAccount that will - // track TXT updates in a map. - validUpdateClient := mockUpdateClient{ - mockClient{egTestAccount}, - make(map[goacmedns.Account]string), - } - - testCases := []struct { - Name string - Client acmeDNSClient - Storage goacmedns.Storage - ExpectedError error - }{ - { - Name: "present when client storage returns unexpected error", - Client: mockClient{egTestAccount}, - Storage: errorFetchStorage{}, - ExpectedError: errorStorageErr, - }, - { - Name: "present when client storage returns ErrDomainNotFound", - Client: mockClient{egTestAccount}, - ExpectedError: ErrCNAMERequired{ - Domain: egDomain, - FQDN: egFQDN, - Target: egTestAccount.FullDomain, - }, - }, - { - Name: "present when client UpdateTXTRecord returns unexpected error", - Client: errorUpdateClient{}, - Storage: validAccountStorage, - ExpectedError: errorClientErr, - }, - { - Name: "present when everything works", - Storage: validAccountStorage, - Client: validUpdateClient, - }, - } - - for _, test := range testCases { - t.Run(test.Name, func(t *testing.T) { - dp, err := NewDNSProviderClient(test.Client, mockStorage{make(map[string]goacmedns.Account)}) - require.NoError(t, err) - - // override the storage mock if required by the test case. - if test.Storage != nil { - dp.storage = test.Storage - } - - // call Present. The token argument can be garbage because the ACME-DNS - // provider does not use it. - err = dp.Present(egDomain, "foo", egKeyAuth) - if test.ExpectedError != nil { - assert.Equal(t, test.ExpectedError, err) - } else { - require.NoError(t, err) - } - }) - } - - // Check that the success test case set a record. - assert.Len(t, validUpdateClient.records, 1) - - // Check that the success test case set the right record for the right account. - assert.Len(t, validUpdateClient.records[egTestAccount], 43) -} - -// TestRegister tests that the ACME-DNS register function works correctly. -func TestRegister(t *testing.T) { - testCases := []struct { - Name string - Client acmeDNSClient - Storage goacmedns.Storage - Domain string - FQDN string - ExpectedError error - }{ - { - Name: "register when acme-dns client returns an error", - Client: errorRegisterClient{}, - ExpectedError: errorClientErr, - }, - { - Name: "register when acme-dns storage put returns an error", - Client: mockClient{egTestAccount}, - Storage: errorPutStorage{mockStorage{make(map[string]goacmedns.Account)}}, - ExpectedError: errorStorageErr, - }, - { - Name: "register when acme-dns storage save returns an error", - Client: mockClient{egTestAccount}, - Storage: errorSaveStorage{mockStorage{make(map[string]goacmedns.Account)}}, - ExpectedError: errorStorageErr, - }, - { - Name: "register when everything works", - Client: mockClient{egTestAccount}, - ExpectedError: ErrCNAMERequired{ - Domain: egDomain, - FQDN: egFQDN, - Target: egTestAccount.FullDomain, - }, - }, - } - - for _, test := range testCases { - t.Run(test.Name, func(t *testing.T) { - dp, err := NewDNSProviderClient(test.Client, mockStorage{make(map[string]goacmedns.Account)}) - require.NoError(t, err) - - // override the storage mock if required by the testcase. - if test.Storage != nil { - dp.storage = test.Storage - } - - // Call register for the example domain/fqdn. - err = dp.register(egDomain, egFQDN) - if test.ExpectedError != nil { - assert.Equal(t, test.ExpectedError, err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.go b/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.go deleted file mode 100644 index 76c8ec7..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.go +++ /dev/null @@ -1,220 +0,0 @@ -// Package alidns implements a DNS provider for solving the DNS-01 challenge using Alibaba Cloud DNS. -package alidns - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/services/alidns" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultRegionID = "cn-hangzhou" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - SecretKey string - RegionID string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPTimeout time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("ALICLOUD_TTL", 600), - PropagationTimeout: env.GetOrDefaultSecond("ALICLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("ALICLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPTimeout: env.GetOrDefaultSecond("ALICLOUD_HTTP_TIMEOUT", 10*time.Second), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *alidns.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Alibaba Cloud DNS. -// Credentials must be passed in the environment variables: ALICLOUD_ACCESS_KEY and ALICLOUD_SECRET_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("ALICLOUD_ACCESS_KEY", "ALICLOUD_SECRET_KEY") - if err != nil { - return nil, fmt.Errorf("alicloud: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["ALICLOUD_ACCESS_KEY"] - config.SecretKey = values["ALICLOUD_SECRET_KEY"] - config.RegionID = env.GetOrFile("ALICLOUD_REGION_ID") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for alidns. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("alicloud: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" || config.SecretKey == "" { - return nil, fmt.Errorf("alicloud: credentials missing") - } - - if len(config.RegionID) == 0 { - config.RegionID = defaultRegionID - } - - conf := sdk.NewConfig().WithTimeout(config.HTTPTimeout) - credential := credentials.NewAccessKeyCredential(config.APIKey, config.SecretKey) - - client, err := alidns.NewClientWithOptions(config.RegionID, conf, credential) - if err != nil { - return nil, fmt.Errorf("alicloud: credentials failed: %v", err) - } - - return &DNSProvider{config: config, client: client}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - _, zoneName, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - - recordAttributes := d.newTxtRecord(zoneName, fqdn, value) - - _, err = d.client.AddDomainRecord(recordAttributes) - if err != nil { - return fmt.Errorf("alicloud: API call failed: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - - _, _, err = d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - - for _, rec := range records { - request := alidns.CreateDeleteDomainRecordRequest() - request.RecordId = rec.RecordId - _, err = d.client.DeleteDomainRecord(request) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - } - return nil -} - -func (d *DNSProvider) getHostedZone(domain string) (string, string, error) { - request := alidns.CreateDescribeDomainsRequest() - - var domains []alidns.Domain - startPage := 1 - - for { - request.PageNumber = requests.NewInteger(startPage) - - response, err := d.client.DescribeDomains(request) - if err != nil { - return "", "", fmt.Errorf("API call failed: %v", err) - } - - domains = append(domains, response.Domains.Domain...) - - if response.PageNumber*response.PageSize >= response.TotalCount { - break - } - - startPage++ - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - - var hostedZone alidns.Domain - for _, zone := range domains { - if zone.DomainName == dns01.UnFqdn(authZone) { - hostedZone = zone - } - } - - if hostedZone.DomainId == "" { - return "", "", fmt.Errorf("zone %s not found in AliDNS for domain %s", authZone, domain) - } - return fmt.Sprintf("%v", hostedZone.DomainId), hostedZone.DomainName, nil -} - -func (d *DNSProvider) newTxtRecord(zone, fqdn, value string) *alidns.AddDomainRecordRequest { - request := alidns.CreateAddDomainRecordRequest() - request.Type = "TXT" - request.DomainName = zone - request.RR = d.extractRecordName(fqdn, zone) - request.Value = value - request.TTL = requests.NewInteger(d.config.TTL) - return request -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) ([]alidns.Record, error) { - _, zoneName, err := d.getHostedZone(domain) - if err != nil { - return nil, err - } - - request := alidns.CreateDescribeDomainRecordsRequest() - request.DomainName = zoneName - request.PageSize = requests.NewInteger(500) - - var records []alidns.Record - - result, err := d.client.DescribeDomainRecords(request) - if err != nil { - return records, fmt.Errorf("API call has failed: %v", err) - } - - recordName := d.extractRecordName(fqdn, zoneName) - for _, record := range result.DomainRecords.Record { - if record.RR == recordName { - records = append(records, record) - } - } - return records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.toml b/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.toml deleted file mode 100644 index 4f613f9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Alibaba Cloud DNS" -Description = '''''' -URL = "https://www.alibabacloud.com/product/dns" -Code = "alidns" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - ALICLOUD_ACCESS_KEY = "Access key ID" - ALICLOUD_SECRET_KEY = "Access Key secret" - [Configuration.Additional] - ALICLOUD_POLLING_INTERVAL = "Time between DNS propagation check" - ALICLOUD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - ALICLOUD_TTL = "The TTL of the TXT record used for the DNS challenge" - ALICLOUD_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.alibabacloud.com/help/doc-detail/42875.htm" - GoClient = "https://github.com/aliyun/alibaba-cloud-sdk-go" diff --git a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns_test.go b/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns_test.go deleted file mode 100644 index e0284f0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package alidns - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "ALICLOUD_ACCESS_KEY", - "ALICLOUD_SECRET_KEY"). - WithDomain("ALICLOUD_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "ALICLOUD_ACCESS_KEY": "123", - "ALICLOUD_SECRET_KEY": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "ALICLOUD_ACCESS_KEY": "", - "ALICLOUD_SECRET_KEY": "", - }, - expected: "alicloud: some credentials information are missing: ALICLOUD_ACCESS_KEY,ALICLOUD_SECRET_KEY", - }, - { - desc: "missing access key", - envVars: map[string]string{ - "ALICLOUD_ACCESS_KEY": "", - "ALICLOUD_SECRET_KEY": "456", - }, - expected: "alicloud: some credentials information are missing: ALICLOUD_ACCESS_KEY", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "ALICLOUD_ACCESS_KEY": "123", - "ALICLOUD_SECRET_KEY": "", - }, - expected: "alicloud: some credentials information are missing: ALICLOUD_SECRET_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - secretKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - secretKey: "456", - }, - { - desc: "missing credentials", - expected: "alicloud: credentials missing", - }, - { - desc: "missing api key", - secretKey: "456", - expected: "alicloud: credentials missing", - }, - { - desc: "missing secret key", - apiKey: "123", - expected: "alicloud: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.SecretKey = test.secretKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.go b/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.go deleted file mode 100644 index 0d46f58..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.go +++ /dev/null @@ -1,191 +0,0 @@ -// Package auroradns implements a DNS provider for solving the DNS-01 challenge using Aurora DNS. -package auroradns - -import ( - "errors" - "fmt" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/nrdcg/auroradns" -) - -const defaultBaseURL = "https://api.auroradns.eu" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - UserID string - Key string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("AURORA_TTL", 300), - PropagationTimeout: env.GetOrDefaultSecond("AURORA_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("AURORA_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider describes a provider for AuroraDNS -type DNSProvider struct { - recordIDs map[string]string - recordIDsMu sync.Mutex - config *Config - client *auroradns.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for AuroraDNS. -// Credentials must be passed in the environment variables: -// AURORA_USER_ID and AURORA_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("AURORA_USER_ID", "AURORA_KEY") - if err != nil { - return nil, fmt.Errorf("aurora: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = env.GetOrFile("AURORA_ENDPOINT") - config.UserID = values["AURORA_USER_ID"] - config.Key = values["AURORA_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for AuroraDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("aurora: the configuration of the DNS provider is nil") - } - - if config.UserID == "" || config.Key == "" { - return nil, errors.New("aurora: some credentials information are missing") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - tr, err := auroradns.NewTokenTransport(config.UserID, config.Key) - if err != nil { - return nil, fmt.Errorf("aurora: %v", err) - } - - client, err := auroradns.NewClient(tr.Client(), auroradns.WithBaseURL(config.BaseURL)) - if err != nil { - return nil, fmt.Errorf("aurora: %v", err) - } - - return &DNSProvider{ - config: config, - client: client, - recordIDs: make(map[string]string), - }, nil -} - -// Present creates a record with a secret -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("aurora: could not determine zone for domain: '%s'. %s", domain, err) - } - - // 1. Aurora will happily create the TXT record when it is provided a fqdn, - // but it will only appear in the control panel and will not be - // propagated to DNS servers. Extract and use subdomain instead. - // 2. A trailing dot in the fqdn will cause Aurora to add a trailing dot to - // the subdomain, resulting in _acme-challenge.. rather - // than _acme-challenge. - - subdomain := fqdn[0 : len(fqdn)-len(authZone)-1] - - authZone = dns01.UnFqdn(authZone) - - zone, err := d.getZoneInformationByName(authZone) - if err != nil { - return fmt.Errorf("aurora: could not create record: %v", err) - } - - record := auroradns.Record{ - RecordType: "TXT", - Name: subdomain, - Content: value, - TTL: d.config.TTL, - } - - newRecord, _, err := d.client.CreateRecord(zone.ID, record) - if err != nil { - return fmt.Errorf("aurora: could not create record: %v", err) - } - - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = newRecord.ID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes a given record that was generated by Present -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - d.recordIDsMu.Lock() - recordID, ok := d.recordIDs[fqdn] - d.recordIDsMu.Unlock() - - if !ok { - return fmt.Errorf("unknown recordID for %q", fqdn) - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("could not determine zone for domain: %q. %v", domain, err) - } - - authZone = dns01.UnFqdn(authZone) - - zone, err := d.getZoneInformationByName(authZone) - if err != nil { - return err - } - - _, _, err = d.client.DeleteRecord(zone.ID, recordID) - if err != nil { - return err - } - - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getZoneInformationByName(name string) (auroradns.Zone, error) { - zs, _, err := d.client.ListZones() - if err != nil { - return auroradns.Zone{}, err - } - - for _, element := range zs { - if element.Name == name { - return element, nil - } - } - - return auroradns.Zone{}, fmt.Errorf("could not find Zone record") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.toml b/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.toml deleted file mode 100644 index be2e946..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Aurora DNS" -Description = '''''' -URL = "https://www.pcextreme.com/aurora/dns" -Code = "auroradns" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - AURORA_USER_ID = "User ID" - AURORA_KEY = "User API key" - AURORA_ENDPOINT = "API endpoint URL" - [Configuration.Additional] - AURORA_POLLING_INTERVAL = "Time between DNS propagation check" - AURORA_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - AURORA_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://libcloud.readthedocs.io/en/latest/dns/drivers/auroradns.html#api-docs" - GoClient = "https://github.com/nrdcg/auroradns" diff --git a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns_test.go b/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns_test.go deleted file mode 100644 index 3d2c2c8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns_test.go +++ /dev/null @@ -1,224 +0,0 @@ -package auroradns - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "AURORA_USER_ID", - "AURORA_KEY", -) - -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) - - config := NewDefaultConfig() - config.UserID = "asdf1234" - config.Key = "key" - config.BaseURL = server.URL - - provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } - - return provider, handler, server.Close -} - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "AURORA_USER_ID": "123", - "AURORA_KEY": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "AURORA_USER_ID": "", - "AURORA_KEY": "", - }, - expected: "aurora: some credentials information are missing: AURORA_USER_ID,AURORA_KEY", - }, - { - desc: "missing user id", - envVars: map[string]string{ - "AURORA_USER_ID": "", - "AURORA_KEY": "456", - }, - expected: "aurora: some credentials information are missing: AURORA_USER_ID", - }, - { - desc: "missing key", - envVars: map[string]string{ - "AURORA_USER_ID": "123", - "AURORA_KEY": "", - }, - expected: "aurora: some credentials information are missing: AURORA_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - userID string - key string - expected string - }{ - { - desc: "success", - userID: "123", - key: "456", - }, - { - desc: "missing credentials", - userID: "", - key: "", - expected: "aurora: some credentials information are missing", - }, - { - desc: "missing user id", - userID: "", - key: "456", - expected: "aurora: some credentials information are missing", - }, - { - desc: "missing key", - userID: "123", - key: "", - expected: "aurora: some credentials information are missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.UserID = test.userID - config.Key = test.key - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method, "method") - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `[{ - "id": "c56a4180-65aa-42ec-a945-5fd21dec0538", - "name": "example.com" - }]`) - }) - - mux.HandleFunc("/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") - - reqBody, err := ioutil.ReadAll(r.Body) - require.NoError(t, err) - assert.Equal(t, `{"type":"TXT","name":"_acme-challenge","content":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":300}`, string(reqBody)) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{ - "id": "c56a4180-65aa-42ec-a945-5fd21dec0538", - "type": "TXT", - "name": "_acme-challenge", - "ttl": 300 - }`) - }) - - err := provider.Present("example.com", "", "foobar") - require.NoError(t, err, "fail to create TXT record") -} - -func TestDNSProvider_CleanUp(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `[{ - "id": "c56a4180-65aa-42ec-a945-5fd21dec0538", - "name": "example.com" - }]`) - }) - - mux.HandleFunc("/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{ - "id": "ec56a4180-65aa-42ec-a945-5fd21dec0538", - "type": "TXT", - "name": "_acme-challenge", - "ttl": 300 - }`) - }) - - mux.HandleFunc("/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records/ec56a4180-65aa-42ec-a945-5fd21dec0538", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodDelete, r.Method) - - assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{}`) - }) - - err := provider.Present("example.com", "", "foobar") - require.NoError(t, err, "fail to create TXT record") - - err = provider.CleanUp("example.com", "", "foobar") - require.NoError(t, err, "fail to remove TXT record") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/azure/azure.go b/vendor/github.com/go-acme/lego/providers/dns/azure/azure.go deleted file mode 100644 index f10bfc9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/azure/azure.go +++ /dev/null @@ -1,274 +0,0 @@ -// Package azure implements a DNS provider for solving the DNS-01 challenge using azure DNS. -// Azure doesn't like trailing dots on domain names, most of the acme code does. -package azure - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/azure/auth" - "github.com/Azure/go-autorest/autorest/to" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultMetadataEndpoint = "http://169.254.169.254" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - // optional if using instance metadata service - ClientID string - ClientSecret string - TenantID string - - SubscriptionID string - ResourceGroup string - - MetadataEndpoint string - - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("AZURE_TTL", 60), - PropagationTimeout: env.GetOrDefaultSecond("AZURE_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("AZURE_POLLING_INTERVAL", 2*time.Second), - MetadataEndpoint: env.GetOrFile("AZURE_METADATA_ENDPOINT"), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - authorizer autorest.Authorizer -} - -// NewDNSProvider returns a DNSProvider instance configured for azure. -// Credentials can be passed in the environment variables: -// AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_RESOURCE_GROUP -// If the credentials are _not_ set via the environment, -// then it will attempt to get a bearer token via the instance metadata service. -// see: https://github.com/Azure/go-autorest/blob/v10.14.0/autorest/azure/auth/auth.go#L38-L42 -func NewDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - config.SubscriptionID = env.GetOrFile("AZURE_SUBSCRIPTION_ID") - config.ResourceGroup = env.GetOrFile("AZURE_RESOURCE_GROUP") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Azure. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("azure: the configuration of the DNS provider is nil") - } - - if config.HTTPClient == nil { - config.HTTPClient = http.DefaultClient - } - - authorizer, err := getAuthorizer(config) - if err != nil { - return nil, err - } - - if config.SubscriptionID == "" { - subsID, err := getMetadata(config, "subscriptionId") - if err != nil { - return nil, fmt.Errorf("azure: %v", err) - } - - if subsID == "" { - return nil, errors.New("azure: SubscriptionID is missing") - } - config.SubscriptionID = subsID - } - - if config.ResourceGroup == "" { - resGroup, err := getMetadata(config, "resourceGroupName") - if err != nil { - return nil, fmt.Errorf("azure: %v", err) - } - - if resGroup == "" { - return nil, errors.New("azure: ResourceGroup is missing") - } - config.ResourceGroup = resGroup - } - - return &DNSProvider{config: config, authorizer: authorizer}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZoneID(ctx, fqdn) - if err != nil { - return fmt.Errorf("azure: %v", err) - } - - rsc := dns.NewRecordSetsClient(d.config.SubscriptionID) - rsc.Authorizer = d.authorizer - - relative := toRelativeRecord(fqdn, dns01.ToFqdn(zone)) - - // Get existing record set - rset, err := rsc.Get(ctx, d.config.ResourceGroup, zone, relative, dns.TXT) - if err != nil { - detailedError, ok := err.(autorest.DetailedError) - if !ok || detailedError.StatusCode != http.StatusNotFound { - return fmt.Errorf("azure: %v", err) - } - } - - // Construct unique TXT records using map - uniqRecords := map[string]struct{}{value: {}} - if rset.RecordSetProperties != nil && rset.TxtRecords != nil { - for _, txtRecord := range *rset.TxtRecords { - // Assume Value doesn't contain multiple strings - if txtRecord.Value != nil && len(*txtRecord.Value) > 0 { - uniqRecords[(*txtRecord.Value)[0]] = struct{}{} - } - } - } - - var txtRecords []dns.TxtRecord - for txt := range uniqRecords { - txtRecords = append(txtRecords, dns.TxtRecord{Value: &[]string{txt}}) - } - - rec := dns.RecordSet{ - Name: &relative, - RecordSetProperties: &dns.RecordSetProperties{ - TTL: to.Int64Ptr(int64(d.config.TTL)), - TxtRecords: &txtRecords, - }, - } - - _, err = rsc.CreateOrUpdate(ctx, d.config.ResourceGroup, zone, relative, dns.TXT, rec, "", "") - if err != nil { - return fmt.Errorf("azure: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZoneID(ctx, fqdn) - if err != nil { - return fmt.Errorf("azure: %v", err) - } - - relative := toRelativeRecord(fqdn, dns01.ToFqdn(zone)) - rsc := dns.NewRecordSetsClient(d.config.SubscriptionID) - rsc.Authorizer = d.authorizer - - _, err = rsc.Delete(ctx, d.config.ResourceGroup, zone, relative, dns.TXT, "") - if err != nil { - return fmt.Errorf("azure: %v", err) - } - return nil -} - -// Checks that azure has a zone for this domain name. -func (d *DNSProvider) getHostedZoneID(ctx context.Context, fqdn string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - dc := dns.NewZonesClient(d.config.SubscriptionID) - dc.Authorizer = d.authorizer - - zone, err := dc.Get(ctx, d.config.ResourceGroup, dns01.UnFqdn(authZone)) - if err != nil { - return "", err - } - - // zone.Name shouldn't have a trailing dot(.) - return to.String(zone.Name), nil -} - -// Returns the relative record to the domain -func toRelativeRecord(domain, zone string) string { - return dns01.UnFqdn(strings.TrimSuffix(domain, zone)) -} - -func getAuthorizer(config *Config) (autorest.Authorizer, error) { - if config.ClientID != "" && config.ClientSecret != "" && config.TenantID != "" { - oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, config.TenantID) - if err != nil { - return nil, err - } - - spt, err := adal.NewServicePrincipalToken(*oauthConfig, config.ClientID, config.ClientSecret, azure.PublicCloud.ResourceManagerEndpoint) - if err != nil { - return nil, err - } - - spt.SetSender(config.HTTPClient) - return autorest.NewBearerAuthorizer(spt), nil - } - - return auth.NewAuthorizerFromEnvironment() -} - -// Fetches metadata from environment or he instance metadata service -// borrowed from https://github.com/Microsoft/azureimds/blob/master/imdssample.go -func getMetadata(config *Config, field string) (string, error) { - metadataEndpoint := config.MetadataEndpoint - if len(metadataEndpoint) == 0 { - metadataEndpoint = defaultMetadataEndpoint - } - - resource := fmt.Sprintf("%s/metadata/instance/compute/%s", metadataEndpoint, field) - req, err := http.NewRequest(http.MethodGet, resource, nil) - if err != nil { - return "", err - } - - req.Header.Add("Metadata", "True") - - q := req.URL.Query() - q.Add("format", "text") - q.Add("api-version", "2017-12-01") - req.URL.RawQuery = q.Encode() - - resp, err := config.HTTPClient.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - return string(respBody), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/azure/azure.toml b/vendor/github.com/go-acme/lego/providers/dns/azure/azure.toml deleted file mode 100644 index b28bcbd..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/azure/azure.toml +++ /dev/null @@ -1,25 +0,0 @@ -Name = "Azure" -Description = '''''' -URL = "https://azure.microsoft.com/services/dns/" -Code = "azure" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - AZURE_CLIENT_ID = "Client ID" - AZURE_CLIENT_SECRET = "Client secret" - AZURE_SUBSCRIPTION_ID = "Subscription ID" - AZURE_TENANT_ID = "Tenant ID" - AZURE_RESOURCE_GROUP = "Resource group" - 'instance metadata service' = "If the credentials are **not** set via the environment, then it will attempt to get a bearer token via the [instance metadata service](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service)." - [Configuration.Additional] - AZURE_POLLING_INTERVAL = "Time between DNS propagation check" - AZURE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - AZURE_TTL = "The TTL of the TXT record used for the DNS challenge" - AZURE_METADATA_ENDPOINT = "Metadata Service endpoint URL" - -[Links] - API = "https://docs.microsoft.com/en-us/go/azure/" - GoClient = "https://github.com/Azure/azure-sdk-for-go" diff --git a/vendor/github.com/go-acme/lego/providers/dns/azure/azure_test.go b/vendor/github.com/go-acme/lego/providers/dns/azure/azure_test.go deleted file mode 100644 index f45e1b5..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/azure/azure_test.go +++ /dev/null @@ -1,181 +0,0 @@ -package azure - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "AZURE_CLIENT_ID", - "AZURE_CLIENT_SECRET", - "AZURE_SUBSCRIPTION_ID", - "AZURE_TENANT_ID", - "AZURE_RESOURCE_GROUP"). - WithDomain("AZURE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "AZURE_CLIENT_ID": "A", - "AZURE_CLIENT_SECRET": "B", - "AZURE_TENANT_ID": "C", - "AZURE_SUBSCRIPTION_ID": "D", - "AZURE_RESOURCE_GROUP": "E", - }, - }, - { - desc: "missing client ID", - envVars: map[string]string{ - "AZURE_CLIENT_ID": "", - "AZURE_CLIENT_SECRET": "B", - "AZURE_TENANT_ID": "C", - "AZURE_SUBSCRIPTION_ID": "D", - "AZURE_RESOURCE_GROUP": "E", - }, - expected: "failed to get oauth token from client credentials: parameter 'clientID' cannot be empty", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - clientID string - clientSecret string - subscriptionID string - tenantID string - resourceGroup string - handler func(w http.ResponseWriter, r *http.Request) - expected string - }{ - { - desc: "success", - clientID: "A", - clientSecret: "B", - tenantID: "C", - subscriptionID: "D", - resourceGroup: "E", - }, - { - desc: "SubscriptionID missing", - clientID: "A", - clientSecret: "B", - tenantID: "C", - subscriptionID: "", - resourceGroup: "", - expected: "azure: SubscriptionID is missing", - }, - { - desc: "ResourceGroup missing", - clientID: "A", - clientSecret: "B", - tenantID: "C", - subscriptionID: "D", - resourceGroup: "", - expected: "azure: ResourceGroup is missing", - }, - { - desc: "use metadata", - clientID: "A", - clientSecret: "B", - tenantID: "C", - subscriptionID: "", - resourceGroup: "", - handler: func(w http.ResponseWriter, _ *http.Request) { - _, err := w.Write([]byte("foo")) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.ClientID = test.clientID - config.ClientSecret = test.clientSecret - config.SubscriptionID = test.subscriptionID - config.TenantID = test.tenantID - config.ResourceGroup = test.resourceGroup - - handler := http.NewServeMux() - server := httptest.NewServer(handler) - defer server.Close() - if test.handler == nil { - handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {}) - } else { - handler.HandleFunc("/", test.handler) - } - config.MetadataEndpoint = server.URL - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.go b/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.go deleted file mode 100644 index 2079711..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.go +++ /dev/null @@ -1,99 +0,0 @@ -// Package bindman implements a DNS provider for solving the DNS-01 challenge. -package bindman - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/labbsr0x/bindman-dns-webhook/src/client" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - PropagationTimeout time.Duration - PollingInterval time.Duration - BaseURL string - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("BINDMAN_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("BINDMAN_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("BINDMAN_HTTP_TIMEOUT", time.Minute), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// Bindman's Address Manager REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - client *client.DNSWebhookClient -} - -// NewDNSProvider returns a DNSProvider instance configured for Bindman. -// BINDMAN_MANAGER_ADDRESS should have the scheme, hostname, and port (if required) of the authoritative Bindman Manager server. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("BINDMAN_MANAGER_ADDRESS") - if err != nil { - return nil, fmt.Errorf("bindman: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = values["BINDMAN_MANAGER_ADDRESS"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Bindman. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("bindman: the configuration of the DNS provider is nil") - } - - if config.BaseURL == "" { - return nil, fmt.Errorf("bindman: bindman manager address missing") - } - - bClient, err := client.New(config.BaseURL, config.HTTPClient) - if err != nil { - return nil, fmt.Errorf("bindman: %v", err) - } - - return &DNSProvider{config: config, client: bClient}, nil -} - -// Present creates a TXT record using the specified parameters. -// This will *not* create a subzone to contain the TXT record, -// so make sure the FQDN specified is within an extant zone. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - if err := d.client.AddRecord(fqdn, "TXT", value); err != nil { - return fmt.Errorf("bindman: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - if err := d.client.RemoveRecord(fqdn, "TXT"); err != nil { - return fmt.Errorf("bindman: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.toml b/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.toml deleted file mode 100644 index 92b8a53..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.toml +++ /dev/null @@ -1,22 +0,0 @@ -Name = "Bindman" -Description = '''''' -URL = "https://github.com/labbsr0x/bindman-dns-webhook" -Code = "bindman" -Since = "v2.6.0" - -Example = ''' -BINDMAN_MANAGER_ADDRESS= \ -lego --dns bindman --domains my.domain.com --email my@email.com run -''' - -[Configuration] - [Configuration.Credentials] - BINDMAN_MANAGER_ADDRESS = "The server URL, should have scheme, hostname, and port (if required) of the Bindman-DNS Manager server" - [Configuration.Additional] - BINDMAN_POLLING_INTERVAL = "Time between DNS propagation check" - BINDMAN_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - BINDMAN_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://gitlab.isc.org/isc-projects/bind9" - GoClient = "https://github.com/labbsr0x/bindman-dns-webhook" \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman_test.go b/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman_test.go deleted file mode 100644 index e209b13..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman_test.go +++ /dev/null @@ -1,238 +0,0 @@ -// Package bindman implements a DNS provider for solving the DNS-01 challenge. -package bindman - -import ( - "errors" - "net/http" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - bindmanClient "github.com/labbsr0x/bindman-dns-webhook/src/client" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("BINDMAN_MANAGER_ADDRESS").WithDomain("BINDMAN_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "BINDMAN_MANAGER_ADDRESS": "http://localhost", - }, - }, - { - desc: "missing bindman manager address", - envVars: map[string]string{ - "BINDMAN_MANAGER_ADDRESS": "", - }, - expected: "bindman: some credentials information are missing: BINDMAN_MANAGER_ADDRESS", - }, - { - desc: "empty bindman manager address", - envVars: map[string]string{ - "BINDMAN_MANAGER_ADDRESS": " ", - }, - expected: "bindman: managerAddress parameter must be a non-empty string", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - config *Config - expected string - }{ - { - desc: "success", - config: &Config{BaseURL: "http://localhost"}, - }, - { - desc: "missing base URL", - config: &Config{BaseURL: ""}, - expected: "bindman: bindman manager address missing", - }, - { - desc: "missing base URL", - config: &Config{BaseURL: " "}, - expected: "bindman: managerAddress parameter must be a non-empty string", - }, - { - desc: "missing config", - expected: "bindman: the configuration of the DNS provider is nil", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - p, err := NewDNSProviderConfig(test.config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - testCases := []struct { - name string - client *bindmanClient.DNSWebhookClient - domain string - token string - keyAuth string - expectError bool - }{ - { - name: "success when add record function return no error", - client: &bindmanClient.DNSWebhookClient{ - ClientAPI: &MockHTTPClientAPI{Status: http.StatusNoContent}, - }, - domain: "hello.test.com", - keyAuth: "szDTG4zmM0GsKG91QAGO2M4UYOJMwU8oFpWOP7eTjCw", - expectError: false, - }, - { - name: "error when add record function return an error", - client: &bindmanClient.DNSWebhookClient{ - ClientAPI: &MockHTTPClientAPI{Error: errors.New("error adding record")}, - }, - domain: "hello.test.com", - keyAuth: "szDTG4zmM0GsKG91QAGO2M4UYOJMwU8oFpWOP7eTjCw", - expectError: true, - }, - } - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - d := &DNSProvider{client: test.client} - - err := d.Present(test.domain, test.token, test.keyAuth) - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestDNSProvider_CleanUp(t *testing.T) { - testCases := []struct { - name string - client *bindmanClient.DNSWebhookClient - domain string - token string - keyAuth string - expectError bool - }{ - { - name: "success when remove record function return no error", - client: &bindmanClient.DNSWebhookClient{ - ClientAPI: &MockHTTPClientAPI{Status: http.StatusNoContent}, - }, - domain: "hello.test.com", - keyAuth: "szDTG4zmM0GsKG91QAGO2M4UYOJMwU8oFpWOP7eTjCw", - expectError: false, - }, - { - name: "error when remove record function return an error", - client: &bindmanClient.DNSWebhookClient{ - ClientAPI: &MockHTTPClientAPI{Error: errors.New("error adding record")}, - }, - domain: "hello.test.com", - keyAuth: "szDTG4zmM0GsKG91QAGO2M4UYOJMwU8oFpWOP7eTjCw", - expectError: true, - }, - } - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - d := &DNSProvider{client: test.client} - - err := d.CleanUp(test.domain, test.token, test.keyAuth) - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -type MockHTTPClientAPI struct { - Data []byte - Status int - Error error -} - -func (m *MockHTTPClientAPI) Put(url string, data []byte) (*http.Response, []byte, error) { - return &http.Response{StatusCode: m.Status}, m.Data, m.Error -} - -func (m *MockHTTPClientAPI) Post(url string, data []byte) (*http.Response, []byte, error) { - return &http.Response{StatusCode: m.Status}, m.Data, m.Error -} - -func (m *MockHTTPClientAPI) Get(url string) (*http.Response, []byte, error) { - return &http.Response{StatusCode: m.Status}, m.Data, m.Error -} -func (m *MockHTTPClientAPI) Delete(url string) (*http.Response, []byte, error) { - return &http.Response{StatusCode: m.Status}, m.Data, m.Error -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.go b/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.go deleted file mode 100644 index d3becf8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.go +++ /dev/null @@ -1,201 +0,0 @@ -// Package bluecat implements a DNS provider for solving the DNS-01 challenge using a self-hosted Bluecat Address Manager. -package bluecat - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - configType = "Configuration" - viewType = "View" - zoneType = "Zone" - txtType = "TXTRecord" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - UserName string - Password string - ConfigName string - DNSView string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("BLUECAT_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("BLUECAT_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("BLUECAT_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("BLUECAT_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// Bluecat's Address Manager REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - token string -} - -// NewDNSProvider returns a DNSProvider instance configured for Bluecat DNS. -// Credentials must be passed in the environment variables: BLUECAT_SERVER_URL, BLUECAT_USER_NAME and BLUECAT_PASSWORD. -// BLUECAT_SERVER_URL should have the scheme, hostname, and port (if required) of the authoritative Bluecat BAM server. -// The REST endpoint will be appended. -// In addition, the Configuration name and external DNS View Name must be passed in BLUECAT_CONFIG_NAME and BLUECAT_DNS_VIEW -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("BLUECAT_SERVER_URL", "BLUECAT_USER_NAME", "BLUECAT_PASSWORD", "BLUECAT_CONFIG_NAME", "BLUECAT_DNS_VIEW") - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = values["BLUECAT_SERVER_URL"] - config.UserName = values["BLUECAT_USER_NAME"] - config.Password = values["BLUECAT_PASSWORD"] - config.ConfigName = values["BLUECAT_CONFIG_NAME"] - config.DNSView = values["BLUECAT_DNS_VIEW"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Bluecat DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("bluecat: the configuration of the DNS provider is nil") - } - - if config.BaseURL == "" || config.UserName == "" || config.Password == "" || config.ConfigName == "" || config.DNSView == "" { - return nil, fmt.Errorf("bluecat: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record using the specified parameters -// This will *not* create a subzone to contain the TXT record, -// so make sure the FQDN specified is within an extant zone. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.login() - if err != nil { - return err - } - - viewID, err := d.lookupViewID(d.config.DNSView) - if err != nil { - return err - } - - parentZoneID, name, err := d.lookupParentZoneID(viewID, fqdn) - if err != nil { - return err - } - - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentZoneID), 10), - } - - body := bluecatEntity{ - Name: name, - Type: "TXTRecord", - Properties: fmt.Sprintf("ttl=%d|absoluteName=%s|txt=%s|", d.config.TTL, fqdn, value), - } - - resp, err := d.sendRequest(http.MethodPost, "addEntity", body, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - addTxtBytes, _ := ioutil.ReadAll(resp.Body) - addTxtResp := string(addTxtBytes) - // addEntity responds only with body text containing the ID of the created record - _, err = strconv.ParseUint(addTxtResp, 10, 64) - if err != nil { - return fmt.Errorf("bluecat: addEntity request failed: %s", addTxtResp) - } - - err = d.deploy(parentZoneID) - if err != nil { - return err - } - - return d.logout() -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - err := d.login() - if err != nil { - return err - } - - viewID, err := d.lookupViewID(d.config.DNSView) - if err != nil { - return err - } - - parentID, name, err := d.lookupParentZoneID(viewID, fqdn) - if err != nil { - return err - } - - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentID), 10), - "name": name, - "type": txtType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - var txtRec entityResponse - err = json.NewDecoder(resp.Body).Decode(&txtRec) - if err != nil { - return fmt.Errorf("bluecat: %v", err) - } - queryArgs = map[string]string{ - "objectId": strconv.FormatUint(uint64(txtRec.ID), 10), - } - - resp, err = d.sendRequest(http.MethodDelete, http.MethodDelete, nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - err = d.deploy(parentID) - if err != nil { - return err - } - - return d.logout() -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.toml b/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.toml deleted file mode 100644 index a6a91fa..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Bluecat" -Description = '''''' -URL = "https://www.bluecatnetworks.com" -Code = "bluecat" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - BLUECAT_SERVER_URL = "The server URL, should have scheme, hostname, and port (if required) of the authoritative Bluecat BAM serve" - BLUECAT_USER_NAME = "API username" - BLUECAT_PASSWORD = "API password" - BLUECAT_CONFIG_NAME = "Configuration name" - BLUECAT_DNS_VIEW = "External DNS View Name" - [Configuration.Additional] - BLUECAT_POLLING_INTERVAL = "Time between DNS propagation check" - BLUECAT_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - BLUECAT_TTL = "The TTL of the TXT record used for the DNS challenge" - BLUECAT_HTTP_TIMEOUT = "API request timeout" diff --git a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat_test.go b/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat_test.go deleted file mode 100644 index 92620ea..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat_test.go +++ /dev/null @@ -1,240 +0,0 @@ -package bluecat - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "BLUECAT_SERVER_URL", - "BLUECAT_USER_NAME", - "BLUECAT_PASSWORD", - "BLUECAT_CONFIG_NAME", - "BLUECAT_DNS_VIEW"). - WithDomain("BLUECAT_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "http://localhost", - "BLUECAT_USER_NAME": "A", - "BLUECAT_PASSWORD": "B", - "BLUECAT_CONFIG_NAME": "C", - "BLUECAT_DNS_VIEW": "D", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "", - "BLUECAT_USER_NAME": "", - "BLUECAT_PASSWORD": "", - "BLUECAT_CONFIG_NAME": "", - "BLUECAT_DNS_VIEW": "", - }, - expected: "bluecat: some credentials information are missing: BLUECAT_SERVER_URL,BLUECAT_USER_NAME,BLUECAT_PASSWORD,BLUECAT_CONFIG_NAME,BLUECAT_DNS_VIEW", - }, - { - desc: "missing server url", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "", - "BLUECAT_USER_NAME": "A", - "BLUECAT_PASSWORD": "B", - "BLUECAT_CONFIG_NAME": "C", - "BLUECAT_DNS_VIEW": "D", - }, - expected: "bluecat: some credentials information are missing: BLUECAT_SERVER_URL", - }, - { - desc: "missing username", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "http://localhost", - "BLUECAT_USER_NAME": "", - "BLUECAT_PASSWORD": "B", - "BLUECAT_CONFIG_NAME": "C", - "BLUECAT_DNS_VIEW": "D", - }, - expected: "bluecat: some credentials information are missing: BLUECAT_USER_NAME", - }, - { - desc: "missing password", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "http://localhost", - "BLUECAT_USER_NAME": "A", - "BLUECAT_PASSWORD": "", - "BLUECAT_CONFIG_NAME": "C", - "BLUECAT_DNS_VIEW": "D", - }, - expected: "bluecat: some credentials information are missing: BLUECAT_PASSWORD", - }, - { - desc: "missing config name", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "http://localhost", - "BLUECAT_USER_NAME": "A", - "BLUECAT_PASSWORD": "B", - "BLUECAT_CONFIG_NAME": "", - "BLUECAT_DNS_VIEW": "D", - }, - expected: "bluecat: some credentials information are missing: BLUECAT_CONFIG_NAME", - }, - { - desc: "missing DNS view", - envVars: map[string]string{ - "BLUECAT_SERVER_URL": "http://localhost", - "BLUECAT_USER_NAME": "A", - "BLUECAT_PASSWORD": "B", - "BLUECAT_CONFIG_NAME": "C", - "BLUECAT_DNS_VIEW": "", - }, - expected: "bluecat: some credentials information are missing: BLUECAT_DNS_VIEW", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - baseURL string - userName string - password string - configName string - dnsView string - expected string - }{ - { - desc: "success", - baseURL: "http://localhost", - userName: "A", - password: "B", - configName: "C", - dnsView: "D", - }, - { - desc: "missing credentials", - expected: "bluecat: credentials missing", - }, - { - desc: "missing base URL", - baseURL: "", - userName: "A", - password: "B", - configName: "C", - dnsView: "D", - expected: "bluecat: credentials missing", - }, - { - desc: "missing username", - baseURL: "http://localhost", - userName: "", - password: "B", - configName: "C", - dnsView: "D", - expected: "bluecat: credentials missing", - }, - { - desc: "missing password", - baseURL: "http://localhost", - userName: "A", - password: "", - configName: "C", - dnsView: "D", - expected: "bluecat: credentials missing", - }, - { - desc: "missing config name", - baseURL: "http://localhost", - userName: "A", - password: "B", - configName: "", - dnsView: "D", - expected: "bluecat: credentials missing", - }, - { - desc: "missing DNS view", - baseURL: "http://localhost", - userName: "A", - password: "B", - configName: "C", - dnsView: "", - expected: "bluecat: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.BaseURL = test.baseURL - config.UserName = test.userName - config.Password = test.password - config.ConfigName = test.configName - config.DNSView = test.dnsView - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(time.Second * 1) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bluecat/client.go b/vendor/github.com/go-acme/lego/providers/dns/bluecat/client.go deleted file mode 100644 index d910594..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bluecat/client.go +++ /dev/null @@ -1,249 +0,0 @@ -package bluecat - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" -) - -// JSON body for Bluecat entity requests and responses -type bluecatEntity struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Properties string `json:"properties"` -} - -type entityResponse struct { - ID uint `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - Properties string `json:"properties"` -} - -// Starts a new Bluecat API Session. Authenticates using customerName, userName, -// password and receives a token to be used in for subsequent requests. -func (d *DNSProvider) login() error { - queryArgs := map[string]string{ - "username": d.config.UserName, - "password": d.config.Password, - } - - resp, err := d.sendRequest(http.MethodGet, "login", nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - authBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("bluecat: %v", err) - } - authResp := string(authBytes) - - if strings.Contains(authResp, "Authentication Error") { - msg := strings.Trim(authResp, "\"") - return fmt.Errorf("bluecat: request failed: %s", msg) - } - - // Upon success, API responds with "Session Token-> BAMAuthToken: dQfuRMTUxNjc3MjcyNDg1ODppcGFybXM= <- for User : username" - d.token = regexp.MustCompile("BAMAuthToken: [^ ]+").FindString(authResp) - return nil -} - -// Destroys Bluecat Session -func (d *DNSProvider) logout() error { - if len(d.token) == 0 { - // nothing to do - return nil - } - - resp, err := d.sendRequest(http.MethodGet, "logout", nil, nil) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - return fmt.Errorf("bluecat: request failed to delete session with HTTP status code %d", resp.StatusCode) - } - - authBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - authResp := string(authBytes) - - if !strings.Contains(authResp, "successfully") { - msg := strings.Trim(authResp, "\"") - return fmt.Errorf("bluecat: request failed to delete session: %s", msg) - } - - d.token = "" - - return nil -} - -// Lookup the entity ID of the configuration named in our properties -func (d *DNSProvider) lookupConfID() (uint, error) { - queryArgs := map[string]string{ - "parentId": strconv.Itoa(0), - "name": d.config.ConfigName, - "type": configType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - if err != nil { - return 0, err - } - defer resp.Body.Close() - - var conf entityResponse - err = json.NewDecoder(resp.Body).Decode(&conf) - if err != nil { - return 0, fmt.Errorf("bluecat: %v", err) - } - return conf.ID, nil -} - -// Find the DNS view with the given name within -func (d *DNSProvider) lookupViewID(viewName string) (uint, error) { - confID, err := d.lookupConfID() - if err != nil { - return 0, err - } - - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(confID), 10), - "name": viewName, - "type": viewType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - if err != nil { - return 0, err - } - defer resp.Body.Close() - - var view entityResponse - err = json.NewDecoder(resp.Body).Decode(&view) - if err != nil { - return 0, fmt.Errorf("bluecat: %v", err) - } - - return view.ID, nil -} - -// Return the entityId of the parent zone by recursing from the root view -// Also return the simple name of the host -func (d *DNSProvider) lookupParentZoneID(viewID uint, fqdn string) (uint, string, error) { - parentViewID := viewID - name := "" - - if fqdn != "" { - zones := strings.Split(strings.Trim(fqdn, "."), ".") - last := len(zones) - 1 - name = zones[0] - - for i := last; i > -1; i-- { - zoneID, err := d.getZone(parentViewID, zones[i]) - if err != nil || zoneID == 0 { - return parentViewID, name, err - } - if i > 0 { - name = strings.Join(zones[0:i], ".") - } - parentViewID = zoneID - } - } - - return parentViewID, name, nil -} - -// Get the DNS zone with the specified name under the parentId -func (d *DNSProvider) getZone(parentID uint, name string) (uint, error) { - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentID), 10), - "name": name, - "type": zoneType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - - // Return an empty zone if the named zone doesn't exist - if resp != nil && resp.StatusCode == http.StatusNotFound { - return 0, fmt.Errorf("bluecat: could not find zone named %s", name) - } - if err != nil { - return 0, err - } - defer resp.Body.Close() - - var zone entityResponse - err = json.NewDecoder(resp.Body).Decode(&zone) - if err != nil { - return 0, fmt.Errorf("bluecat: %v", err) - } - - return zone.ID, nil -} - -// Deploy the DNS config for the specified entity to the authoritative servers -func (d *DNSProvider) deploy(entityID uint) error { - queryArgs := map[string]string{ - "entityId": strconv.FormatUint(uint64(entityID), 10), - } - - resp, err := d.sendRequest(http.MethodPost, "quickDeploy", nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// Send a REST request, using query parameters specified. The Authorization -// header will be set if we have an active auth token -func (d *DNSProvider) sendRequest(method, resource string, payload interface{}, queryArgs map[string]string) (*http.Response, error) { - url := fmt.Sprintf("%s/Services/REST/v1/%s", d.config.BaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - req.Header.Set("Content-Type", "application/json") - if len(d.token) > 0 { - req.Header.Set("Authorization", d.token) - } - - // Add all query parameters - q := req.URL.Query() - for argName, argVal := range queryArgs { - q.Add(argName, argVal) - } - req.URL.RawQuery = q.Encode() - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - - if resp.StatusCode >= 400 { - errBytes, _ := ioutil.ReadAll(resp.Body) - errResp := string(errBytes) - return nil, fmt.Errorf("bluecat: request failed with HTTP status code %d\n Full message: %s", - resp.StatusCode, errResp) - } - - return resp, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.go b/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.go deleted file mode 100644 index 85b298a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.go +++ /dev/null @@ -1,157 +0,0 @@ -// Package cloudflare implements a DNS provider for solving the DNS-01 challenge using cloudflare DNS. -package cloudflare - -import ( - "errors" - "fmt" - "net/http" - "time" - - cloudflare "github.com/cloudflare/cloudflare-go" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - minTTL = 120 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AuthEmail string - AuthKey string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("CLOUDFLARE_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("CLOUDFLARE_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("CLOUDFLARE_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CLOUDFLARE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - client *cloudflare.API - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for Cloudflare. -// Credentials must be passed in the environment variables: -// CLOUDFLARE_EMAIL and CLOUDFLARE_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.GetWithFallback( - []string{"CLOUDFLARE_EMAIL", "CF_API_EMAIL"}, - []string{"CLOUDFLARE_API_KEY", "CF_API_KEY"}) - if err != nil { - return nil, fmt.Errorf("cloudflare: %v", err) - } - - config := NewDefaultConfig() - config.AuthEmail = values["CLOUDFLARE_EMAIL"] - config.AuthKey = values["CLOUDFLARE_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Cloudflare. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("cloudflare: the configuration of the DNS provider is nil") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("cloudflare: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client, err := cloudflare.New(config.AuthKey, config.AuthEmail, cloudflare.HTTPClient(config.HTTPClient)) - if err != nil { - return nil, err - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("cloudflare: %v", err) - } - - zoneID, err := d.client.ZoneIDByName(dns01.UnFqdn(authZone)) - if err != nil { - return fmt.Errorf("cloudflare: failed to find zone %s: %v", authZone, err) - } - - dnsRecord := cloudflare.DNSRecord{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - Content: value, - TTL: d.config.TTL, - } - - response, err := d.client.CreateDNSRecord(zoneID, dnsRecord) - if err != nil { - return fmt.Errorf("cloudflare: failed to create TXT record: %v", err) - } - - if !response.Success { - return fmt.Errorf("cloudflare: failed to create TXT record: %+v %+v", response.Errors, response.Messages) - } - - log.Infof("cloudflare: new record for %s, ID %s", domain, response.Result.ID) - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("cloudflare: %v", err) - } - - zoneID, err := d.client.ZoneIDByName(dns01.UnFqdn(authZone)) - if err != nil { - return fmt.Errorf("cloudflare: failed to find zone %s: %v", authZone, err) - } - - dnsRecord := cloudflare.DNSRecord{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - } - - records, err := d.client.DNSRecords(zoneID, dnsRecord) - if err != nil { - return fmt.Errorf("cloudflare: failed to find TXT records: %v", err) - } - - for _, record := range records { - err = d.client.DeleteDNSRecord(zoneID, record.ID) - if err != nil { - log.Printf("cloudflare: failed to delete TXT record: %v", err) - } - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.toml b/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.toml deleted file mode 100644 index 017c119..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.toml +++ /dev/null @@ -1,25 +0,0 @@ -Name = "Cloudflare" -Description = '''''' -URL = "https://www.cloudflare.com/dns/" -Code = "cloudflare" -Since = "v0.3.0" - -Example = ''' -CLOUDFLARE_EMAIL=foo@bar.com \ -CLOUDFLARE_API_KEY=b9841238feb177a84330febba8a83208921177bffe733 \ -lego --dns cloudflare --domains my.domain.com --email my@email.com run -''' - -[Configuration] - [Configuration.Credentials] - CLOUDFLARE_EMAIL = "Account email" - CLOUDFLARE_API_KEY = "API key" - [Configuration.Additional] - CLOUDFLARE_POLLING_INTERVAL = "Time between DNS propagation check" - CLOUDFLARE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - CLOUDFLARE_TTL = "The TTL of the TXT record used for the DNS challenge" - CLOUDFLARE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://api.cloudflare.com/" - GoClient = "https://github.com/cloudflare/cloudflare-go" diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare_test.go b/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare_test.go deleted file mode 100644 index a2adc0a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package cloudflare - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "CLOUDFLARE_EMAIL", - "CLOUDFLARE_API_KEY"). - WithDomain("CLOUDFLARE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "CLOUDFLARE_EMAIL": "test@example.com", - "CLOUDFLARE_API_KEY": "123", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "CLOUDFLARE_EMAIL": "", - "CLOUDFLARE_API_KEY": "", - }, - expected: "cloudflare: some credentials information are missing: CLOUDFLARE_EMAIL,CLOUDFLARE_API_KEY", - }, - { - desc: "missing email", - envVars: map[string]string{ - "CLOUDFLARE_EMAIL": "", - "CLOUDFLARE_API_KEY": "key", - }, - expected: "cloudflare: some credentials information are missing: CLOUDFLARE_EMAIL", - }, - { - desc: "missing api key", - envVars: map[string]string{ - "CLOUDFLARE_EMAIL": "awesome@possum.com", - "CLOUDFLARE_API_KEY": "", - }, - expected: "cloudflare: some credentials information are missing: CLOUDFLARE_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - authEmail string - authKey string - expected string - }{ - { - desc: "success", - authEmail: "test@example.com", - authKey: "123", - }, - { - desc: "missing credentials", - expected: "invalid credentials: key & email must not be empty", - }, - { - desc: "missing email", - authKey: "123", - expected: "invalid credentials: key & email must not be empty", - }, - { - desc: "missing api key", - authEmail: "test@example.com", - expected: "invalid credentials: key & email must not be empty", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.AuthEmail = test.authEmail - config.AuthKey = test.authKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.go b/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.go deleted file mode 100644 index a33d3f0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package cloudns implements a DNS provider for solving the DNS-01 challenge using ClouDNS DNS. -package cloudns - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/cloudns/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AuthID string - AuthPassword string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("CLOUDNS_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("CLOUDNS_POLLING_INTERVAL", 4*time.Second), - TTL: env.GetOrDefaultInt("CLOUDNS_TTL", 60), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CLOUDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for ClouDNS. -// Credentials must be passed in the environment variables: -// CLOUDNS_AUTH_ID and CLOUDNS_AUTH_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("CLOUDNS_AUTH_ID", "CLOUDNS_AUTH_PASSWORD") - if err != nil { - return nil, fmt.Errorf("ClouDNS: %v", err) - } - - config := NewDefaultConfig() - config.AuthID = values["CLOUDNS_AUTH_ID"] - config.AuthPassword = values["CLOUDNS_AUTH_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for ClouDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("ClouDNS: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.AuthID, config.AuthPassword) - if err != nil { - return nil, fmt.Errorf("ClouDNS: %v", err) - } - - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.client.GetZone(fqdn) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - err = d.client.AddTxtRecord(zone.Name, fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.client.GetZone(fqdn) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - record, err := d.client.FindTxtRecord(zone.Name, fqdn) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - if record == nil { - return nil - } - - err = d.client.RemoveTxtRecord(record.ID, zone.Name) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.toml b/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.toml deleted file mode 100644 index 95176a9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "ClouDNS" -Description = '''''' -URL = "https://www.cloudns.net" -Code = "cloudns" -Since = "v2.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - CLOUDNS_AUTH_ID = "The API user ID" - CLOUDNS_AUTH_PASSWORD = "The password for API user ID" - [Configuration.Additional] - CLOUDNS_POLLING_INTERVAL = "Time between DNS propagation check" - CLOUDNS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - CLOUDNS_TTL = "The TTL of the TXT record used for the DNS challenge" - CLOUDNS_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.cloudns.net/wiki/article/42/" diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns_test.go b/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns_test.go deleted file mode 100644 index 1f1540b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudns - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "CLOUDNS_AUTH_ID", - "CLOUDNS_AUTH_PASSWORD"). - WithDomain("CLOUDNS_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "CLOUDNS_AUTH_ID": "123", - "CLOUDNS_AUTH_PASSWORD": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "CLOUDNS_AUTH_ID": "", - "CLOUDNS_AUTH_PASSWORD": "", - }, - expected: "ClouDNS: some credentials information are missing: CLOUDNS_AUTH_ID,CLOUDNS_AUTH_PASSWORD", - }, - { - desc: "missing auth-id", - envVars: map[string]string{ - "CLOUDNS_AUTH_ID": "", - "CLOUDNS_AUTH_PASSWORD": "456", - }, - expected: "ClouDNS: some credentials information are missing: CLOUDNS_AUTH_ID", - }, - { - desc: "missing auth-password", - envVars: map[string]string{ - "CLOUDNS_AUTH_ID": "123", - "CLOUDNS_AUTH_PASSWORD": "", - }, - expected: "ClouDNS: some credentials information are missing: CLOUDNS_AUTH_PASSWORD", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - authID string - authPassword string - expected string - }{ - { - desc: "success", - authID: "123", - authPassword: "456", - }, - { - desc: "missing credentials", - expected: "ClouDNS: credentials missing: authID", - }, - { - desc: "missing auth-id", - authPassword: "456", - expected: "ClouDNS: credentials missing: authID", - }, - { - desc: "missing auth-password", - authID: "123", - expected: "ClouDNS: credentials missing: authPassword", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.AuthID = test.authID - config.AuthPassword = test.authPassword - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client.go deleted file mode 100644 index 92620e9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client.go +++ /dev/null @@ -1,271 +0,0 @@ -package internal - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" -) - -const defaultBaseURL = "https://api.cloudns.net/dns/" - -type apiResponse struct { - Status string `json:"status"` - StatusDescription string `json:"statusDescription"` -} - -type Zone struct { - Name string - Type string - Zone string - Status string // is an integer, but cast as string -} - -// TXTRecord a TXT record -type TXTRecord struct { - ID int `json:"id,string"` - Type string `json:"type"` - Host string `json:"host"` - Record string `json:"record"` - Failover int `json:"failover,string"` - TTL int `json:"ttl,string"` - Status int `json:"status"` -} - -type TXTRecords map[string]TXTRecord - -// NewClient creates a ClouDNS client -func NewClient(authID string, authPassword string) (*Client, error) { - if authID == "" { - return nil, fmt.Errorf("credentials missing: authID") - } - - if authPassword == "" { - return nil, fmt.Errorf("credentials missing: authPassword") - } - - baseURL, err := url.Parse(defaultBaseURL) - if err != nil { - return nil, err - } - - return &Client{ - authID: authID, - authPassword: authPassword, - HTTPClient: &http.Client{}, - BaseURL: baseURL, - }, nil -} - -// Client ClouDNS client -type Client struct { - authID string - authPassword string - HTTPClient *http.Client - BaseURL *url.URL -} - -// GetZone Get domain name information for a FQDN -func (c *Client) GetZone(authFQDN string) (*Zone, error) { - authZone, err := dns01.FindZoneByFqdn(authFQDN) - if err != nil { - return nil, err - } - - authZoneName := dns01.UnFqdn(authZone) - - reqURL := *c.BaseURL - reqURL.Path += "get-zone-info.json" - - q := reqURL.Query() - q.Add("domain-name", authZoneName) - reqURL.RawQuery = q.Encode() - - result, err := c.doRequest(http.MethodGet, &reqURL) - if err != nil { - return nil, err - } - - var zone Zone - - if len(result) > 0 { - if err = json.Unmarshal(result, &zone); err != nil { - return nil, fmt.Errorf("zone unmarshaling error: %v", err) - } - } - - if zone.Name == authZoneName { - return &zone, nil - } - - return nil, fmt.Errorf("zone %s not found for authFQDN %s", authZoneName, authFQDN) -} - -// FindTxtRecord return the TXT record a zone ID and a FQDN -func (c *Client) FindTxtRecord(zoneName, fqdn string) (*TXTRecord, error) { - host := dns01.UnFqdn(strings.TrimSuffix(dns01.UnFqdn(fqdn), zoneName)) - - reqURL := *c.BaseURL - reqURL.Path += "records.json" - - q := reqURL.Query() - q.Add("domain-name", zoneName) - q.Add("host", host) - q.Add("type", "TXT") - reqURL.RawQuery = q.Encode() - - result, err := c.doRequest(http.MethodGet, &reqURL) - if err != nil { - return nil, err - } - - // the API returns [] when there is no records. - if string(result) == "[]" { - return nil, nil - } - - var records TXTRecords - if err = json.Unmarshal(result, &records); err != nil { - return nil, fmt.Errorf("TXT record unmarshaling error: %v: %s", err, string(result)) - } - - for _, record := range records { - if record.Host == host && record.Type == "TXT" { - return &record, nil - } - } - - return nil, nil -} - -// AddTxtRecord add a TXT record -func (c *Client) AddTxtRecord(zoneName string, fqdn, value string, ttl int) error { - host := dns01.UnFqdn(strings.TrimSuffix(dns01.UnFqdn(fqdn), zoneName)) - - reqURL := *c.BaseURL - reqURL.Path += "add-record.json" - - q := reqURL.Query() - q.Add("domain-name", zoneName) - q.Add("host", host) - q.Add("record", value) - q.Add("ttl", strconv.Itoa(ttlRounder(ttl))) - q.Add("record-type", "TXT") - reqURL.RawQuery = q.Encode() - - raw, err := c.doRequest(http.MethodPost, &reqURL) - if err != nil { - return err - } - - resp := apiResponse{} - if err = json.Unmarshal(raw, &resp); err != nil { - return fmt.Errorf("apiResponse unmarshaling error: %v: %s", err, string(raw)) - } - - if resp.Status != "Success" { - return fmt.Errorf("fail to add TXT record: %s %s", resp.Status, resp.StatusDescription) - } - - return nil -} - -// RemoveTxtRecord remove a TXT record -func (c *Client) RemoveTxtRecord(recordID int, zoneName string) error { - reqURL := *c.BaseURL - reqURL.Path += "delete-record.json" - - q := reqURL.Query() - q.Add("domain-name", zoneName) - q.Add("record-id", strconv.Itoa(recordID)) - reqURL.RawQuery = q.Encode() - - raw, err := c.doRequest(http.MethodPost, &reqURL) - if err != nil { - return err - } - - resp := apiResponse{} - if err = json.Unmarshal(raw, &resp); err != nil { - return fmt.Errorf("apiResponse unmarshaling error: %v: %s", err, string(raw)) - } - - if resp.Status != "Success" { - return fmt.Errorf("fail to add TXT record: %s %s", resp.Status, resp.StatusDescription) - } - - return nil -} - -func (c *Client) doRequest(method string, url *url.URL) (json.RawMessage, error) { - req, err := c.buildRequest(method, url) - if err != nil { - return nil, err - } - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - - defer resp.Body.Close() - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.New(toUnreadableBodyMessage(req, content)) - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("invalid code (%v), error: %s", resp.StatusCode, content) - } - return content, nil -} - -func (c *Client) buildRequest(method string, url *url.URL) (*http.Request, error) { - q := url.Query() - q.Add("auth-id", c.authID) - q.Add("auth-password", c.authPassword) - url.RawQuery = q.Encode() - - req, err := http.NewRequest(method, url.String(), nil) - if err != nil { - return nil, fmt.Errorf("invalid request: %v", err) - } - - return req, nil -} - -func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody)) -} - -// https://www.cloudns.net/wiki/article/58/ -// Available TTL's: -// 60 = 1 minute -// 300 = 5 minutes -// 900 = 15 minutes -// 1800 = 30 minutes -// 3600 = 1 hour -// 21600 = 6 hours -// 43200 = 12 hours -// 86400 = 1 day -// 172800 = 2 days -// 259200 = 3 days -// 604800 = 1 week -// 1209600 = 2 weeks -// 2592000 = 1 month -func ttlRounder(ttl int) int { - for _, validTTL := range []int{60, 300, 900, 1800, 3600, 21600, 43200, 86400, 172800, 259200, 604800, 1209600} { - if ttl <= validTTL { - return validTTL - } - } - - return 2592000 -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client_test.go deleted file mode 100644 index 7816eeb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client_test.go +++ /dev/null @@ -1,247 +0,0 @@ -package internal - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func handlerMock(method string, jsonData []byte) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Method != method { - http.Error(rw, "Incorrect method used", http.StatusBadRequest) - return - } - - _, err := rw.Write(jsonData) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - }) -} - -func TestClientGetZone(t *testing.T) { - type result struct { - zone *Zone - error bool - } - testCases := []struct { - desc string - authFQDN string - apiResponse []byte - expected result - }{ - { - desc: "zone found", - authFQDN: "_acme-challenge.foo.com.", - apiResponse: []byte(`{"name": "foo.com", "type": "master", "zone": "zone", "status": "1"}`), - expected: result{ - zone: &Zone{ - Name: "foo.com", - Type: "master", - Zone: "zone", - Status: "1", - }, - }, - }, - { - desc: "zone not found", - authFQDN: "_acme-challenge.foo.com.", - apiResponse: []byte(``), - expected: result{error: true}, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - server := httptest.NewServer(handlerMock(http.MethodGet, test.apiResponse)) - - client, _ := NewClient("myAuthID", "myAuthPassword") - mockBaseURL, _ := url.Parse(fmt.Sprintf("%s/", server.URL)) - client.BaseURL = mockBaseURL - - zone, err := client.GetZone(test.authFQDN) - - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.zone, zone) - } - }) - } -} - -func TestClientFindTxtRecord(t *testing.T) { - type result struct { - txtRecord *TXTRecord - error bool - } - - testCases := []struct { - desc string - authFQDN string - zoneName string - apiResponse []byte - expected result - }{ - { - desc: "record found", - authFQDN: "_acme-challenge.foo.com.", - zoneName: "foo.com", - apiResponse: []byte(`{ - "5769228": { - "id": "5769228", - "type": "TXT", - "host": "_acme-challenge", - "record": "txtTXTtxtTXTtxtTXTtxtTXT", - "failover": "0", - "ttl": "3600", - "status": 1 - }, - "181805209": { - "id": "181805209", - "type": "TXT", - "host": "_github-challenge", - "record": "b66b8324b5", - "failover": "0", - "ttl": "300", - "status": 1 - } -}`), - expected: result{ - txtRecord: &TXTRecord{ - ID: 5769228, - Type: "TXT", - Host: "_acme-challenge", - Record: "txtTXTtxtTXTtxtTXTtxtTXT", - Failover: 0, - TTL: 3600, - Status: 1, - }, - }, - }, - { - desc: "record not found", - authFQDN: "_acme-challenge.foo.com.", - zoneName: "test-zone", - apiResponse: []byte(`[]`), - expected: result{txtRecord: nil}, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - server := httptest.NewServer(handlerMock(http.MethodGet, test.apiResponse)) - - client, _ := NewClient("myAuthID", "myAuthPassword") - mockBaseURL, _ := url.Parse(fmt.Sprintf("%s/", server.URL)) - client.BaseURL = mockBaseURL - - txtRecord, err := client.FindTxtRecord(test.zoneName, test.authFQDN) - - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.txtRecord, txtRecord) - } - }) - } -} - -func TestClientAddTxtRecord(t *testing.T) { - type expected struct { - Query string - Error string - } - - testCases := []struct { - desc string - zone *Zone - authFQDN string - value string - ttl int - apiResponse []byte - expected expected - }{ - { - desc: "sub-zone", - zone: &Zone{ - Name: "bar.com", - Type: "master", - Zone: "domain", - Status: "1", - }, - authFQDN: "_acme-challenge.foo.bar.com.", - value: "txtTXTtxtTXTtxtTXTtxtTXT", - ttl: 60, - apiResponse: []byte(`{"status":"Success","statusDescription":"The record was added successfully."}`), - expected: expected{ - Query: `auth-id=myAuthID&auth-password=myAuthPassword&domain-name=bar.com&host=_acme-challenge.foo&record=txtTXTtxtTXTtxtTXTtxtTXT&record-type=TXT&ttl=60`, - }, - }, - { - desc: "main zone", - zone: &Zone{ - Name: "bar.com", - Type: "master", - Zone: "domain", - Status: "1", - }, - authFQDN: "_acme-challenge.bar.com.", - value: "TXTtxtTXTtxtTXTtxtTXTtxt", - ttl: 60, - apiResponse: []byte(`{"status":"Success","statusDescription":"The record was added successfully."}`), - expected: expected{ - Query: `auth-id=myAuthID&auth-password=myAuthPassword&domain-name=bar.com&host=_acme-challenge&record=TXTtxtTXTtxtTXTtxtTXTtxt&record-type=TXT&ttl=60`, - }, - }, - { - desc: "invalid status", - zone: &Zone{ - Name: "bar.com", - Type: "master", - Zone: "domain", - Status: "1", - }, - authFQDN: "_acme-challenge.bar.com.", - value: "TXTtxtTXTtxtTXTtxtTXTtxt", - ttl: 120, - apiResponse: []byte(`{"status":"Failed","statusDescription":"Invalid TTL. Choose from the list of the values we support."}`), - expected: expected{ - Query: `auth-id=myAuthID&auth-password=myAuthPassword&domain-name=bar.com&host=_acme-challenge&record=TXTtxtTXTtxtTXTtxtTXTtxt&record-type=TXT&ttl=300`, - Error: "fail to add TXT record: Failed Invalid TTL. Choose from the list of the values we support.", - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - assert.NotNil(t, req.URL.RawQuery) - assert.Equal(t, test.expected.Query, req.URL.RawQuery) - - handlerMock(http.MethodPost, test.apiResponse).ServeHTTP(rw, req) - })) - - client, _ := NewClient("myAuthID", "myAuthPassword") - mockBaseURL, _ := url.Parse(fmt.Sprintf("%s/", server.URL)) - client.BaseURL = mockBaseURL - - err := client.AddTxtRecord(test.zone.Name, test.authFQDN, test.value, test.ttl) - - if test.expected.Error != "" { - require.EqualError(t, err, test.expected.Error) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.go b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.go deleted file mode 100644 index ef70629..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.go +++ /dev/null @@ -1,108 +0,0 @@ -// Package cloudxns implements a DNS provider for solving the DNS-01 challenge using CloudXNS DNS. -package cloudxns - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/cloudxns/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - SecretKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("CLOUDXNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("CLOUDXNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("CLOUDXNS_TTL", dns01.DefaultTTL), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CLOUDXNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for CloudXNS. -// Credentials must be passed in the environment variables: -// CLOUDXNS_API_KEY and CLOUDXNS_SECRET_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("CLOUDXNS_API_KEY", "CLOUDXNS_SECRET_KEY") - if err != nil { - return nil, fmt.Errorf("CloudXNS: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["CLOUDXNS_API_KEY"] - config.SecretKey = values["CLOUDXNS_SECRET_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for CloudXNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("CloudXNS: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.APIKey, config.SecretKey) - if err != nil { - return nil, err - } - - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - info, err := d.client.GetDomainInformation(fqdn) - if err != nil { - return err - } - - return d.client.AddTxtRecord(info, fqdn, value, d.config.TTL) -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - info, err := d.client.GetDomainInformation(fqdn) - if err != nil { - return err - } - - record, err := d.client.FindTxtRecord(info.ID, fqdn) - if err != nil { - return err - } - - return d.client.RemoveTxtRecord(record.RecordID, info.ID) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.toml b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.toml deleted file mode 100644 index d5bc6d4..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "CloudXNS" -Description = """""" -URL = "https://www.cloudxns.net/" -Code = "cloudxns" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - CLOUDXNS_API_KEY = "The API key" - CLOUDXNS_SECRET_KEY = "THe API secret key" - [Configuration.Additional] - CLOUDXNS_POLLING_INTERVAL = "Time between DNS propagation check" - CLOUDXNS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - CLOUDXNS_TTL = "The TTL of the TXT record used for the DNS challenge" - CLOUDXNS_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.cloudxns.net/Public/Doc/CloudXNS_api2.0_doc_zh-cn.zip" diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns_test.go b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns_test.go deleted file mode 100644 index 1c830a9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudxns - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "CLOUDXNS_API_KEY", - "CLOUDXNS_SECRET_KEY"). - WithDomain("CLOUDXNS_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "CLOUDXNS_API_KEY": "123", - "CLOUDXNS_SECRET_KEY": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "CLOUDXNS_API_KEY": "", - "CLOUDXNS_SECRET_KEY": "", - }, - expected: "CloudXNS: some credentials information are missing: CLOUDXNS_API_KEY,CLOUDXNS_SECRET_KEY", - }, - { - desc: "missing API key", - envVars: map[string]string{ - "CLOUDXNS_API_KEY": "", - "CLOUDXNS_SECRET_KEY": "456", - }, - expected: "CloudXNS: some credentials information are missing: CLOUDXNS_API_KEY", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "CLOUDXNS_API_KEY": "123", - "CLOUDXNS_SECRET_KEY": "", - }, - expected: "CloudXNS: some credentials information are missing: CLOUDXNS_SECRET_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - secretKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - secretKey: "456", - }, - { - desc: "missing credentials", - expected: "CloudXNS: credentials missing: apiKey", - }, - { - desc: "missing api key", - secretKey: "456", - expected: "CloudXNS: credentials missing: apiKey", - }, - { - desc: "missing secret key", - apiKey: "123", - expected: "CloudXNS: credentials missing: secretKey", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.SecretKey = test.secretKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client.go deleted file mode 100644 index be71c9b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client.go +++ /dev/null @@ -1,208 +0,0 @@ -package internal - -import ( - "bytes" - "crypto/md5" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" -) - -const defaultBaseURL = "https://www.cloudxns.net/api2/" - -type apiResponse struct { - Code int `json:"code"` - Message string `json:"message"` - Data json.RawMessage `json:"data,omitempty"` -} - -// Data Domain information -type Data struct { - ID string `json:"id"` - Domain string `json:"domain"` - TTL int `json:"ttl,omitempty"` -} - -// TXTRecord a TXT record -type TXTRecord struct { - ID int `json:"domain_id,omitempty"` - RecordID string `json:"record_id,omitempty"` - - Host string `json:"host"` - Value string `json:"value"` - Type string `json:"type"` - LineID int `json:"line_id,string"` - TTL int `json:"ttl,string"` -} - -// NewClient creates a CloudXNS client -func NewClient(apiKey string, secretKey string) (*Client, error) { - if apiKey == "" { - return nil, fmt.Errorf("CloudXNS: credentials missing: apiKey") - } - - if secretKey == "" { - return nil, fmt.Errorf("CloudXNS: credentials missing: secretKey") - } - - return &Client{ - apiKey: apiKey, - secretKey: secretKey, - HTTPClient: &http.Client{}, - BaseURL: defaultBaseURL, - }, nil -} - -// Client CloudXNS client -type Client struct { - apiKey string - secretKey string - HTTPClient *http.Client - BaseURL string -} - -// GetDomainInformation Get domain name information for a FQDN -func (c *Client) GetDomainInformation(fqdn string) (*Data, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - result, err := c.doRequest(http.MethodGet, "domain", nil) - if err != nil { - return nil, err - } - - var domains []Data - if len(result) > 0 { - err = json.Unmarshal(result, &domains) - if err != nil { - return nil, fmt.Errorf("CloudXNS: domains unmarshaling error: %v", err) - } - } - - for _, data := range domains { - if data.Domain == authZone { - return &data, nil - } - } - - return nil, fmt.Errorf("CloudXNS: zone %s not found for domain %s", authZone, fqdn) -} - -// FindTxtRecord return the TXT record a zone ID and a FQDN -func (c *Client) FindTxtRecord(zoneID, fqdn string) (*TXTRecord, error) { - result, err := c.doRequest(http.MethodGet, fmt.Sprintf("record/%s?host_id=0&offset=0&row_num=2000", zoneID), nil) - if err != nil { - return nil, err - } - - var records []TXTRecord - err = json.Unmarshal(result, &records) - if err != nil { - return nil, fmt.Errorf("CloudXNS: TXT record unmarshaling error: %v", err) - } - - for _, record := range records { - if record.Host == dns01.UnFqdn(fqdn) && record.Type == "TXT" { - return &record, nil - } - } - - return nil, fmt.Errorf("CloudXNS: no existing record found for %q", fqdn) -} - -// AddTxtRecord add a TXT record -func (c *Client) AddTxtRecord(info *Data, fqdn, value string, ttl int) error { - id, err := strconv.Atoi(info.ID) - if err != nil { - return fmt.Errorf("CloudXNS: invalid zone ID: %v", err) - } - - payload := TXTRecord{ - ID: id, - Host: dns01.UnFqdn(strings.TrimSuffix(fqdn, info.Domain)), - Value: value, - Type: "TXT", - LineID: 1, - TTL: ttl, - } - - body, err := json.Marshal(payload) - if err != nil { - return fmt.Errorf("CloudXNS: record unmarshaling error: %v", err) - } - - _, err = c.doRequest(http.MethodPost, "record", body) - return err -} - -// RemoveTxtRecord remove a TXT record -func (c *Client) RemoveTxtRecord(recordID, zoneID string) error { - _, err := c.doRequest(http.MethodDelete, fmt.Sprintf("record/%s/%s", recordID, zoneID), nil) - return err -} - -func (c *Client) doRequest(method, uri string, body []byte) (json.RawMessage, error) { - req, err := c.buildRequest(method, uri, body) - if err != nil { - return nil, err - } - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("CloudXNS: %v", err) - } - - defer resp.Body.Close() - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("CloudXNS: %s", toUnreadableBodyMessage(req, content)) - } - - var r apiResponse - err = json.Unmarshal(content, &r) - if err != nil { - return nil, fmt.Errorf("CloudXNS: response unmashaling error: %v: %s", err, toUnreadableBodyMessage(req, content)) - } - - if r.Code != 1 { - return nil, fmt.Errorf("CloudXNS: invalid code (%v), error: %s", r.Code, r.Message) - } - return r.Data, nil -} - -func (c *Client) buildRequest(method, uri string, body []byte) (*http.Request, error) { - url := c.BaseURL + uri - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, fmt.Errorf("CloudXNS: invalid request: %v", err) - } - - requestDate := time.Now().Format(time.RFC1123Z) - - req.Header.Set("API-KEY", c.apiKey) - req.Header.Set("API-REQUEST-DATE", requestDate) - req.Header.Set("API-HMAC", c.hmac(url, requestDate, string(body))) - req.Header.Set("API-FORMAT", "json") - - return req, nil -} - -func (c *Client) hmac(url, date, body string) string { - sum := md5.Sum([]byte(c.apiKey + url + body + date + c.secretKey)) - return hex.EncodeToString(sum[:]) -} - -func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client_test.go deleted file mode 100644 index c9d6209..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client_test.go +++ /dev/null @@ -1,287 +0,0 @@ -package internal - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func handlerMock(method string, response *apiResponse, data interface{}) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Method != method { - content, err := json.Marshal(apiResponse{ - Code: 999, // random code only for the test - Message: fmt.Sprintf("invalid method: got %s want %s", req.Method, method), - }) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - http.Error(rw, string(content), http.StatusBadRequest) - return - } - - jsonData, err := json.Marshal(data) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - response.Data = jsonData - - content, err := json.Marshal(response) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - _, err = rw.Write(content) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - }) -} - -func TestClientGetDomainInformation(t *testing.T) { - type result struct { - domain *Data - error bool - } - - testCases := []struct { - desc string - fqdn string - response *apiResponse - data []Data - expected result - }{ - { - desc: "domain found", - fqdn: "_acme-challenge.foo.com.", - response: &apiResponse{ - Code: 1, - }, - data: []Data{ - { - ID: "1", - Domain: "bar.com.", - }, - { - ID: "2", - Domain: "foo.com.", - }, - }, - expected: result{domain: &Data{ - ID: "2", - Domain: "foo.com.", - }}, - }, - { - desc: "domains not found", - fqdn: "_acme-challenge.huu.com.", - response: &apiResponse{ - Code: 1, - }, - data: []Data{ - { - ID: "5", - Domain: "bar.com.", - }, - { - ID: "6", - Domain: "foo.com.", - }, - }, - expected: result{error: true}, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - server := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.data)) - - client, _ := NewClient("myKey", "mySecret") - client.BaseURL = server.URL + "/" - - domain, err := client.GetDomainInformation(test.fqdn) - - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.domain, domain) - } - }) - } -} - -func TestClientFindTxtRecord(t *testing.T) { - type result struct { - txtRecord *TXTRecord - error bool - } - - testCases := []struct { - desc string - fqdn string - zoneID string - txtRecords []TXTRecord - response *apiResponse - expected result - }{ - { - desc: "record found", - fqdn: "_acme-challenge.foo.com.", - zoneID: "test-zone", - txtRecords: []TXTRecord{ - { - ID: 1, - RecordID: "Record-A", - Host: "_acme-challenge.foo.com", - Value: "txtTXTtxtTXTtxtTXTtxtTXT", - Type: "TXT", - LineID: 6, - TTL: 30, - }, - { - ID: 2, - RecordID: "Record-B", - Host: "_acme-challenge.bar.com", - Value: "TXTtxtTXTtxtTXTtxtTXTtxt", - Type: "TXT", - LineID: 6, - TTL: 30, - }, - }, - response: &apiResponse{ - Code: 1, - }, - expected: result{ - txtRecord: &TXTRecord{ - ID: 1, - RecordID: "Record-A", - Host: "_acme-challenge.foo.com", - Value: "txtTXTtxtTXTtxtTXTtxtTXT", - Type: "TXT", - LineID: 6, - TTL: 30, - }, - }, - }, - { - desc: "record not found", - fqdn: "_acme-challenge.huu.com.", - zoneID: "test-zone", - txtRecords: []TXTRecord{ - { - ID: 1, - RecordID: "Record-A", - Host: "_acme-challenge.foo.com", - Value: "txtTXTtxtTXTtxtTXTtxtTXT", - Type: "TXT", - LineID: 6, - TTL: 30, - }, - { - ID: 2, - RecordID: "Record-B", - Host: "_acme-challenge.bar.com", - Value: "TXTtxtTXTtxtTXTtxtTXTtxt", - Type: "TXT", - LineID: 6, - TTL: 30, - }, - }, - response: &apiResponse{ - Code: 1, - }, - expected: result{error: true}, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - server := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.txtRecords)) - - client, _ := NewClient("myKey", "mySecret") - client.BaseURL = server.URL + "/" - - txtRecord, err := client.FindTxtRecord(test.zoneID, test.fqdn) - - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.txtRecord, txtRecord) - } - }) - } -} - -func TestClientAddTxtRecord(t *testing.T) { - testCases := []struct { - desc string - domain *Data - fqdn string - value string - ttl int - expected string - }{ - { - desc: "sub-domain", - domain: &Data{ - ID: "1", - Domain: "bar.com.", - }, - fqdn: "_acme-challenge.foo.bar.com.", - value: "txtTXTtxtTXTtxtTXTtxtTXT", - ttl: 30, - expected: `{"domain_id":1,"host":"_acme-challenge.foo","value":"txtTXTtxtTXTtxtTXTtxtTXT","type":"TXT","line_id":"1","ttl":"30"}`, - }, - { - desc: "main domain", - domain: &Data{ - ID: "2", - Domain: "bar.com.", - }, - fqdn: "_acme-challenge.bar.com.", - value: "TXTtxtTXTtxtTXTtxtTXTtxt", - ttl: 30, - expected: `{"domain_id":2,"host":"_acme-challenge","value":"TXTtxtTXTtxtTXTtxtTXTtxt","type":"TXT","line_id":"1","ttl":"30"}`, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - response := &apiResponse{ - Code: 1, - } - - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - assert.NotNil(t, req.Body) - content, err := ioutil.ReadAll(req.Body) - require.NoError(t, err) - - assert.Equal(t, test.expected, string(content)) - - handlerMock(http.MethodPost, response, nil).ServeHTTP(rw, req) - })) - - client, _ := NewClient("myKey", "mySecret") - client.BaseURL = server.URL + "/" - - err := client.AddTxtRecord(test.domain, test.fqdn, test.value, test.ttl) - require.NoError(t, err) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.go b/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.go deleted file mode 100644 index 2a96218..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.go +++ /dev/null @@ -1,148 +0,0 @@ -// Package conoha implements a DNS provider for solving the DNS-01 challenge using ConoHa DNS. -package conoha - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/conoha/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Region string - TenantID string - Username string - Password string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - Region: env.GetOrDefaultString("CONOHA_REGION", "tyo1"), - TTL: env.GetOrDefaultInt("CONOHA_TTL", 60), - PropagationTimeout: env.GetOrDefaultSecond("CONOHA_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("CONOHA_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CONOHA_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for ConoHa DNS. -// Credentials must be passed in the environment variables: CONOHA_TENANT_ID, CONOHA_API_USERNAME, CONOHA_API_PASSWORD -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("CONOHA_TENANT_ID", "CONOHA_API_USERNAME", "CONOHA_API_PASSWORD") - if err != nil { - return nil, fmt.Errorf("conoha: %v", err) - } - - config := NewDefaultConfig() - config.TenantID = values["CONOHA_TENANT_ID"] - config.Username = values["CONOHA_API_USERNAME"] - config.Password = values["CONOHA_API_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for ConoHa DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("conoha: the configuration of the DNS provider is nil") - } - - if config.TenantID == "" || config.Username == "" || config.Password == "" { - return nil, errors.New("conoha: some credentials information are missing") - } - - auth := internal.Auth{ - TenantID: config.TenantID, - PasswordCredentials: internal.PasswordCredentials{ - Username: config.Username, - Password: config.Password, - }, - } - - client, err := internal.NewClient(config.Region, auth, config.HTTPClient) - if err != nil { - return nil, fmt.Errorf("conoha: failed to create client: %v", err) - } - - return &DNSProvider{config: config, client: client}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - id, err := d.client.GetDomainID(authZone) - if err != nil { - return fmt.Errorf("conoha: failed to get domain ID: %v", err) - } - - record := internal.Record{ - Name: fqdn, - Type: "TXT", - Data: value, - TTL: d.config.TTL, - } - - err = d.client.CreateRecord(id, record) - if err != nil { - return fmt.Errorf("conoha: failed to create record: %v", err) - } - - return nil -} - -// CleanUp clears ConoHa DNS TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - domID, err := d.client.GetDomainID(authZone) - if err != nil { - return fmt.Errorf("conoha: failed to get domain ID: %v", err) - } - - recID, err := d.client.GetRecordID(domID, fqdn, "TXT", value) - if err != nil { - return fmt.Errorf("conoha: failed to get record ID: %v", err) - } - - err = d.client.DeleteRecord(domID, recID) - if err != nil { - return fmt.Errorf("conoha: failed to delete record: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.toml b/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.toml deleted file mode 100644 index 7301451..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.toml +++ /dev/null @@ -1,22 +0,0 @@ -Name = "ConoHa" -Description = '''''' -URL = "https://www.conoha.jp/" -Code = "conoha" -Since = "v1.2.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - CONOHA_TENANT_ID = "Tenant ID" - CONOHA_API_USERNAME = "The API username" - CONOHA_API_PASSWORD = "The API password" - [Configuration.Additional] - CONOHA_POLLING_INTERVAL = "Time between DNS propagation check" - CONOHA_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - CONOHA_TTL = "The TTL of the TXT record used for the DNS challenge" - CONOHA_HTTP_TIMEOUT = "API request timeout" - CONOHA_REGION = "The region" - -[Links] - API = "https://www.conoha.jp/docs/" diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha_test.go b/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha_test.go deleted file mode 100644 index d73f2dd..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package conoha - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "CONOHA_TENANT_ID", - "CONOHA_API_USERNAME", - "CONOHA_API_PASSWORD"). - WithDomain("CONOHA_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "complete credentials, but login failed", - envVars: map[string]string{ - "CONOHA_TENANT_ID": "tenant_id", - "CONOHA_API_USERNAME": "api_username", - "CONOHA_API_PASSWORD": "api_password", - }, - expected: `conoha: failed to create client: failed to login: HTTP request failed with status code 401: {"unauthorized":{"message":"Invalid user: api_username","code":401}}`, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "CONOHA_TENANT_ID": "", - "CONOHA_API_USERNAME": "", - "CONOHA_API_PASSWORD": "", - }, - expected: "conoha: some credentials information are missing: CONOHA_TENANT_ID,CONOHA_API_USERNAME,CONOHA_API_PASSWORD", - }, - { - desc: "missing tenant id", - envVars: map[string]string{ - "CONOHA_TENANT_ID": "", - "CONOHA_API_USERNAME": "api_username", - "CONOHA_API_PASSWORD": "api_password", - }, - expected: "conoha: some credentials information are missing: CONOHA_TENANT_ID", - }, - { - desc: "missing api username", - envVars: map[string]string{ - "CONOHA_TENANT_ID": "tenant_id", - "CONOHA_API_USERNAME": "", - "CONOHA_API_PASSWORD": "api_password", - }, - expected: "conoha: some credentials information are missing: CONOHA_API_USERNAME", - }, - { - desc: "missing api password", - envVars: map[string]string{ - "CONOHA_TENANT_ID": "tenant_id", - "CONOHA_API_USERNAME": "api_username", - "CONOHA_API_PASSWORD": "", - }, - expected: "conoha: some credentials information are missing: CONOHA_API_PASSWORD", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - expected string - tenant string - username string - password string - }{ - { - desc: "complete credentials, but login failed", - expected: `conoha: failed to create client: failed to login: HTTP request failed with status code 401: {"unauthorized":{"message":"Invalid user: api_username","code":401}}`, - tenant: "tenant_id", - username: "api_username", - password: "api_password", - }, - { - desc: "missing credentials", - expected: "conoha: some credentials information are missing", - }, - { - desc: "missing tenant id", - expected: "conoha: some credentials information are missing", - username: "api_username", - password: "api_password", - }, - { - desc: "missing api username", - expected: "conoha: some credentials information are missing", - tenant: "tenant_id", - password: "api_password", - }, - { - desc: "missing api password", - expected: "conoha: some credentials information are missing", - tenant: "tenant_id", - username: "api_username", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.TenantID = test.tenant - config.Username = test.username - config.Password = test.password - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client.go deleted file mode 100644 index 3136a24..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client.go +++ /dev/null @@ -1,205 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" -) - -const ( - identityBaseURL = "https://identity.%s.conoha.io" - dnsServiceBaseURL = "https://dns-service.%s.conoha.io" -) - -// IdentityRequest is an authentication request body. -type IdentityRequest struct { - Auth Auth `json:"auth"` -} - -// Auth is an authentication information. -type Auth struct { - TenantID string `json:"tenantId"` - PasswordCredentials PasswordCredentials `json:"passwordCredentials"` -} - -// PasswordCredentials is API-user's credentials. -type PasswordCredentials struct { - Username string `json:"username"` - Password string `json:"password"` -} - -// IdentityResponse is an authentication response body. -type IdentityResponse struct { - Access Access `json:"access"` -} - -// Access is an identity information. -type Access struct { - Token Token `json:"token"` -} - -// Token is an api access token. -type Token struct { - ID string `json:"id"` -} - -// DomainListResponse is a response of a domain listing request. -type DomainListResponse struct { - Domains []Domain `json:"domains"` -} - -// Domain is a hosted domain entry. -type Domain struct { - ID string `json:"id"` - Name string `json:"name"` -} - -// RecordListResponse is a response of record listing request. -type RecordListResponse struct { - Records []Record `json:"records"` -} - -// Record is a record entry. -type Record struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Data string `json:"data"` - TTL int `json:"ttl"` -} - -// Client is a ConoHa API client. -type Client struct { - token string - endpoint string - httpClient *http.Client -} - -// NewClient returns a client instance logged into the ConoHa service. -func NewClient(region string, auth Auth, httpClient *http.Client) (*Client, error) { - if httpClient == nil { - httpClient = &http.Client{} - } - - c := &Client{httpClient: httpClient} - - c.endpoint = fmt.Sprintf(identityBaseURL, region) - - identity, err := c.getIdentity(auth) - if err != nil { - return nil, fmt.Errorf("failed to login: %v", err) - } - - c.token = identity.Access.Token.ID - c.endpoint = fmt.Sprintf(dnsServiceBaseURL, region) - - return c, nil -} - -func (c *Client) getIdentity(auth Auth) (*IdentityResponse, error) { - req := &IdentityRequest{Auth: auth} - - identity := &IdentityResponse{} - - err := c.do(http.MethodPost, "/v2.0/tokens", req, identity) - if err != nil { - return nil, err - } - - return identity, nil -} - -// GetDomainID returns an ID of specified domain. -func (c *Client) GetDomainID(domainName string) (string, error) { - domainList := &DomainListResponse{} - - err := c.do(http.MethodGet, "/v1/domains", nil, domainList) - if err != nil { - return "", err - } - - for _, domain := range domainList.Domains { - if domain.Name == domainName { - return domain.ID, nil - } - } - return "", fmt.Errorf("no such domain: %s", domainName) -} - -// GetRecordID returns an ID of specified record. -func (c *Client) GetRecordID(domainID, recordName, recordType, data string) (string, error) { - recordList := &RecordListResponse{} - - err := c.do(http.MethodGet, fmt.Sprintf("/v1/domains/%s/records", domainID), nil, recordList) - if err != nil { - return "", err - } - - for _, record := range recordList.Records { - if record.Name == recordName && record.Type == recordType && record.Data == data { - return record.ID, nil - } - } - return "", errors.New("no such record") -} - -// CreateRecord adds new record. -func (c *Client) CreateRecord(domainID string, record Record) error { - return c.do(http.MethodPost, fmt.Sprintf("/v1/domains/%s/records", domainID), record, nil) -} - -// DeleteRecord removes specified record. -func (c *Client) DeleteRecord(domainID, recordID string) error { - return c.do(http.MethodDelete, fmt.Sprintf("/v1/domains/%s/records/%s", domainID, recordID), nil, nil) -} - -func (c *Client) do(method, path string, payload, result interface{}) error { - body := bytes.NewReader(nil) - - if payload != nil { - bodyBytes, err := json.Marshal(payload) - if err != nil { - return err - } - body = bytes.NewReader(bodyBytes) - } - - req, err := http.NewRequest(method, c.endpoint+path, body) - if err != nil { - return err - } - - req.Header.Set("Accept", "application/json") - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Auth-Token", c.token) - - resp, err := c.httpClient.Do(req) - if err != nil { - return err - } - - if resp.StatusCode != http.StatusOK { - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - return fmt.Errorf("HTTP request failed with status code %d: %s", resp.StatusCode, string(respBody)) - } - - if result != nil { - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - return json.Unmarshal(respBody, result) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client_test.go deleted file mode 100644 index 75f2bdb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package internal - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/require" - - "github.com/stretchr/testify/assert" -) - -func setupClientTest() (*http.ServeMux, *Client, func()) { - mux := http.NewServeMux() - server := httptest.NewServer(mux) - - client := &Client{ - token: "secret", - endpoint: server.URL, - httpClient: &http.Client{Timeout: 5 * time.Second}, - } - - return mux, client, server.Close -} - -func TestClient_GetDomainID(t *testing.T) { - type expected struct { - domainID string - error bool - } - - testCases := []struct { - desc string - domainName string - handler http.HandlerFunc - expected expected - }{ - { - desc: "success", - domainName: "domain1.com.", - handler: func(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet { - http.Error(rw, fmt.Sprintf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), req.Method), http.StatusMethodNotAllowed) - return - } - - content := ` -{ - "domains":[ - { - "id": "09494b72-b65b-4297-9efb-187f65a0553e", - "name": "domain1.com.", - "ttl": 3600, - "serial": 1351800668, - "email": "nsadmin@example.org", - "gslb": 0, - "created_at": "2012-11-01T20:11:08.000000", - "updated_at": null, - "description": "memo" - }, - { - "id": "cf661142-e577-40b5-b3eb-75795cdc0cd7", - "name": "domain2.com.", - "ttl": 7200, - "serial": 1351800670, - "email": "nsadmin2@example.org", - "gslb": 1, - "created_at": "2012-11-01T20:11:08.000000", - "updated_at": "2012-12-01T20:11:08.000000", - "description": "memomemo" - } - ] -} -` - _, err := fmt.Fprint(rw, content) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - }, - expected: expected{domainID: "09494b72-b65b-4297-9efb-187f65a0553e"}, - }, - { - desc: "non existing domain", - domainName: "domain1.com.", - handler: func(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet { - http.Error(rw, fmt.Sprintf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), req.Method), http.StatusMethodNotAllowed) - return - } - - _, err := fmt.Fprint(rw, "{}") - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - }, - expected: expected{error: true}, - }, - { - desc: "marshaling error", - domainName: "domain1.com.", - handler: func(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet { - http.Error(rw, fmt.Sprintf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), req.Method), http.StatusMethodNotAllowed) - return - } - - _, err := fmt.Fprint(rw, "[]") - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - }, - expected: expected{error: true}, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - mux, client, tearDown := setupClientTest() - defer tearDown() - - mux.Handle("/v1/domains", test.handler) - - domainID, err := client.GetDomainID(test.domainName) - - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.domainID, domainID) - } - }) - } - -} - -func TestClient_CreateRecord(t *testing.T) { - testCases := []struct { - desc string - handler http.HandlerFunc - expectError bool - }{ - { - desc: "success", - handler: func(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - http.Error(rw, fmt.Sprintf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), req.Method), http.StatusMethodNotAllowed) - return - } - - raw, err := ioutil.ReadAll(req.Body) - if err != nil { - http.Error(rw, err.Error(), http.StatusBadRequest) - return - } - defer req.Body.Close() - - if string(raw) != `{"name":"lego.com.","type":"TXT","data":"txtTXTtxt","ttl":300}` { - http.Error(rw, fmt.Sprintf("invalid request body: %s", string(raw)), http.StatusBadRequest) - return - } - }, - }, - { - desc: "bad request", - handler: func(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - http.Error(rw, fmt.Sprintf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), req.Method), http.StatusMethodNotAllowed) - return - } - - http.Error(rw, "OOPS", http.StatusBadRequest) - }, - expectError: true, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - mux, client, tearDown := setupClientTest() - defer tearDown() - - mux.Handle("/v1/domains/lego/records", test.handler) - - domainID := "lego" - - record := Record{ - Name: "lego.com.", - Type: "TXT", - Data: "txtTXTtxt", - TTL: 300, - } - - err := client.CreateRecord(domainID, record) - - if test.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - - }) - } - -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/designate/designate.go b/vendor/github.com/go-acme/lego/providers/dns/designate/designate.go deleted file mode 100644 index 0727842..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/designate/designate.go +++ /dev/null @@ -1,249 +0,0 @@ -// Package designate implements a DNS provider for solving the DNS-01 challenge using the Designate DNSaaS for Openstack. -package designate - -import ( - "errors" - "fmt" - "log" - "os" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/openstack" - "github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets" - "github.com/gophercloud/gophercloud/openstack/dns/v2/zones" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - opts gophercloud.AuthOptions -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DESIGNATE_TTL", 10), - PropagationTimeout: env.GetOrDefaultSecond("DESIGNATE_PROPAGATION_TIMEOUT", 10*time.Minute), - PollingInterval: env.GetOrDefaultSecond("DESIGNATE_POLLING_INTERVAL", 10*time.Second), - } -} - -// DNSProvider describes a provider for Designate -type DNSProvider struct { - config *Config - client *gophercloud.ServiceClient - dnsEntriesMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for Designate. -// Credentials must be passed in the environment variables: -// OS_AUTH_URL, OS_USERNAME, OS_PASSWORD, OS_TENANT_NAME, OS_REGION_NAME. -func NewDNSProvider() (*DNSProvider, error) { - _, err := env.Get("OS_AUTH_URL", "OS_USERNAME", "OS_PASSWORD", "OS_TENANT_NAME", "OS_REGION_NAME") - if err != nil { - return nil, fmt.Errorf("designate: %v", err) - } - - opts, err := openstack.AuthOptionsFromEnv() - if err != nil { - return nil, fmt.Errorf("designate: %v", err) - } - - config := NewDefaultConfig() - config.opts = opts - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Designate. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("designate: the configuration of the DNS provider is nil") - } - - provider, err := openstack.AuthenticatedClient(config.opts) - if err != nil { - return nil, fmt.Errorf("designate: failed to authenticate: %v", err) - } - - dnsClient, err := openstack.NewDNSV2(provider, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) - if err != nil { - return nil, fmt.Errorf("designate: failed to get DNS provider: %v", err) - } - - return &DNSProvider{client: dnsClient, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("designate: couldn't get zone ID in Present: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("designate: %v", err) - } - - // use mutex to prevent race condition between creating the record and verifying it - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - existingRecord, err := d.getRecord(zoneID, fqdn) - if err != nil { - return fmt.Errorf("designate: %v", err) - } - - if existingRecord != nil { - if contains(existingRecord.Records, value) { - log.Printf("designate: the record already exists: %s", value) - return nil - } - - return d.updateRecord(existingRecord, value) - } - - err = d.createRecord(zoneID, fqdn, value) - if err != nil { - return fmt.Errorf("designate: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("designate: couldn't get zone ID in CleanUp: %v", err) - } - - // use mutex to prevent race condition between getting the record and deleting it - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - record, err := d.getRecord(zoneID, fqdn) - if err != nil { - return fmt.Errorf("designate: couldn't get Record ID in CleanUp: %v", err) - } - - if record == nil { - // Record is already deleted - return nil - } - - err = recordsets.Delete(d.client, zoneID, record.ID).ExtractErr() - if err != nil { - return fmt.Errorf("designate: error for %s in CleanUp: %v", fqdn, err) - } - return nil -} - -func contains(values []string, value string) bool { - for _, v := range values { - if v == value { - return true - } - } - return false -} - -func (d *DNSProvider) createRecord(zoneID, fqdn, value string) error { - createOpts := recordsets.CreateOpts{ - Name: fqdn, - Type: "TXT", - TTL: d.config.TTL, - Description: "ACME verification record", - Records: []string{value}, - } - - actual, err := recordsets.Create(d.client, zoneID, createOpts).Extract() - if err != nil { - return fmt.Errorf("error for %s in Present while creating record: %v", fqdn, err) - } - - if actual.Name != fqdn || actual.TTL != d.config.TTL { - return fmt.Errorf("the created record doesn't match what we wanted to create") - } - - return nil -} - -func (d *DNSProvider) updateRecord(record *recordsets.RecordSet, value string) error { - if contains(record.Records, value) { - log.Printf("skip: the record already exists: %s", value) - return nil - } - - values := append([]string{value}, record.Records...) - - updateOpts := recordsets.UpdateOpts{ - Description: &record.Description, - TTL: record.TTL, - Records: values, - } - - result := recordsets.Update(d.client, record.ZoneID, record.ID, updateOpts) - return result.Err -} - -func (d *DNSProvider) getZoneID(wanted string) (string, error) { - allPages, err := zones.List(d.client, nil).AllPages() - if err != nil { - return "", err - } - allZones, err := zones.ExtractZones(allPages) - if err != nil { - return "", err - } - - for _, zone := range allZones { - if zone.Name == wanted { - return zone.ID, nil - } - } - return "", fmt.Errorf("zone id not found for %s", wanted) -} - -func (d *DNSProvider) getRecord(zoneID string, wanted string) (*recordsets.RecordSet, error) { - allPages, err := recordsets.ListByZone(d.client, zoneID, nil).AllPages() - if err != nil { - return nil, err - } - allRecords, err := recordsets.ExtractRecordSets(allPages) - if err != nil { - return nil, err - } - - for _, record := range allRecords { - if record.Name == wanted { - return &record, nil - } - } - - return nil, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/designate/designate.toml b/vendor/github.com/go-acme/lego/providers/dns/designate/designate.toml deleted file mode 100644 index 799f5cd..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/designate/designate.toml +++ /dev/null @@ -1,23 +0,0 @@ -Name = "Designate DNSaaS for Openstack" -Description = '''''' -URL = "https://docs.openstack.org/designate/latest/" -Code = "designate" -Since = "v2.2.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - OS_AUTH_URL = "Identity endpoint URL" - OS_USERNAME = "Username" - OS_PASSWORD = "Password" - OS_TENANT_NAME = "Tenant name" - OS_REGION_NAME = "Region name" - [Configuration.Additional] - DESIGNATE_POLLING_INTERVAL = "Time between DNS propagation check" - DESIGNATE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DESIGNATE_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://docs.openstack.org/designate/latest/" - GoClient = "https://godoc.org/github.com/gophercloud/gophercloud/openstack/dns/v2" diff --git a/vendor/github.com/go-acme/lego/providers/dns/designate/designate_test.go b/vendor/github.com/go-acme/lego/providers/dns/designate/designate_test.go deleted file mode 100644 index 5f5fdda..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/designate/designate_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package designate - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "OS_AUTH_URL", - "OS_USERNAME", - "OS_PASSWORD", - "OS_TENANT_NAME", - "OS_REGION_NAME"). - WithDomain("DESIGNATE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - server := getServer() - defer server.Close() - - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "OS_AUTH_URL": server.URL + "/v2.0/", - "OS_USERNAME": "B", - "OS_PASSWORD": "C", - "OS_REGION_NAME": "D", - "OS_TENANT_NAME": "E", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "OS_AUTH_URL": "", - "OS_USERNAME": "", - "OS_PASSWORD": "", - "OS_REGION_NAME": "", - "OS_TENANT_NAME": "", - }, - expected: "designate: some credentials information are missing: OS_AUTH_URL,OS_USERNAME,OS_PASSWORD,OS_TENANT_NAME,OS_REGION_NAME", - }, - { - desc: "missing auth url", - envVars: map[string]string{ - "OS_AUTH_URL": "", - "OS_USERNAME": "B", - "OS_PASSWORD": "C", - "OS_REGION_NAME": "D", - "OS_TENANT_NAME": "E", - }, - expected: "designate: some credentials information are missing: OS_AUTH_URL", - }, - { - desc: "missing username", - envVars: map[string]string{ - "OS_AUTH_URL": server.URL + "/v2.0/", - "OS_USERNAME": "", - "OS_PASSWORD": "C", - "OS_REGION_NAME": "D", - "OS_TENANT_NAME": "E", - }, - expected: "designate: some credentials information are missing: OS_USERNAME", - }, - { - desc: "missing password", - envVars: map[string]string{ - "OS_AUTH_URL": server.URL + "/v2.0/", - "OS_USERNAME": "B", - "OS_PASSWORD": "", - "OS_REGION_NAME": "D", - "OS_TENANT_NAME": "E", - }, - expected: "designate: some credentials information are missing: OS_PASSWORD", - }, - { - desc: "missing region name", - envVars: map[string]string{ - "OS_AUTH_URL": server.URL + "/v2.0/", - "OS_USERNAME": "B", - "OS_PASSWORD": "C", - "OS_REGION_NAME": "", - "OS_TENANT_NAME": "E", - }, - expected: "designate: some credentials information are missing: OS_REGION_NAME", - }, - { - desc: "missing tenant name", - envVars: map[string]string{ - "OS_AUTH_URL": server.URL + "/v2.0/", - "OS_USERNAME": "B", - "OS_PASSWORD": "C", - "OS_REGION_NAME": "D", - "OS_TENANT_NAME": "", - }, - expected: "designate: some credentials information are missing: OS_TENANT_NAME", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - server := getServer() - defer server.Close() - - testCases := []struct { - desc string - tenantName string - password string - userName string - authURL string - expected string - }{ - { - desc: "success", - tenantName: "A", - password: "B", - userName: "C", - authURL: server.URL + "/v2.0/", - }, - { - desc: "wrong auth url", - tenantName: "A", - password: "B", - userName: "C", - authURL: server.URL, - expected: "designate: failed to authenticate: No supported version available from endpoint " + server.URL + "/", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.opts.TenantName = test.tenantName - config.opts.Password = test.password - config.opts.Username = test.userName - config.opts.IdentityEndpoint = test.authURL - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func getServer() *httptest.Server { - mux := http.NewServeMux() - mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`{ - "access": { - "token": { - "id": "a", - "expires": "9015-06-05T16:24:57.637Z" - }, - "user": { - "name": "a", - "roles": [ ], - "role_links": [ ] - }, - "serviceCatalog": [ - { - "endpoints": [ - { - "adminURL": "http://23.253.72.207:9696/", - "region": "D", - "internalURL": "http://23.253.72.207:9696/", - "id": "97c526db8d7a4c88bbb8d68db1bdcdb8", - "publicURL": "http://23.253.72.207:9696/" - } - ], - "endpoints_links": [ ], - "type": "dns", - "name": "designate" - } - ] - } -}`)) - w.WriteHeader(200) - }) - return httptest.NewServer(mux) -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/client.go b/vendor/github.com/go-acme/lego/providers/dns/digitalocean/client.go deleted file mode 100644 index 48e335a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/client.go +++ /dev/null @@ -1,132 +0,0 @@ -package digitalocean - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - - "github.com/go-acme/lego/challenge/dns01" -) - -const defaultBaseURL = "https://api.digitalocean.com" - -// txtRecordResponse represents a response from DO's API after making a TXT record -type txtRecordResponse struct { - DomainRecord record `json:"domain_record"` -} - -type record struct { - ID int `json:"id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Data string `json:"data,omitempty"` - TTL int `json:"ttl,omitempty"` -} - -type apiError struct { - ID string `json:"id"` - Message string `json:"message"` -} - -func (d *DNSProvider) removeTxtRecord(domain string, recordID int) error { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("could not determine zone for domain: '%s'. %s", domain, err) - } - - reqURL := fmt.Sprintf("%s/v2/domains/%s/records/%d", d.config.BaseURL, dns01.UnFqdn(authZone), recordID) - req, err := d.newRequest(http.MethodDelete, reqURL, nil) - if err != nil { - return err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return readError(req, resp) - } - - return nil -} - -func (d *DNSProvider) addTxtRecord(fqdn, value string) (*txtRecordResponse, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(fqdn)) - if err != nil { - return nil, fmt.Errorf("could not determine zone for domain: '%s'. %s", fqdn, err) - } - - reqData := record{Type: "TXT", Name: fqdn, Data: value, TTL: d.config.TTL} - body, err := json.Marshal(reqData) - if err != nil { - return nil, err - } - - reqURL := fmt.Sprintf("%s/v2/domains/%s/records", d.config.BaseURL, dns01.UnFqdn(authZone)) - req, err := d.newRequest(http.MethodPost, reqURL, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, readError(req, resp) - } - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.New(toUnreadableBodyMessage(req, content)) - } - - // Everything looks good; but we'll need the ID later to delete the record - respData := &txtRecordResponse{} - err = json.Unmarshal(content, respData) - if err != nil { - return nil, fmt.Errorf("%v: %s", err, toUnreadableBodyMessage(req, content)) - } - - return respData, nil -} - -func (d *DNSProvider) newRequest(method, reqURL string, body io.Reader) (*http.Request, error) { - req, err := http.NewRequest(method, reqURL, body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", d.config.AuthToken)) - - return req, nil -} - -func readError(req *http.Request, resp *http.Response) error { - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return errors.New(toUnreadableBodyMessage(req, content)) - } - - var errInfo apiError - err = json.Unmarshal(content, &errInfo) - if err != nil { - return fmt.Errorf("apiError unmarshaling error: %v: %s", err, toUnreadableBodyMessage(req, content)) - } - - return fmt.Errorf("HTTP %d: %s: %s", resp.StatusCode, errInfo.ID, errInfo.Message) -} - -func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.go b/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.go deleted file mode 100644 index 0492a59..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.go +++ /dev/null @@ -1,131 +0,0 @@ -// Package digitalocean implements a DNS provider for solving the DNS-01 challenge using digitalocean DNS. -package digitalocean - -import ( - "errors" - "fmt" - "net/http" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - AuthToken string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - TTL: env.GetOrDefaultInt("DO_TTL", 30), - PropagationTimeout: env.GetOrDefaultSecond("DO_PROPAGATION_TIMEOUT", 60*time.Second), - PollingInterval: env.GetOrDefaultSecond("DO_POLLING_INTERVAL", 5*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DO_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -// that uses DigitalOcean's REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - recordIDs map[string]int - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for Digital -// Ocean. Credentials must be passed in the environment variable: -// DO_AUTH_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DO_AUTH_TOKEN") - if err != nil { - return nil, fmt.Errorf("digitalocean: %v", err) - } - - config := NewDefaultConfig() - config.AuthToken = values["DO_AUTH_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Digital Ocean. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("digitalocean: the configuration of the DNS provider is nil") - } - - if config.AuthToken == "" { - return nil, fmt.Errorf("digitalocean: credentials missing") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - return &DNSProvider{ - config: config, - recordIDs: make(map[string]int), - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - respData, err := d.addTxtRecord(fqdn, value) - if err != nil { - return fmt.Errorf("digitalocean: %v", err) - } - - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = respData.DomainRecord.ID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("digitalocean: %v", err) - } - - // get the record's unique ID from when we created it - d.recordIDsMu.Lock() - recordID, ok := d.recordIDs[fqdn] - d.recordIDsMu.Unlock() - if !ok { - return fmt.Errorf("digitalocean: unknown record ID for '%s'", fqdn) - } - - err = d.removeTxtRecord(authZone, recordID) - if err != nil { - return fmt.Errorf("digitalocean: %v", err) - } - - // Delete record ID from map - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.toml b/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.toml deleted file mode 100644 index 7dbb123..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Digital Ocean" -Description = '''''' -URL = "https://www.digitalocean.com/docs/networking/dns/" -Code = "digitalocean" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DO_AUTH_TOKEN = "Authentication token" - [Configuration.Additional] - DO_POLLING_INTERVAL = "Time between DNS propagation check" - DO_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DO_TTL = "The TTL of the TXT record used for the DNS challenge" - DO_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://developers.digitalocean.com/documentation/v2/#domain-records" diff --git a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean_test.go b/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean_test.go deleted file mode 100644 index 5d818eb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean_test.go +++ /dev/null @@ -1,171 +0,0 @@ -package digitalocean - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("DO_AUTH_TOKEN") - -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) - - config := NewDefaultConfig() - config.AuthToken = "asdf1234" - config.BaseURL = server.URL - - provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } - - return provider, handler, server.Close -} - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DO_AUTH_TOKEN": "123", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "DO_AUTH_TOKEN": "", - }, - expected: "digitalocean: some credentials information are missing: DO_AUTH_TOKEN", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.recordIDs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - authToken string - expected string - }{ - { - desc: "success", - authToken: "123", - }, - { - desc: "missing credentials", - expected: "digitalocean: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.AuthToken = test.authToken - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.recordIDs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/v2/domains/example.com/records", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method, "method") - - assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") - assert.Equal(t, "Bearer asdf1234", r.Header.Get("Authorization"), "Authorization") - - reqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - - expectedReqBody := `{"type":"TXT","name":"_acme-challenge.example.com.","data":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":30}` - assert.Equal(t, expectedReqBody, string(reqBody)) - - w.WriteHeader(http.StatusCreated) - _, err = fmt.Fprintf(w, `{ - "domain_record": { - "id": 1234567, - "type": "TXT", - "name": "_acme-challenge", - "data": "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI", - "priority": null, - "port": null, - "weight": null - } - }`) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - err := provider.Present("example.com", "", "foobar") - require.NoError(t, err) -} - -func TestDNSProvider_CleanUp(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/v2/domains/example.com/records/1234567", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodDelete, r.Method, "method") - - assert.Equal(t, "/v2/domains/example.com/records/1234567", r.URL.Path, "Path") - - // NOTE: Even though the body is empty, DigitalOcean API docs still show setting this Content-Type... - assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") - assert.Equal(t, "Bearer asdf1234", r.Header.Get("Authorization"), "Authorization") - - w.WriteHeader(http.StatusNoContent) - }) - - provider.recordIDsMu.Lock() - provider.recordIDs["_acme-challenge.example.com."] = 1234567 - provider.recordIDsMu.Unlock() - - err := provider.CleanUp("example.com", "", "") - require.NoError(t, err, "fail to remove TXT record") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dns_providers.go b/vendor/github.com/go-acme/lego/providers/dns/dns_providers.go deleted file mode 100644 index 194db1d..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dns_providers.go +++ /dev/null @@ -1,189 +0,0 @@ -package dns - -import ( - "fmt" - - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/providers/dns/acmedns" - "github.com/go-acme/lego/providers/dns/alidns" - "github.com/go-acme/lego/providers/dns/auroradns" - "github.com/go-acme/lego/providers/dns/azure" - "github.com/go-acme/lego/providers/dns/bindman" - "github.com/go-acme/lego/providers/dns/bluecat" - "github.com/go-acme/lego/providers/dns/cloudflare" - "github.com/go-acme/lego/providers/dns/cloudns" - "github.com/go-acme/lego/providers/dns/cloudxns" - "github.com/go-acme/lego/providers/dns/conoha" - "github.com/go-acme/lego/providers/dns/designate" - "github.com/go-acme/lego/providers/dns/digitalocean" - "github.com/go-acme/lego/providers/dns/dnsimple" - "github.com/go-acme/lego/providers/dns/dnsmadeeasy" - "github.com/go-acme/lego/providers/dns/dnspod" - "github.com/go-acme/lego/providers/dns/dode" - "github.com/go-acme/lego/providers/dns/dreamhost" - "github.com/go-acme/lego/providers/dns/duckdns" - "github.com/go-acme/lego/providers/dns/dyn" - "github.com/go-acme/lego/providers/dns/easydns" - "github.com/go-acme/lego/providers/dns/exec" - "github.com/go-acme/lego/providers/dns/exoscale" - "github.com/go-acme/lego/providers/dns/fastdns" - "github.com/go-acme/lego/providers/dns/gandi" - "github.com/go-acme/lego/providers/dns/gandiv5" - "github.com/go-acme/lego/providers/dns/gcloud" - "github.com/go-acme/lego/providers/dns/glesys" - "github.com/go-acme/lego/providers/dns/godaddy" - "github.com/go-acme/lego/providers/dns/hostingde" - "github.com/go-acme/lego/providers/dns/httpreq" - "github.com/go-acme/lego/providers/dns/iij" - "github.com/go-acme/lego/providers/dns/inwx" - "github.com/go-acme/lego/providers/dns/joker" - "github.com/go-acme/lego/providers/dns/lightsail" - "github.com/go-acme/lego/providers/dns/linode" - "github.com/go-acme/lego/providers/dns/linodev4" - "github.com/go-acme/lego/providers/dns/mydnsjp" - "github.com/go-acme/lego/providers/dns/namecheap" - "github.com/go-acme/lego/providers/dns/namedotcom" - "github.com/go-acme/lego/providers/dns/netcup" - "github.com/go-acme/lego/providers/dns/nifcloud" - "github.com/go-acme/lego/providers/dns/ns1" - "github.com/go-acme/lego/providers/dns/oraclecloud" - "github.com/go-acme/lego/providers/dns/otc" - "github.com/go-acme/lego/providers/dns/ovh" - "github.com/go-acme/lego/providers/dns/pdns" - "github.com/go-acme/lego/providers/dns/rackspace" - "github.com/go-acme/lego/providers/dns/rfc2136" - "github.com/go-acme/lego/providers/dns/route53" - "github.com/go-acme/lego/providers/dns/sakuracloud" - "github.com/go-acme/lego/providers/dns/selectel" - "github.com/go-acme/lego/providers/dns/stackpath" - "github.com/go-acme/lego/providers/dns/transip" - "github.com/go-acme/lego/providers/dns/vegadns" - "github.com/go-acme/lego/providers/dns/vscale" - "github.com/go-acme/lego/providers/dns/vultr" - "github.com/go-acme/lego/providers/dns/zoneee" -) - -// NewDNSChallengeProviderByName Factory for DNS providers -func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { - switch name { - case "acme-dns": - return acmedns.NewDNSProvider() - case "alidns": - return alidns.NewDNSProvider() - case "azure": - return azure.NewDNSProvider() - case "auroradns": - return auroradns.NewDNSProvider() - case "bindman": - return bindman.NewDNSProvider() - case "bluecat": - return bluecat.NewDNSProvider() - case "cloudflare": - return cloudflare.NewDNSProvider() - case "cloudns": - return cloudns.NewDNSProvider() - case "cloudxns": - return cloudxns.NewDNSProvider() - case "conoha": - return conoha.NewDNSProvider() - case "designate": - return designate.NewDNSProvider() - case "digitalocean": - return digitalocean.NewDNSProvider() - case "dnsimple": - return dnsimple.NewDNSProvider() - case "dnsmadeeasy": - return dnsmadeeasy.NewDNSProvider() - case "dnspod": - return dnspod.NewDNSProvider() - case "dode": - return dode.NewDNSProvider() - case "dreamhost": - return dreamhost.NewDNSProvider() - case "duckdns": - return duckdns.NewDNSProvider() - case "dyn": - return dyn.NewDNSProvider() - case "fastdns": - return fastdns.NewDNSProvider() - case "easydns": - return easydns.NewDNSProvider() - case "exec": - return exec.NewDNSProvider() - case "exoscale": - return exoscale.NewDNSProvider() - case "gandi": - return gandi.NewDNSProvider() - case "gandiv5": - return gandiv5.NewDNSProvider() - case "glesys": - return glesys.NewDNSProvider() - case "gcloud": - return gcloud.NewDNSProvider() - case "godaddy": - return godaddy.NewDNSProvider() - case "hostingde": - return hostingde.NewDNSProvider() - case "httpreq": - return httpreq.NewDNSProvider() - case "iij": - return iij.NewDNSProvider() - case "inwx": - return inwx.NewDNSProvider() - case "joker": - return joker.NewDNSProvider() - case "lightsail": - return lightsail.NewDNSProvider() - case "linode": - return linode.NewDNSProvider() - case "linodev4": - return linodev4.NewDNSProvider() - case "manual": - return dns01.NewDNSProviderManual() - case "mydnsjp": - return mydnsjp.NewDNSProvider() - case "namecheap": - return namecheap.NewDNSProvider() - case "namedotcom": - return namedotcom.NewDNSProvider() - case "netcup": - return netcup.NewDNSProvider() - case "nifcloud": - return nifcloud.NewDNSProvider() - case "ns1": - return ns1.NewDNSProvider() - case "oraclecloud": - return oraclecloud.NewDNSProvider() - case "otc": - return otc.NewDNSProvider() - case "ovh": - return ovh.NewDNSProvider() - case "pdns": - return pdns.NewDNSProvider() - case "rackspace": - return rackspace.NewDNSProvider() - case "route53": - return route53.NewDNSProvider() - case "rfc2136": - return rfc2136.NewDNSProvider() - case "sakuracloud": - return sakuracloud.NewDNSProvider() - case "stackpath": - return stackpath.NewDNSProvider() - case "selectel": - return selectel.NewDNSProvider() - case "transip": - return transip.NewDNSProvider() - case "vegadns": - return vegadns.NewDNSProvider() - case "vultr": - return vultr.NewDNSProvider() - case "vscale": - return vscale.NewDNSProvider() - case "zoneee": - return zoneee.NewDNSProvider() - default: - return nil, fmt.Errorf("unrecognised DNS provider: %s", name) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dns_providers_test.go b/vendor/github.com/go-acme/lego/providers/dns/dns_providers_test.go deleted file mode 100644 index 2ff7a2c..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dns_providers_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package dns - -import ( - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/go-acme/lego/providers/dns/exec" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("EXEC_PATH") - -func TestKnownDNSProviderSuccess(t *testing.T) { - defer envTest.RestoreEnv() - envTest.Apply(map[string]string{ - "EXEC_PATH": "abc", - }) - - provider, err := NewDNSChallengeProviderByName("exec") - require.NoError(t, err) - assert.NotNil(t, provider) - - assert.IsType(t, &exec.DNSProvider{}, provider, "The loaded DNS provider doesn't have the expected type.") -} - -func TestKnownDNSProviderError(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - provider, err := NewDNSChallengeProviderByName("exec") - assert.Error(t, err) - assert.Nil(t, provider) -} - -func TestUnknownDNSProvider(t *testing.T) { - provider, err := NewDNSChallengeProviderByName("foobar") - assert.Error(t, err) - assert.Nil(t, provider) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.go b/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.go deleted file mode 100644 index ac26e30..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.go +++ /dev/null @@ -1,211 +0,0 @@ -// Package dnsimple implements a DNS provider for solving the DNS-01 challenge using dnsimple DNS. -package dnsimple - -import ( - "context" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/dnsimple/dnsimple-go/dnsimple" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "golang.org/x/oauth2" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AccessToken string - BaseURL string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DNSIMPLE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("DNSIMPLE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DNSIMPLE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *dnsimple.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for dnsimple. -// Credentials must be passed in the environment variables: DNSIMPLE_OAUTH_TOKEN. -// -// See: https://developer.dnsimple.com/v2/#authentication -func NewDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - config.AccessToken = env.GetOrFile("DNSIMPLE_OAUTH_TOKEN") - config.BaseURL = env.GetOrFile("DNSIMPLE_BASE_URL") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DNSimple. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dnsimple: the configuration of the DNS provider is nil") - } - - if config.AccessToken == "" { - return nil, fmt.Errorf("dnsimple: OAuth token is missing") - } - - ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: config.AccessToken}) - client := dnsimple.NewClient(oauth2.NewClient(context.Background(), ts)) - - if config.BaseURL != "" { - client.BaseURL = config.BaseURL - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zoneName, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - accountID, err := d.getAccountID() - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - recordAttributes := newTxtRecord(zoneName, fqdn, value, d.config.TTL) - _, err = d.client.Zones.CreateRecord(accountID, zoneName, recordAttributes) - if err != nil { - return fmt.Errorf("dnsimple: API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - accountID, err := d.getAccountID() - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - var lastErr error - for _, rec := range records { - _, err := d.client.Zones.DeleteRecord(accountID, rec.ZoneID, rec.ID) - if err != nil { - lastErr = fmt.Errorf("dnsimple: %v", err) - } - } - - return lastErr -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(domain string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", err - } - - accountID, err := d.getAccountID() - if err != nil { - return "", err - } - - zoneName := dns01.UnFqdn(authZone) - - zones, err := d.client.Zones.ListZones(accountID, &dnsimple.ZoneListOptions{NameLike: zoneName}) - if err != nil { - return "", fmt.Errorf("API call failed: %v", err) - } - - var hostedZone dnsimple.Zone - for _, zone := range zones.Data { - if zone.Name == zoneName { - hostedZone = zone - } - } - - if hostedZone.ID == 0 { - return "", fmt.Errorf("zone %s not found in DNSimple for domain %s", authZone, domain) - } - - return hostedZone.Name, nil -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) ([]dnsimple.ZoneRecord, error) { - zoneName, err := d.getHostedZone(domain) - if err != nil { - return nil, err - } - - accountID, err := d.getAccountID() - if err != nil { - return nil, err - } - - recordName := extractRecordName(fqdn, zoneName) - - result, err := d.client.Zones.ListRecords(accountID, zoneName, &dnsimple.ZoneRecordListOptions{Name: recordName, Type: "TXT", ListOptions: dnsimple.ListOptions{}}) - if err != nil { - return nil, fmt.Errorf("API call has failed: %v", err) - } - - return result.Data, nil -} - -func newTxtRecord(zoneName, fqdn, value string, ttl int) dnsimple.ZoneRecord { - name := extractRecordName(fqdn, zoneName) - - return dnsimple.ZoneRecord{ - Type: "TXT", - Name: name, - Content: value, - TTL: ttl, - } -} - -func extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} - -func (d *DNSProvider) getAccountID() (string, error) { - whoamiResponse, err := d.client.Identity.Whoami() - if err != nil { - return "", err - } - - if whoamiResponse.Data.Account == nil { - return "", fmt.Errorf("user tokens are not supported, please use an account token") - } - - return strconv.FormatInt(whoamiResponse.Data.Account.ID, 10), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.toml b/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.toml deleted file mode 100644 index 5a78e76..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "DNSimple" -Description = '''''' -URL = "https://dnsimple.com/" -Code = "dnsimple" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DNSIMPLE_OAUTH_TOKEN = "OAuth token" - DNSIMPLE_BASE_URL = "API endpoint URL" - [Configuration.Additional] - DNSIMPLE_POLLING_INTERVAL = "Time between DNS propagation check" - DNSIMPLE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DNSIMPLE_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://developer.dnsimple.com/v2/" - GoClient = "https://github.com/dnsimple/dnsimple-go" diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple_test.go b/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple_test.go deleted file mode 100644 index ad6107d..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package dnsimple - -import ( - "os" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const sandboxURL = "https://api.sandbox.fake.com" - -var envTest = tester.NewEnvTest( - "DNSIMPLE_OAUTH_TOKEN", - "DNSIMPLE_BASE_URL"). - WithDomain("DNSIMPLE_DOMAIN"). - WithLiveTestRequirements("DNSIMPLE_OAUTH_TOKEN", "DNSIMPLE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DNSIMPLE_OAUTH_TOKEN": "my_token", - }, - }, - { - desc: "success: base url", - envVars: map[string]string{ - "DNSIMPLE_OAUTH_TOKEN": "my_token", - "DNSIMPLE_BASE_URL": "https://api.dnsimple.test", - }, - }, - { - desc: "missing oauth token", - envVars: map[string]string{ - "DNSIMPLE_OAUTH_TOKEN": "", - }, - expected: "dnsimple: OAuth token is missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - - baseURL := os.Getenv("DNSIMPLE_BASE_URL") - if baseURL != "" { - assert.Equal(t, baseURL, p.client.BaseURL) - } - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - accessToken string - baseURL string - expected string - }{ - { - desc: "success", - accessToken: "my_token", - baseURL: "", - }, - { - desc: "success: base url", - accessToken: "my_token", - baseURL: "https://api.dnsimple.test", - }, - { - desc: "missing oauth token", - expected: "dnsimple: OAuth token is missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.AccessToken = test.accessToken - config.BaseURL = test.baseURL - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - - if test.baseURL != "" { - assert.Equal(t, test.baseURL, p.client.BaseURL) - } - - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - if len(os.Getenv("DNSIMPLE_BASE_URL")) == 0 { - os.Setenv("DNSIMPLE_BASE_URL", sandboxURL) - } - - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - if len(os.Getenv("DNSIMPLE_BASE_URL")) == 0 { - os.Setenv("DNSIMPLE_BASE_URL", sandboxURL) - } - - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.go b/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.go deleted file mode 100644 index 0d38ef1..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.go +++ /dev/null @@ -1,163 +0,0 @@ -// Package dnsmadeeasy implements a DNS provider for solving the DNS-01 challenge using DNS Made Easy. -package dnsmadeeasy - -import ( - "crypto/tls" - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - APISecret string - Sandbox bool - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DNSMADEEASY_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("DNSMADEEASY_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DNSMADEEASY_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DNSMADEEASY_HTTP_TIMEOUT", 10*time.Second), - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// DNSMadeEasy's DNS API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for DNSMadeEasy DNS. -// Credentials must be passed in the environment variables: -// DNSMADEEASY_API_KEY and DNSMADEEASY_API_SECRET. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DNSMADEEASY_API_KEY", "DNSMADEEASY_API_SECRET") - if err != nil { - return nil, fmt.Errorf("dnsmadeeasy: %v", err) - } - - config := NewDefaultConfig() - config.Sandbox = env.GetOrDefaultBool("DNSMADEEASY_SANDBOX", false) - config.APIKey = values["DNSMADEEASY_API_KEY"] - config.APISecret = values["DNSMADEEASY_API_SECRET"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DNS Made Easy. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dnsmadeeasy: the configuration of the DNS provider is nil") - } - - var baseURL string - if config.Sandbox { - baseURL = "https://api.sandbox.dnsmadeeasy.com/V2.0" - } else { - if len(config.BaseURL) > 0 { - baseURL = config.BaseURL - } else { - baseURL = "https://api.dnsmadeeasy.com/V2.0" - } - } - - client, err := internal.NewClient(config.APIKey, config.APISecret) - if err != nil { - return nil, fmt.Errorf("dnsmadeeasy: %v", err) - } - - client.HTTPClient = config.HTTPClient - client.BaseURL = baseURL - - return &DNSProvider{ - client: client, - config: config, - }, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domainName, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domainName, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to find zone for %s: %v", fqdn, err) - } - - // fetch the domain details - domain, err := d.client.GetDomain(authZone) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to get domain for zone %s: %v", authZone, err) - } - - // create the TXT record - name := strings.Replace(fqdn, "."+authZone, "", 1) - record := &internal.Record{Type: "TXT", Name: name, Value: value, TTL: d.config.TTL} - - err = d.client.CreateRecord(domain, record) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to create record for %s: %v", name, err) - } - return nil -} - -// CleanUp removes the TXT records matching the specified parameters -func (d *DNSProvider) CleanUp(domainName, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domainName, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to find zone for %s: %v", fqdn, err) - } - - // fetch the domain details - domain, err := d.client.GetDomain(authZone) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to get domain for zone %s: %v", authZone, err) - } - - // find matching records - name := strings.Replace(fqdn, "."+authZone, "", 1) - records, err := d.client.GetRecords(domain, name, "TXT") - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to get records for domain %s: %v", domain.Name, err) - } - - // delete records - var lastError error - for _, record := range *records { - err = d.client.DeleteRecord(record) - if err != nil { - lastError = fmt.Errorf("dnsmadeeasy: unable to delete record [id=%d, name=%s]: %v", record.ID, record.Name, err) - } - } - - return lastError -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.toml b/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.toml deleted file mode 100644 index a3e9270..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "DNS Made Easy" -Description = '''''' -URL = "https://dnsmadeeasy.com/" -Code = "dnsmadeeasy" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DNSMADEEASY_API_KEY = "The API key" - DNSMADEEASY_API_SECRET = "The API Secret key" - [Configuration.Additional] - DNSMADEEASY_SANDBOX = "Activate the sandbox (boolean)" - DNSMADEEASY_POLLING_INTERVAL = "Time between DNS propagation check" - DNSMADEEASY_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DNSMADEEASY_TTL = "The TTL of the TXT record used for the DNS challenge" - DNSMADEEASY_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://api-docs.dnsmadeeasy.com/" diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go b/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go deleted file mode 100644 index 88e8633..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package dnsmadeeasy - -import ( - "os" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "DNSMADEEASY_API_KEY", - "DNSMADEEASY_API_SECRET"). - WithDomain("DNSMADEEASY_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - os.Setenv("DNSMADEEASY_SANDBOX", "true") - - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DNSMADEEASY_API_KEY": "123", - "DNSMADEEASY_API_SECRET": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "DNSMADEEASY_API_KEY": "", - "DNSMADEEASY_API_SECRET": "", - }, - expected: "dnsmadeeasy: some credentials information are missing: DNSMADEEASY_API_KEY,DNSMADEEASY_API_SECRET", - }, - { - desc: "missing access key", - envVars: map[string]string{ - "DNSMADEEASY_API_KEY": "", - "DNSMADEEASY_API_SECRET": "456", - }, - expected: "dnsmadeeasy: some credentials information are missing: DNSMADEEASY_API_KEY", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "DNSMADEEASY_API_KEY": "123", - "DNSMADEEASY_API_SECRET": "", - }, - expected: "dnsmadeeasy: some credentials information are missing: DNSMADEEASY_API_SECRET", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - os.Setenv("DNSMADEEASY_SANDBOX", "true") - - testCases := []struct { - desc string - apiKey string - apiSecret string - expected string - }{ - { - desc: "success", - apiKey: "123", - apiSecret: "456", - }, - { - desc: "missing credentials", - expected: "dnsmadeeasy: credentials missing: API key", - }, - { - desc: "missing api key", - apiSecret: "456", - expected: "dnsmadeeasy: credentials missing: API key", - }, - { - desc: "missing secret key", - apiKey: "123", - expected: "dnsmadeeasy: credentials missing: API secret", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.APISecret = test.apiSecret - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresentAndCleanup(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - os.Setenv("DNSMADEEASY_SANDBOX", "true") - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal/client.go deleted file mode 100644 index 748d385..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal/client.go +++ /dev/null @@ -1,173 +0,0 @@ -package internal - -import ( - "bytes" - "crypto/hmac" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "time" -) - -// Domain holds the DNSMadeEasy API representation of a Domain -type Domain struct { - ID int `json:"id"` - Name string `json:"name"` -} - -// Record holds the DNSMadeEasy API representation of a Domain Record -type Record struct { - ID int `json:"id"` - Type string `json:"type"` - Name string `json:"name"` - Value string `json:"value"` - TTL int `json:"ttl"` - SourceID int `json:"sourceId"` -} - -type recordsResponse struct { - Records *[]Record `json:"data"` -} - -// Client DNSMadeEasy client -type Client struct { - apiKey string - apiSecret string - BaseURL string - HTTPClient *http.Client -} - -// NewClient creates a DNSMadeEasy client -func NewClient(apiKey string, apiSecret string) (*Client, error) { - if apiKey == "" { - return nil, fmt.Errorf("credentials missing: API key") - } - - if apiSecret == "" { - return nil, fmt.Errorf("credentials missing: API secret") - } - - return &Client{ - apiKey: apiKey, - apiSecret: apiSecret, - HTTPClient: &http.Client{}, - }, nil -} - -// GetDomain gets a domain -func (c *Client) GetDomain(authZone string) (*Domain, error) { - domainName := authZone[0 : len(authZone)-1] - resource := fmt.Sprintf("%s%s", "/dns/managed/name?domainname=", domainName) - - resp, err := c.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - domain := &Domain{} - err = json.NewDecoder(resp.Body).Decode(&domain) - if err != nil { - return nil, err - } - - return domain, nil -} - -// GetRecords gets all TXT records -func (c *Client) GetRecords(domain *Domain, recordName, recordType string) (*[]Record, error) { - resource := fmt.Sprintf("%s/%d/%s%s%s%s", "/dns/managed", domain.ID, "records?recordName=", recordName, "&type=", recordType) - - resp, err := c.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - records := &recordsResponse{} - err = json.NewDecoder(resp.Body).Decode(&records) - if err != nil { - return nil, err - } - - return records.Records, nil -} - -// CreateRecord creates a TXT records -func (c *Client) CreateRecord(domain *Domain, record *Record) error { - url := fmt.Sprintf("%s/%d/%s", "/dns/managed", domain.ID, "records") - - resp, err := c.sendRequest(http.MethodPost, url, record) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// DeleteRecord deletes a TXT records -func (c *Client) DeleteRecord(record Record) error { - resource := fmt.Sprintf("%s/%d/%s/%d", "/dns/managed", record.SourceID, "records", record.ID) - - resp, err := c.sendRequest(http.MethodDelete, resource, nil) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Client) sendRequest(method, resource string, payload interface{}) (*http.Response, error) { - url := fmt.Sprintf("%s%s", c.BaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - timestamp := time.Now().UTC().Format(time.RFC1123) - signature, err := computeHMAC(timestamp, c.apiSecret) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("x-dnsme-apiKey", c.apiKey) - req.Header.Set("x-dnsme-requestDate", timestamp) - req.Header.Set("x-dnsme-hmac", signature) - req.Header.Set("accept", "application/json") - req.Header.Set("content-type", "application/json") - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - - if resp.StatusCode > 299 { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("request failed with HTTP status code %d", resp.StatusCode) - } - return nil, fmt.Errorf("request failed with HTTP status code %d: %s", resp.StatusCode, string(body)) - } - - return resp, nil -} - -func computeHMAC(message string, secret string) (string, error) { - key := []byte(secret) - h := hmac.New(sha1.New, key) - _, err := h.Write([]byte(message)) - if err != nil { - return "", err - } - return hex.EncodeToString(h.Sum(nil)), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.go b/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.go deleted file mode 100644 index 506836d..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.go +++ /dev/null @@ -1,189 +0,0 @@ -// Package dnspod implements a DNS provider for solving the DNS-01 challenge using dnspod DNS. -package dnspod - -import ( - "errors" - "fmt" - "net/http" - "strconv" - "strings" - "time" - - dnspod "github.com/decker502/dnspod-go" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - LoginToken string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DNSPOD_TTL", 600), - PropagationTimeout: env.GetOrDefaultSecond("DNSPOD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DNSPOD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DNSPOD_HTTP_TIMEOUT", 0), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *dnspod.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for dnspod. -// Credentials must be passed in the environment variables: DNSPOD_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DNSPOD_API_KEY") - if err != nil { - return nil, fmt.Errorf("dnspod: %v", err) - } - - config := NewDefaultConfig() - config.LoginToken = values["DNSPOD_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for dnspod. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dnspod: the configuration of the DNS provider is nil") - } - - if config.LoginToken == "" { - return nil, fmt.Errorf("dnspod: credentials missing") - } - - params := dnspod.CommonParams{LoginToken: config.LoginToken, Format: "json"} - - client := dnspod.NewClient(params) - client.HttpClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zoneID, zoneName, err := d.getHostedZone(domain) - if err != nil { - return err - } - - recordAttributes := d.newTxtRecord(zoneName, fqdn, value, d.config.TTL) - _, _, err = d.client.Domains.CreateRecord(zoneID, *recordAttributes) - if err != nil { - return fmt.Errorf("API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return err - } - - zoneID, _, err := d.getHostedZone(domain) - if err != nil { - return err - } - - for _, rec := range records { - _, err := d.client.Domains.DeleteRecord(zoneID, rec.ID) - if err != nil { - return err - } - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(domain string) (string, string, error) { - zones, _, err := d.client.Domains.List() - if err != nil { - return "", "", fmt.Errorf("API call failed: %v", err) - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - - var hostedZone dnspod.Domain - for _, zone := range zones { - if zone.Name == dns01.UnFqdn(authZone) { - hostedZone = zone - } - } - - if hostedZone.ID == 0 { - return "", "", fmt.Errorf("zone %s not found in dnspod for domain %s", authZone, domain) - - } - - return fmt.Sprintf("%v", hostedZone.ID), hostedZone.Name, nil -} - -func (d *DNSProvider) newTxtRecord(zone, fqdn, value string, ttl int) *dnspod.Record { - name := d.extractRecordName(fqdn, zone) - - return &dnspod.Record{ - Type: "TXT", - Name: name, - Value: value, - Line: "默认", - TTL: strconv.Itoa(ttl), - } -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) ([]dnspod.Record, error) { - zoneID, zoneName, err := d.getHostedZone(domain) - if err != nil { - return nil, err - } - - var records []dnspod.Record - result, _, err := d.client.Domains.ListRecords(zoneID, "") - if err != nil { - return records, fmt.Errorf("API call has failed: %v", err) - } - - recordName := d.extractRecordName(fqdn, zoneName) - - for _, record := range result { - if record.Name == recordName { - records = append(records, record) - } - } - - return records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.toml b/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.toml deleted file mode 100644 index 60aaea7..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "DNSPod" -Description = '''''' -URL = "http://www.dnspod.com/" -Code = "dnspod" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DNSPOD_API_KEY = "The user token" - [Configuration.Additional] - DNSPOD_POLLING_INTERVAL = "Time between DNS propagation check" - DNSPOD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DNSPOD_TTL = "The TTL of the TXT record used for the DNS challenge" - DNSPOD_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.dnspod.com/docs/index.html" - GoClient = "https://github.com/decker502/dnspod-go" diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod_test.go b/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod_test.go deleted file mode 100644 index aff591f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package dnspod - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("DNSPOD_API_KEY"). - WithDomain("DNSPOD_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DNSPOD_API_KEY": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "DNSPOD_API_KEY": "", - }, - expected: "dnspod: some credentials information are missing: DNSPOD_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - loginToken string - expected string - }{ - { - desc: "success", - loginToken: "123", - }, - { - desc: "missing credentials", - expected: "dnspod: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.LoginToken = test.loginToken - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dode/client.go b/vendor/github.com/go-acme/lego/providers/dns/dode/client.go deleted file mode 100644 index 193b516..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dode/client.go +++ /dev/null @@ -1,57 +0,0 @@ -package dode - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/url" - - "github.com/go-acme/lego/challenge/dns01" -) - -type apiResponse struct { - Domain string - Success bool -} - -// updateTxtRecord Update the domains TXT record -// To update the TXT record we just need to make one simple get request. -func (d *DNSProvider) updateTxtRecord(fqdn, token, txt string, clear bool) error { - u, _ := url.Parse("https://www.do.de/api/letsencrypt") - - query := u.Query() - query.Set("token", token) - query.Set("domain", dns01.UnFqdn(fqdn)) - - // api call differs per set/delete - if clear { - query.Set("action", "delete") - } else { - query.Set("value", txt) - } - - u.RawQuery = query.Encode() - - response, err := d.config.HTTPClient.Get(u.String()) - if err != nil { - return err - } - defer response.Body.Close() - - bodyBytes, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - - var r apiResponse - err = json.Unmarshal(bodyBytes, &r) - if err != nil { - return fmt.Errorf("request to change TXT record for do.de returned the following invalid json (%s); used url [%s]", string(bodyBytes), u) - } - - body := string(bodyBytes) - if !r.Success { - return fmt.Errorf("request to change TXT record for do.de returned the following error result (%s); used url [%s]", body, u) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dode/dode.go b/vendor/github.com/go-acme/lego/providers/dns/dode/dode.go deleted file mode 100644 index 693543a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dode/dode.go +++ /dev/null @@ -1,89 +0,0 @@ -// Package dode implements a DNS provider for solving the DNS-01 challenge using do.de. -package dode - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("DODE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DODE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - SequenceInterval: env.GetOrDefaultSecond("DODE_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DODE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DODE_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DODE_TOKEN") - if err != nil { - return nil, fmt.Errorf("do.de: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["DODE_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for do.de. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("do.de: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("do.de: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, txtRecord := dns01.GetRecord(domain, keyAuth) - return d.updateTxtRecord(fqdn, d.config.Token, txtRecord, false) -} - -// CleanUp clears TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - return d.updateTxtRecord(fqdn, d.config.Token, "", true) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dode/dode.toml b/vendor/github.com/go-acme/lego/providers/dns/dode/dode.toml deleted file mode 100644 index 470b730..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dode/dode.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Domain Offensive (do.de)" -Description = '''''' -URL = "https://www.do.de/" -Code = "dode" -Since = "v2.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DODE_TOKEN = "API token" - [Configuration.Additional] - DODE_POLLING_INTERVAL = "Time between DNS propagation check" - DODE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DODE_TTL = "The TTL of the TXT record used for the DNS challenge" - DODE_HTTP_TIMEOUT = "API request timeout" - DODE_SEQUENCE_INTERVAL = "Interval between iteration" - -[Links] - API = "https://www.do.de/wiki/LetsEncrypt_-_Entwickler" diff --git a/vendor/github.com/go-acme/lego/providers/dns/dode/dode_test.go b/vendor/github.com/go-acme/lego/providers/dns/dode/dode_test.go deleted file mode 100644 index f000703..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dode/dode_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package dode - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("DODE_TOKEN"). - WithDomain("DODE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DODE_TOKEN": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "DODE_TOKEN": "", - }, - expected: "do.de: some credentials information are missing: DODE_TOKEN", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - token string - expected string - }{ - { - desc: "success", - token: "123", - }, - { - desc: "missing credentials", - expected: "do.de: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Token = test.token - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client.go b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client.go deleted file mode 100644 index 9734d55..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client.go +++ /dev/null @@ -1,73 +0,0 @@ -package dreamhost - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/url" - - "github.com/go-acme/lego/log" -) - -const ( - defaultBaseURL = "https://api.dreamhost.com" - - cmdAddRecord = "dns-add_record" - cmdRemoveRecord = "dns-remove_record" -) - -type apiResponse struct { - Data string `json:"data"` - Result string `json:"result"` -} - -func (d *DNSProvider) buildQuery(action, domain, txt string) (*url.URL, error) { - u, err := url.Parse(d.config.BaseURL) - if err != nil { - return nil, err - } - - query := u.Query() - query.Set("key", d.config.APIKey) - query.Set("cmd", action) - query.Set("format", "json") - query.Set("record", domain) - query.Set("type", "TXT") - query.Set("value", txt) - query.Set("comment", url.QueryEscape("Managed By lego")) - u.RawQuery = query.Encode() - - return u, nil -} - -// updateTxtRecord will either add or remove a TXT record. -// action is either cmdAddRecord or cmdRemoveRecord -func (d *DNSProvider) updateTxtRecord(u fmt.Stringer) error { - resp, err := d.config.HTTPClient.Get(u.String()) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - return fmt.Errorf("request failed with HTTP status code %d", resp.StatusCode) - } - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("failed to read body: %v", err) - } - - var response apiResponse - err = json.Unmarshal(raw, &response) - if err != nil { - return fmt.Errorf("unable to decode API server response: %v: %s", err, string(raw)) - } - - if response.Result == "error" { - return fmt.Errorf("add TXT record failed: %s", response.Data) - } - - log.Infof("dreamhost: %s", response.Data) - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client_test.go deleted file mode 100644 index c8d195b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package dreamhost - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestDNSProvider_buildQuery(t *testing.T) { - testCases := []struct { - desc string - apiKey string - baseURL string - action string - domain string - txt string - expected string - }{ - { - desc: "success", - apiKey: fakeAPIKey, - action: cmdAddRecord, - domain: "domain", - txt: "TXTtxtTXT", - expected: "https://api.dreamhost.com?cmd=dns-add_record&comment=Managed%2BBy%2Blego&format=json&key=asdf1234&record=domain&type=TXT&value=TXTtxtTXT", - }, - { - desc: "Invalid base URL", - apiKey: fakeAPIKey, - baseURL: ":", - action: cmdAddRecord, - domain: "domain", - txt: "TXTtxtTXT", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - config := NewDefaultConfig() - config.APIKey = test.apiKey - if test.baseURL != "" { - config.BaseURL = test.baseURL - } - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - require.NotNil(t, provider) - - u, err := provider.buildQuery(test.action, test.domain, test.txt) - - if test.expected == "" { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected, u.String()) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.go b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.go deleted file mode 100644 index c781603..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package dreamhost implements a DNS provider for solving the DNS-01 challenge using DreamHost. -// See https://help.dreamhost.com/hc/en-us/articles/217560167-API_overview -// and https://help.dreamhost.com/hc/en-us/articles/217555707-DNS-API-commands for the API spec. -package dreamhost - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - PropagationTimeout: env.GetOrDefaultSecond("DREAMHOST_PROPAGATION_TIMEOUT", 60*time.Minute), - PollingInterval: env.GetOrDefaultSecond("DREAMHOST_POLLING_INTERVAL", 1*time.Minute), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DREAMHOST_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DREAMHOST_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DREAMHOST_API_KEY") - if err != nil { - return nil, fmt.Errorf("dreamhost: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["DREAMHOST_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DreamHost. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dreamhost: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, errors.New("dreamhost: credentials missing") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - record := dns01.UnFqdn(fqdn) - - u, err := d.buildQuery(cmdAddRecord, record, value) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - - err = d.updateTxtRecord(u) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - return nil -} - -// CleanUp clears DreamHost TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - record := dns01.UnFqdn(fqdn) - - u, err := d.buildQuery(cmdRemoveRecord, record, value) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - - err = d.updateTxtRecord(u) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.toml b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.toml deleted file mode 100644 index 4e6eeb1..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "DreamHost" -Description = '''''' -URL = "https://www.dreamhost.com" -Code = "dreamhost" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DREAMHOST_API_KEY = "The API key" - [Configuration.Additional] - DREAMHOST_POLLING_INTERVAL = "Time between DNS propagation check" - DREAMHOST_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DREAMHOST_TTL = "The TTL of the TXT record used for the DNS challenge" - DREAMHOST_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://help.dreamhost.com/hc/en-us/articles/217560167-API_overview" diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost_test.go b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost_test.go deleted file mode 100644 index c6dfc97..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package dreamhost - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("DREAMHOST_API_KEY"). - WithDomain("DREAMHOST_TEST_DOMAIN") - -const ( - fakeAPIKey = "asdf1234" - fakeChallengeToken = "foobar" - fakeKeyAuth = "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI" -) - -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) - - config := NewDefaultConfig() - config.APIKey = fakeAPIKey - config.BaseURL = server.URL - - provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } - - return provider, handler, server.Close -} - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DREAMHOST_API_KEY": "123", - }, - }, - { - desc: "missing API key", - envVars: map[string]string{ - "DREAMHOST_API_KEY": "", - }, - expected: "dreamhost: some credentials information are missing: DREAMHOST_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - assert.NoError(t, err) - assert.NotNil(t, p) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "dreamhost: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - assert.NoError(t, err) - assert.NotNil(t, p) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method, "method") - - q := r.URL.Query() - assert.Equal(t, q.Get("key"), fakeAPIKey) - assert.Equal(t, q.Get("cmd"), "dns-add_record") - assert.Equal(t, q.Get("format"), "json") - assert.Equal(t, q.Get("record"), "_acme-challenge.example.com") - assert.Equal(t, q.Get("value"), fakeKeyAuth) - assert.Equal(t, q.Get("comment"), "Managed+By+lego") - - _, err := fmt.Fprintf(w, `{"data":"record_added","result":"success"}`) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - err := provider.Present("example.com", "", fakeChallengeToken) - require.NoError(t, err) -} - -func TestDNSProvider_PresentFailed(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method, "method") - - _, err := fmt.Fprintf(w, `{"data":"record_already_exists_remove_first","result":"error"}`) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - err := provider.Present("example.com", "", fakeChallengeToken) - require.EqualError(t, err, "dreamhost: add TXT record failed: record_already_exists_remove_first") -} - -func TestDNSProvider_Cleanup(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method, "method") - - q := r.URL.Query() - assert.Equal(t, q.Get("key"), fakeAPIKey, "key mismatch") - assert.Equal(t, q.Get("cmd"), "dns-remove_record", "cmd mismatch") - assert.Equal(t, q.Get("format"), "json") - assert.Equal(t, q.Get("record"), "_acme-challenge.example.com") - assert.Equal(t, q.Get("value"), fakeKeyAuth, "value mismatch") - assert.Equal(t, q.Get("comment"), "Managed+By+lego") - - _, err := fmt.Fprintf(w, `{"data":"record_removed","result":"success"}`) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - err := provider.CleanUp("example.com", "", fakeChallengeToken) - require.NoError(t, err, "failed to remove TXT record") -} - -func TestLivePresentAndCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/duckdns/client.go b/vendor/github.com/go-acme/lego/providers/dns/duckdns/client.go deleted file mode 100644 index 4c0f35f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/duckdns/client.go +++ /dev/null @@ -1,68 +0,0 @@ -package duckdns - -import ( - "fmt" - "io/ioutil" - "net/url" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/miekg/dns" -) - -// updateTxtRecord Update the domains TXT record -// To update the TXT record we just need to make one simple get request. -// In DuckDNS you only have one TXT record shared with the domain and all sub domains. -func (d *DNSProvider) updateTxtRecord(domain, token, txt string, clear bool) error { - u, _ := url.Parse("https://www.duckdns.org/update") - - mainDomain := getMainDomain(domain) - if len(mainDomain) == 0 { - return fmt.Errorf("unable to find the main domain for: %s", domain) - } - - query := u.Query() - query.Set("domains", mainDomain) - query.Set("token", token) - query.Set("clear", strconv.FormatBool(clear)) - query.Set("txt", txt) - u.RawQuery = query.Encode() - - response, err := d.config.HTTPClient.Get(u.String()) - if err != nil { - return err - } - defer response.Body.Close() - - bodyBytes, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - - body := string(bodyBytes) - if body != "OK" { - return fmt.Errorf("request to change TXT record for DuckDNS returned the following result (%s) this does not match expectation (OK) used url [%s]", body, u) - } - return nil -} - -// DuckDNS only lets you write to your subdomain -// so it must be in format subdomain.duckdns.org -// not in format subsubdomain.subdomain.duckdns.org -// so strip off everything that is not top 3 levels -func getMainDomain(domain string) string { - domain = dns01.UnFqdn(domain) - - split := dns.Split(domain) - if strings.HasSuffix(strings.ToLower(domain), "duckdns.org") { - if len(split) < 3 { - return "" - } - - firstSubDomainIndex := split[len(split)-3] - return domain[firstSubDomainIndex:] - } - - return domain[split[len(split)-1]:] -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.go b/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.go deleted file mode 100644 index 8d2d783..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.go +++ /dev/null @@ -1,89 +0,0 @@ -// Package duckdns implements a DNS provider for solving the DNS-01 challenge using DuckDNS. -// See http://www.duckdns.org/spec.jsp for more info on updating TXT records. -package duckdns - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("DUCKDNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DUCKDNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), - SequenceInterval: env.GetOrDefaultSecond("DUCKDNS_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DUCKDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DUCKDNS_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DUCKDNS_TOKEN") - if err != nil { - return nil, fmt.Errorf("duckdns: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["DUCKDNS_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DuckDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("duckdns: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("duckdns: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, txtRecord := dns01.GetRecord(domain, keyAuth) - return d.updateTxtRecord(domain, d.config.Token, txtRecord, false) -} - -// CleanUp clears DuckDNS TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - return d.updateTxtRecord(domain, d.config.Token, "", true) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.toml b/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.toml deleted file mode 100644 index 6aebf8e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Duck DNS" -Description = '''''' -URL = "https://www.duckdns.org/" -Code = "duckdns" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DUCKDNS_TOKEN = "Account token" - [Configuration.Additional] - DUCKDNS_POLLING_INTERVAL = "Time between DNS propagation check" - DUCKDNS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DUCKDNS_TTL = "The TTL of the TXT record used for the DNS challenge" - DUCKDNS_HTTP_TIMEOUT = "API request timeout" - DUCKDNS_SEQUENCE_INTERVAL = "Interval between iteration" - -[Links] - API = "https://www.duckdns.org/spec.jsp" diff --git a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns_test.go b/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns_test.go deleted file mode 100644 index 69e5045..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package duckdns - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("DUCKDNS_TOKEN"). - WithDomain("DUCKDNS_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DUCKDNS_TOKEN": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "DUCKDNS_TOKEN": "", - }, - expected: "duckdns: some credentials information are missing: DUCKDNS_TOKEN", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - token string - expected string - }{ - { - desc: "success", - token: "123", - }, - { - desc: "missing credentials", - expected: "duckdns: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Token = test.token - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func Test_getMainDomain(t *testing.T) { - testCases := []struct { - desc string - domain string - expected string - }{ - { - desc: "empty", - domain: "", - expected: "", - }, - { - desc: "missing sub domain", - domain: "duckdns.org", - expected: "", - }, - { - desc: "explicit domain: sub domain", - domain: "sub.duckdns.org", - expected: "sub.duckdns.org", - }, - { - desc: "explicit domain: subsub domain", - domain: "my.sub.duckdns.org", - expected: "sub.duckdns.org", - }, - { - desc: "explicit domain: subsubsub domain", - domain: "my.sub.sub.duckdns.org", - expected: "sub.duckdns.org", - }, - { - desc: "only subname: sub domain", - domain: "sub", - expected: "sub", - }, - { - desc: "only subname: subsub domain", - domain: "my.sub", - expected: "sub", - }, - { - desc: "only subname: subsubsub domain", - domain: "my.sub.sub", - expected: "sub", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - wDomain := getMainDomain(test.domain) - assert.Equal(t, test.expected, wDomain) - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dyn/client.go b/vendor/github.com/go-acme/lego/providers/dns/dyn/client.go deleted file mode 100644 index f7e6cee..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dyn/client.go +++ /dev/null @@ -1,146 +0,0 @@ -package dyn - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" -) - -const defaultBaseURL = "https://api.dynect.net/REST" - -type dynResponse struct { - // One of 'success', 'failure', or 'incomplete' - Status string `json:"status"` - - // The structure containing the actual results of the request - Data json.RawMessage `json:"data"` - - // The ID of the job that was created in response to a request. - JobID int `json:"job_id"` - - // A list of zero or more messages - Messages json.RawMessage `json:"msgs"` -} - -type credentials struct { - Customer string `json:"customer_name"` - User string `json:"user_name"` - Pass string `json:"password"` -} - -type session struct { - Token string `json:"token"` - Version string `json:"version"` -} - -type publish struct { - Publish bool `json:"publish"` - Notes string `json:"notes"` -} - -// Starts a new Dyn API Session. Authenticates using customerName, userName, -// password and receives a token to be used in for subsequent requests. -func (d *DNSProvider) login() error { - payload := &credentials{Customer: d.config.CustomerName, User: d.config.UserName, Pass: d.config.Password} - dynRes, err := d.sendRequest(http.MethodPost, "Session", payload) - if err != nil { - return err - } - - var s session - err = json.Unmarshal(dynRes.Data, &s) - if err != nil { - return err - } - - d.token = s.Token - - return nil -} - -// Destroys Dyn Session -func (d *DNSProvider) logout() error { - if len(d.token) == 0 { - // nothing to do - return nil - } - - url := fmt.Sprintf("%s/Session", defaultBaseURL) - req, err := http.NewRequest(http.MethodDelete, url, nil) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Auth-Token", d.token) - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("API request failed to delete session with HTTP status code %d", resp.StatusCode) - } - - d.token = "" - - return nil -} - -func (d *DNSProvider) publish(zone, notes string) error { - pub := &publish{Publish: true, Notes: notes} - resource := fmt.Sprintf("Zone/%s/", zone) - - _, err := d.sendRequest(http.MethodPut, resource, pub) - return err -} - -func (d *DNSProvider) sendRequest(method, resource string, payload interface{}) (*dynResponse, error) { - url := fmt.Sprintf("%s/%s", defaultBaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - if len(d.token) > 0 { - req.Header.Set("Auth-Token", d.token) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 500 { - return nil, fmt.Errorf("API request failed with HTTP status code %d", resp.StatusCode) - } - - var dynRes dynResponse - err = json.NewDecoder(resp.Body).Decode(&dynRes) - if err != nil { - return nil, err - } - - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("API request failed with HTTP status code %d: %s", resp.StatusCode, dynRes.Messages) - } else if resp.StatusCode == 307 { - // TODO add support for HTTP 307 response and long running jobs - return nil, fmt.Errorf("API request returned HTTP 307. This is currently unsupported") - } - - if dynRes.Status == "failure" { - // TODO add better error handling - return nil, fmt.Errorf("API request failed: %s", dynRes.Messages) - } - - return &dynRes, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.go b/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.go deleted file mode 100644 index 37cc7ec..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.go +++ /dev/null @@ -1,157 +0,0 @@ -// Package dyn implements a DNS provider for solving the DNS-01 challenge using Dyn Managed DNS. -package dyn - -import ( - "errors" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - CustomerName string - UserName string - Password string - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DYN_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("DYN_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DYN_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DYN_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// Dyn's Managed DNS API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - token string -} - -// NewDNSProvider returns a DNSProvider instance configured for Dyn DNS. -// Credentials must be passed in the environment variables: -// DYN_CUSTOMER_NAME, DYN_USER_NAME and DYN_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DYN_CUSTOMER_NAME", "DYN_USER_NAME", "DYN_PASSWORD") - if err != nil { - return nil, fmt.Errorf("dyn: %v", err) - } - - config := NewDefaultConfig() - config.CustomerName = values["DYN_CUSTOMER_NAME"] - config.UserName = values["DYN_USER_NAME"] - config.Password = values["DYN_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Dyn DNS -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dyn: the configuration of the DNS provider is nil") - } - - if config.CustomerName == "" || config.UserName == "" || config.Password == "" { - return nil, fmt.Errorf("dyn: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - data := map[string]interface{}{ - "rdata": map[string]string{ - "txtdata": value, - }, - "ttl": strconv.Itoa(d.config.TTL), - } - - resource := fmt.Sprintf("TXTRecord/%s/%s/", authZone, fqdn) - _, err = d.sendRequest(http.MethodPost, resource, data) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - err = d.publish(authZone, "Added TXT record for ACME dns-01 challenge using lego client") - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - return d.logout() -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - resource := fmt.Sprintf("TXTRecord/%s/%s/", authZone, fqdn) - url := fmt.Sprintf("%s/%s", defaultBaseURL, resource) - - req, err := http.NewRequest(http.MethodDelete, url, nil) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Auth-Token", d.token) - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("dyn: API request failed to delete TXT record HTTP status code %d", resp.StatusCode) - } - - err = d.publish(authZone, "Removed TXT record for ACME dns-01 challenge using lego client") - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - return d.logout() -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.toml b/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.toml deleted file mode 100644 index b183589..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Dyn" -Description = '''''' -URL = "https://dyn.com/" -Code = "dyn" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - DYN_CUSTOMER_NAME = "Customer name" - DYN_USER_NAME = "User name" - DYN_PASSWORD = "Paswword" - [Configuration.Additional] - DYN_POLLING_INTERVAL = "Time between DNS propagation check" - DYN_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - DYN_TTL = "The TTL of the TXT record used for the DNS challenge" - DYN_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://help.dyn.com/rest/" diff --git a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn_test.go b/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn_test.go deleted file mode 100644 index 139370a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package dyn - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "DYN_CUSTOMER_NAME", - "DYN_USER_NAME", - "DYN_PASSWORD"). - WithDomain("DYN_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "DYN_CUSTOMER_NAME": "A", - "DYN_USER_NAME": "B", - "DYN_PASSWORD": "C", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "DYN_CUSTOMER_NAME": "", - "DYN_USER_NAME": "", - "DYN_PASSWORD": "", - }, - expected: "dyn: some credentials information are missing: DYN_CUSTOMER_NAME,DYN_USER_NAME,DYN_PASSWORD", - }, - { - desc: "missing customer name", - envVars: map[string]string{ - "DYN_CUSTOMER_NAME": "", - "DYN_USER_NAME": "B", - "DYN_PASSWORD": "C", - }, - expected: "dyn: some credentials information are missing: DYN_CUSTOMER_NAME", - }, - { - desc: "missing password", - envVars: map[string]string{ - "DYN_CUSTOMER_NAME": "A", - "DYN_USER_NAME": "", - "DYN_PASSWORD": "C", - }, - expected: "dyn: some credentials information are missing: DYN_USER_NAME", - }, - { - desc: "missing username", - envVars: map[string]string{ - "DYN_CUSTOMER_NAME": "A", - "DYN_USER_NAME": "B", - "DYN_PASSWORD": "", - }, - expected: "dyn: some credentials information are missing: DYN_PASSWORD", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - customerName string - password string - userName string - expected string - }{ - { - desc: "success", - customerName: "A", - password: "B", - userName: "C", - }, - { - desc: "missing credentials", - expected: "dyn: credentials missing", - }, - { - desc: "missing customer name", - customerName: "", - password: "B", - userName: "C", - expected: "dyn: credentials missing", - }, - { - desc: "missing password", - customerName: "A", - password: "", - userName: "C", - expected: "dyn: credentials missing", - }, - { - desc: "missing username", - customerName: "A", - password: "B", - userName: "", - expected: "dyn: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.CustomerName = test.customerName - config.Password = test.password - config.UserName = test.userName - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/easydns/client.go b/vendor/github.com/go-acme/lego/providers/dns/easydns/client.go deleted file mode 100644 index 3d2c565..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/easydns/client.go +++ /dev/null @@ -1,97 +0,0 @@ -package easydns - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "path" -) - -const defaultEndpoint = "https://rest.easydns.net" - -type zoneRecord struct { - ID string `json:"id,omitempty"` - Domain string `json:"domain"` - Host string `json:"host"` - TTL string `json:"ttl"` - Prio string `json:"prio"` - Type string `json:"type"` - Rdata string `json:"rdata"` - LastMod string `json:"last_mod,omitempty"` - Revoked int `json:"revoked,omitempty"` - NewHost string `json:"new_host,omitempty"` -} - -type addRecordResponse struct { - Msg string `json:"msg"` - Tm int `json:"tm"` - Data zoneRecord `json:"data"` - Status int `json:"status"` -} - -func (d *DNSProvider) addRecord(domain string, record interface{}) (string, error) { - pathAdd := path.Join("/zones/records/add", domain, "TXT") - - response := &addRecordResponse{} - err := d.doRequest(http.MethodPut, pathAdd, record, response) - if err != nil { - return "", err - } - - recordID := response.Data.ID - - return recordID, nil -} - -func (d *DNSProvider) deleteRecord(domain, recordID string) error { - pathDelete := path.Join("/zones/records", domain, recordID) - - return d.doRequest(http.MethodDelete, pathDelete, nil, nil) -} - -func (d *DNSProvider) doRequest(method, path string, requestMsg, responseMsg interface{}) error { - reqBody := &bytes.Buffer{} - if requestMsg != nil { - err := json.NewEncoder(reqBody).Encode(requestMsg) - if err != nil { - return err - } - } - - endpoint, err := d.config.Endpoint.Parse(path + "?format=json") - if err != nil { - return err - } - - request, err := http.NewRequest(method, endpoint.String(), reqBody) - if err != nil { - return err - } - - request.Header.Set("Content-Type", "application/json") - request.Header.Set("Accept", "application/json") - request.SetBasicAuth(d.config.Token, d.config.Key) - - response, err := d.config.HTTPClient.Do(request) - if err != nil { - return err - } - defer response.Body.Close() - - if response.StatusCode >= http.StatusBadRequest { - body, err := ioutil.ReadAll(response.Body) - if err != nil { - return fmt.Errorf("%d: failed to read response body: %v", response.StatusCode, err) - } - - return fmt.Errorf("%d: request failed: %v", response.StatusCode, string(body)) - } - - if responseMsg != nil { - return json.NewDecoder(response.Body).Decode(responseMsg) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.go b/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.go deleted file mode 100644 index 2ef5c28..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.go +++ /dev/null @@ -1,165 +0,0 @@ -// Package easydns implements a DNS provider for solving the DNS-01 challenge using EasyDNS API. -package easydns - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/miekg/dns" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Endpoint *url.URL - Token string - Key string - TTL int - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("EASYDNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - SequenceInterval: env.GetOrDefaultSecond("EASYDNS_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("EASYDNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("EASYDNS_TTL", dns01.DefaultTTL), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("EASYDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider describes a provider for acme-proxy -type DNSProvider struct { - config *Config - recordIDs map[string]string - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance. -func NewDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - - endpoint, err := url.Parse(env.GetOrDefaultString("EASYDNS_ENDPOINT", defaultEndpoint)) - if err != nil { - return nil, fmt.Errorf("easydns: %v", err) - } - config.Endpoint = endpoint - - values, err := env.Get("EASYDNS_TOKEN", "EASYDNS_KEY") - if err != nil { - return nil, fmt.Errorf("easydns: %v", err) - } - - config.Token = values["EASYDNS_TOKEN"] - config.Key = values["EASYDNS_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider . -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("easydns: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("easydns: the API token is missing") - } - - if config.Key == "" { - return nil, errors.New("easydns: the API key is missing") - } - - return &DNSProvider{config: config, recordIDs: map[string]string{}}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - apiHost, apiDomain := splitFqdn(fqdn) - record := &zoneRecord{ - Domain: apiDomain, - Host: apiHost, - Type: "TXT", - Rdata: value, - TTL: strconv.Itoa(d.config.TTL), - Prio: "0", - } - - recordID, err := d.addRecord(apiDomain, record) - if err != nil { - return fmt.Errorf("easydns: error adding zone record: %v", err) - } - - key := getMapKey(fqdn, value) - - d.recordIDsMu.Lock() - d.recordIDs[key] = recordID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, challenge := dns01.GetRecord(domain, keyAuth) - - key := getMapKey(fqdn, challenge) - recordID, exists := d.recordIDs[key] - if !exists { - return nil - } - - _, apiDomain := splitFqdn(fqdn) - err := d.deleteRecord(apiDomain, recordID) - - d.recordIDsMu.Lock() - defer delete(d.recordIDs, key) - d.recordIDsMu.Unlock() - - if err != nil { - return fmt.Errorf("easydns: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} - -func splitFqdn(fqdn string) (host, domain string) { - parts := dns.SplitDomainName(fqdn) - length := len(parts) - - host = strings.Join(parts[0:length-2], ".") - domain = strings.Join(parts[length-2:length], ".") - return -} - -func getMapKey(fqdn, value string) string { - return fqdn + "|" + value -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.toml b/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.toml deleted file mode 100644 index 01e866e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.toml +++ /dev/null @@ -1,30 +0,0 @@ -Name = "EasyDNS" -Description = '''''' -URL = "https://easydns.com/" -Code = "easydns" -Since = "v2.6.0" - -Example = ''' -EASYDNS_TOKEN= \ -EASYDNS_KEY= \ -lego --dns easydns --domains my.domain.com --email my@email.com run -''' - -Additional = ''' -To test with the sandbox environment set ```EASYDNS_ENDPOINT=https://sandbox.rest.easydns.net``` -''' - -[Configuration] - [Configuration.Credentials] - EASYDNS_TOKEN = "API Token" - EASYDNS_KEY = "API Key" - [Configuration.Additional] - EASYDNS_ENDPOINT = "The endpoint URL of the API Server" - EASYDNS_POLLING_INTERVAL = "Time between DNS propagation check" - EASYDNS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - EASYDNS_SEQUENCE_INTERVAL = "Time between sequential requests" - EASYDNS_TTL = "The TTL of the TXT record used for the DNS challenge" - EASYDNS_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "http://docs.sandbox.rest.easydns.net" diff --git a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns_test.go b/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns_test.go deleted file mode 100644 index b4412ee..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns_test.go +++ /dev/null @@ -1,315 +0,0 @@ -package easydns - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "EASYDNS_ENDPOINT", - "EASYDNS_TOKEN", - "EASYDNS_KEY"). - WithDomain("EASYDNS_DOMAIN") - -func setup() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) - - endpoint, err := url.Parse(server.URL) - if err != nil { - panic(err) - } - - config := NewDefaultConfig() - config.Token = "TOKEN" - config.Key = "SECRET" - config.Endpoint = endpoint - - provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } - - return provider, handler, server.Close -} - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "EASYDNS_TOKEN": "TOKEN", - "EASYDNS_KEY": "SECRET", - }, - }, - { - desc: "missing token", - envVars: map[string]string{ - "EASYDNS_KEY": "SECRET", - }, - expected: "easydns: some credentials information are missing: EASYDNS_TOKEN", - }, - { - desc: "missing key", - envVars: map[string]string{ - "EASYDNS_TOKEN": "TOKEN", - }, - expected: "easydns: some credentials information are missing: EASYDNS_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - config *Config - expected string - }{ - { - desc: "success", - config: &Config{ - Token: "TOKEN", - Key: "KEY", - }, - }, - { - desc: "nil config", - config: nil, - expected: "easydns: the configuration of the DNS provider is nil", - }, - { - desc: "missing token", - config: &Config{ - Key: "KEY", - }, - expected: "easydns: the API token is missing", - }, - { - desc: "missing key", - config: &Config{ - Token: "TOKEN", - }, - expected: "easydns: the API key is missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - p, err := NewDNSProviderConfig(test.config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setup() - defer tearDown() - - mux.HandleFunc("/zones/records/add/example.com/TXT", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPut, r.Method, "method") - assert.Equal(t, "format=json", r.URL.RawQuery, "query") - assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") - assert.Equal(t, "Basic VE9LRU46U0VDUkVU", r.Header.Get("Authorization"), "Authorization") - - reqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - - expectedReqBody := `{"domain":"example.com","host":"_acme-challenge","ttl":"120","prio":"0","type":"TXT","rdata":"pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM"} -` - assert.Equal(t, expectedReqBody, string(reqBody)) - - w.WriteHeader(http.StatusCreated) - _, err = fmt.Fprintf(w, `{ - "msg": "OK", - "tm": 1554681934, - "data": { - "host": "_acme-challenge", - "geozone_id": 0, - "ttl": "120", - "prio": "0", - "rdata": "pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM", - "revoked": 0, - "id": "123456789", - "new_host": "_acme-challenge.example.com" - }, - "status": 201 - }`) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - err := provider.Present("example.com", "token", "keyAuth") - require.NoError(t, err) - require.Contains(t, provider.recordIDs, "_acme-challenge.example.com.|pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM") -} - -func TestDNSProvider_Cleanup_WhenRecordIdNotSet_NoOp(t *testing.T) { - provider, _, tearDown := setup() - defer tearDown() - - err := provider.CleanUp("example.com", "token", "keyAuth") - require.NoError(t, err) -} - -func TestDNSProvider_Cleanup_WhenRecordIdSet_DeletesTxtRecord(t *testing.T) { - provider, mux, tearDown := setup() - defer tearDown() - - mux.HandleFunc("/zones/records/example.com/123456", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodDelete, r.Method, "method") - assert.Equal(t, "format=json", r.URL.RawQuery, "query") - assert.Equal(t, "Basic VE9LRU46U0VDUkVU", r.Header.Get("Authorization"), "Authorization") - - w.WriteHeader(http.StatusOK) - _, err := fmt.Fprintf(w, `{ - "msg": "OK", - "data": { - "domain": "example.com", - "id": "123456" - }, - "status": 200 - }`) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - provider.recordIDs["_acme-challenge.example.com.|pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM"] = "123456" - err := provider.CleanUp("example.com", "token", "keyAuth") - require.NoError(t, err) -} - -func TestDNSProvider_Cleanup_WhenHttpError_ReturnsError(t *testing.T) { - provider, mux, tearDown := setup() - defer tearDown() - - errorMessage := `{ - "error": { - "code": 406, - "message": "Provided id is invalid or you do not have permission to access it." - } - }` - mux.HandleFunc("/zones/records/example.com/123456", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodDelete, r.Method, "method") - assert.Equal(t, "format=json", r.URL.RawQuery, "query") - assert.Equal(t, "Basic VE9LRU46U0VDUkVU", r.Header.Get("Authorization"), "Authorization") - - w.WriteHeader(http.StatusNotAcceptable) - _, err := fmt.Fprintf(w, errorMessage) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - provider.recordIDs["_acme-challenge.example.com.|pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM"] = "123456" - err := provider.CleanUp("example.com", "token", "keyAuth") - expectedError := fmt.Sprintf("easydns: 406: request failed: %v", errorMessage) - require.EqualError(t, err, expectedError) -} - -func TestSplitFqdn(t *testing.T) { - testCases := []struct { - desc string - fqdn string - expectedHost string - expectedDomain string - }{ - { - desc: "domain only", - fqdn: "domain.com.", - expectedHost: "", - expectedDomain: "domain.com", - }, - { - desc: "single-part host", - fqdn: "_acme-challenge.domain.com.", - expectedHost: "_acme-challenge", - expectedDomain: "domain.com", - }, - { - desc: "multi-part host", - fqdn: "_acme-challenge.sub.domain.com.", - expectedHost: "_acme-challenge.sub", - expectedDomain: "domain.com", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - actualHost, actualDomain := splitFqdn(test.fqdn) - - require.Equal(t, test.expectedHost, actualHost) - require.Equal(t, test.expectedDomain, actualDomain) - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exec/exec.go b/vendor/github.com/go-acme/lego/providers/dns/exec/exec.go deleted file mode 100644 index 903bcca..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exec/exec.go +++ /dev/null @@ -1,113 +0,0 @@ -// Package exec implements a DNS provider which runs a program for adding/removing the DNS record. -package exec - -import ( - "errors" - "fmt" - "os" - "os/exec" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config Provider configuration. -type Config struct { - Program string - Mode string - PropagationTimeout time.Duration - PollingInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("EXEC_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("EXEC_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider adds and removes the record for the DNS challenge by calling a -// program with command-line parameters. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider which runs the program in the -// environment variable EXEC_PATH for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("EXEC_PATH") - if err != nil { - return nil, fmt.Errorf("exec: %v", err) - } - - config := NewDefaultConfig() - config.Program = values["EXEC_PATH"] - config.Mode = os.Getenv("EXEC_MODE") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig returns a new DNS provider which runs the given configuration -// for adding and removing the DNS record. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("the configuration is nil") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - var args []string - if d.config.Mode == "RAW" { - args = []string{"present", "--", domain, token, keyAuth} - } else { - fqdn, value := dns01.GetRecord(domain, keyAuth) - args = []string{"present", fqdn, value} - } - - cmd := exec.Command(d.config.Program, args...) - - output, err := cmd.CombinedOutput() - if len(output) > 0 { - log.Println(string(output)) - } - - return err -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - var args []string - if d.config.Mode == "RAW" { - args = []string{"cleanup", "--", domain, token, keyAuth} - } else { - fqdn, value := dns01.GetRecord(domain, keyAuth) - args = []string{"cleanup", fqdn, value} - } - - cmd := exec.Command(d.config.Program, args...) - - output, err := cmd.CombinedOutput() - if len(output) > 0 { - log.Println(string(output)) - } - - return err -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.PropagationTimeout -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exec/exec.toml b/vendor/github.com/go-acme/lego/providers/dns/exec/exec.toml deleted file mode 100644 index 615c55d..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exec/exec.toml +++ /dev/null @@ -1,111 +0,0 @@ -Name = "External program" -Description = "Solving the DNS-01 challenge using an external program." -URL = "/dns/exec" -Code = "exec" -Since = "v0.5.0" - -Example = ''' -EXEC_PATH=/the/path/to/myscript.sh \ -lego --dns exec --domains my.domain.com --email my@email.com run -''' - -Additional = ''' - -## Base Configuration - -| Environment Variable Name | Description | -|---------------------------|---------------------------------------| -| `EXEC_MODE` | `RAW`, none | -| `EXEC_PATH` | The path of the the external program. | - - -## Additional Configuration - -| Environment Variable Name | Description | -|----------------------------|-------------------------------------------| -| `EXEC_POLLING_INTERVAL` | Time between DNS propagation check. | -| `EXEC_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation. | - - -## Description - -The file name of the external program is specified in the environment variable `EXEC_PATH`. - -When it is run by lego, three command-line parameters are passed to it: -The action ("present" or "cleanup"), the fully-qualified domain name and the value for the record. - -For example, requesting a certificate for the domain 'foo.example.com' can be achieved by calling lego as follows: - -```bash -EXEC_PATH=./update-dns.sh \ - lego --dns exec \ - --domains foo.example.com \ - --email invalid@example.com run -``` - -It will then call the program './update-dns.sh' with like this: - -```bash -./update-dns.sh "present" "_acme-challenge.foo.example.com." "MsijOYZxqyjGnFGwhjrhfg-Xgbl5r68WPda0J9EgqqI" -``` - -The program then needs to make sure the record is inserted. -When it returns an error via a non-zero exit code, lego aborts. - -When the record is to be removed again, -the program is called with the first command-line parameter set to `cleanup` instead of `present`. - -If you want to use the raw domain, token, and keyAuth values with your program, you can set `EXEC_MODE=RAW`: - -```bash -EXEC_MODE=RAW \ -EXEC_PATH=./update-dns.sh \ - lego --dns exec \ - --domains foo.example.com \ - --email invalid@example.com run -``` - -It will then call the program `./update-dns.sh` like this: - -```bash -./update-dns.sh "present" "foo.example.com." "--" "some-token" "KxAy-J3NwUmg9ZQuM-gP_Mq1nStaYSaP9tYQs5_-YsE.ksT-qywTd8058G-SHHWA3RAN72Pr0yWtPYmmY5UBpQ8" -``` - -## Commands - -{{% notice note %}} -The `--` is because the token MAY start with a `-`, and the called program may try and interpret a `-` as indicating a flag. -In the case of urfave, which is commonly used, -you can use the `--` delimiter to specify the start of positional arguments, and handle such a string safely. -{{% /notice %}} - -### Present - -| Mode | Command | -|---------|----------------------------------------------------| -| default | `myprogram present -- ` | -| `RAW` | `myprogram present -- ` | - -### Cleanup - -| Mode | Command | -|---------|----------------------------------------------------| -| default | `myprogram cleanup -- ` | -| `RAW` | `myprogram cleanup -- ` | - -### Timeout - -The command have to display propagation timeout and polling interval into Stdout. - -The values must be formatted as JSON, and times are in seconds. -Example: `{"timeout": 30, "interval": 5}` - -If an error occurs or if the command is not provided: -the default display propagation timeout and polling interval are used. - -| Mode | Command | -|---------|----------------------------------------------------| -| default | `myprogram timeout` | -| `RAW` | `myprogram timeout` | - -''' diff --git a/vendor/github.com/go-acme/lego/providers/dns/exec/exec_test.go b/vendor/github.com/go-acme/lego/providers/dns/exec/exec_test.go deleted file mode 100644 index 7d0898c..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exec/exec_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package exec - -import ( - "fmt" - "os" - "testing" - - "github.com/go-acme/lego/log" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -func TestDNSProvider_Present(t *testing.T) { - backupLogger := log.Logger - defer func() { - log.Logger = backupLogger - }() - - logRecorder := &LogRecorder{} - log.Logger = logRecorder - - type expected struct { - args string - error bool - } - - testCases := []struct { - desc string - config *Config - expected expected - }{ - { - desc: "Standard mode", - config: &Config{ - Program: "echo", - Mode: "", - }, - expected: expected{ - args: "present _acme-challenge.domain. pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM\n", - }, - }, - { - desc: "program error", - config: &Config{ - Program: "ogellego", - Mode: "", - }, - expected: expected{error: true}, - }, - { - desc: "Raw mode", - config: &Config{ - Program: "echo", - Mode: "RAW", - }, - expected: expected{ - args: "present -- domain token keyAuth\n", - }, - }, - } - - var message string - logRecorder.On("Println", mock.Anything).Run(func(args mock.Arguments) { - message = args.String(0) - fmt.Fprintln(os.Stdout, "XXX", message) - }) - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - message = "" - - provider, err := NewDNSProviderConfig(test.config) - require.NoError(t, err) - - err = provider.Present("domain", "token", "keyAuth") - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.args, message) - } - }) - } -} - -func TestDNSProvider_CleanUp(t *testing.T) { - backupLogger := log.Logger - defer func() { - log.Logger = backupLogger - }() - - logRecorder := &LogRecorder{} - log.Logger = logRecorder - - type expected struct { - args string - error bool - } - - testCases := []struct { - desc string - config *Config - expected expected - }{ - { - desc: "Standard mode", - config: &Config{ - Program: "echo", - Mode: "", - }, - expected: expected{ - args: "cleanup _acme-challenge.domain. pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM\n", - }, - }, - { - desc: "program error", - config: &Config{ - Program: "ogellego", - Mode: "", - }, - expected: expected{error: true}, - }, - { - desc: "Raw mode", - config: &Config{ - Program: "echo", - Mode: "RAW", - }, - expected: expected{ - args: "cleanup -- domain token keyAuth\n", - }, - }, - } - - var message string - logRecorder.On("Println", mock.Anything).Run(func(args mock.Arguments) { - message = args.String(0) - fmt.Fprintln(os.Stdout, "XXX", message) - }) - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - message = "" - - provider, err := NewDNSProviderConfig(test.config) - require.NoError(t, err) - - err = provider.CleanUp("domain", "token", "keyAuth") - if test.expected.error { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.args, message) - } - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exec/log_mock_test.go b/vendor/github.com/go-acme/lego/providers/dns/exec/log_mock_test.go deleted file mode 100644 index 47935cc..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exec/log_mock_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package exec - -import "github.com/stretchr/testify/mock" - -type LogRecorder struct { - mock.Mock -} - -func (*LogRecorder) Fatal(args ...interface{}) { - panic("implement me") -} - -func (*LogRecorder) Fatalln(args ...interface{}) { - panic("implement me") -} - -func (*LogRecorder) Fatalf(format string, args ...interface{}) { - panic("implement me") -} - -func (*LogRecorder) Print(args ...interface{}) { - panic("implement me") -} - -func (l *LogRecorder) Println(args ...interface{}) { - l.Called(args...) -} - -func (*LogRecorder) Printf(format string, args ...interface{}) { - panic("implement me") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.go b/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.go deleted file mode 100644 index 02ec214..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.go +++ /dev/null @@ -1,184 +0,0 @@ -// Package exoscale implements a DNS provider for solving the DNS-01 challenge using exoscale DNS. -package exoscale - -import ( - "context" - "errors" - "fmt" - "net/http" - "time" - - "github.com/exoscale/egoscale" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultBaseURL = "https://api.exoscale.com/dns" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - APISecret string - Endpoint string - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("EXOSCALE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("EXOSCALE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("EXOSCALE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("EXOSCALE_HTTP_TIMEOUT", 0), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *egoscale.Client -} - -// NewDNSProvider Credentials must be passed in the environment variables: -// EXOSCALE_API_KEY, EXOSCALE_API_SECRET, EXOSCALE_ENDPOINT. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("EXOSCALE_API_KEY", "EXOSCALE_API_SECRET") - if err != nil { - return nil, fmt.Errorf("exoscale: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["EXOSCALE_API_KEY"] - config.APISecret = values["EXOSCALE_API_SECRET"] - config.Endpoint = env.GetOrFile("EXOSCALE_ENDPOINT") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Exoscale. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("the configuration of the DNS provider is nil") - } - - if config.APIKey == "" || config.APISecret == "" { - return nil, fmt.Errorf("exoscale: credentials missing") - } - - if config.Endpoint == "" { - config.Endpoint = defaultBaseURL - } - - client := egoscale.NewClient(config.Endpoint, config.APIKey, config.APISecret) - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, recordName, err := d.FindZoneAndRecordName(fqdn, domain) - if err != nil { - return err - } - - recordID, err := d.FindExistingRecordID(zone, recordName) - if err != nil { - return err - } - - if recordID == 0 { - record := egoscale.DNSRecord{ - Name: recordName, - TTL: d.config.TTL, - Content: value, - RecordType: "TXT", - } - - _, err := d.client.CreateRecord(ctx, zone, record) - if err != nil { - return errors.New("Error while creating DNS record: " + err.Error()) - } - } else { - record := egoscale.UpdateDNSRecord{ - ID: recordID, - Name: recordName, - TTL: d.config.TTL, - Content: value, - RecordType: "TXT", - } - - _, err := d.client.UpdateRecord(ctx, zone, record) - if err != nil { - return errors.New("Error while updating DNS record: " + err.Error()) - } - } - - return nil -} - -// CleanUp removes the record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, _ := dns01.GetRecord(domain, keyAuth) - zone, recordName, err := d.FindZoneAndRecordName(fqdn, domain) - if err != nil { - return err - } - - recordID, err := d.FindExistingRecordID(zone, recordName) - if err != nil { - return err - } - - if recordID != 0 { - err = d.client.DeleteRecord(ctx, zone, recordID) - if err != nil { - return errors.New("Error while deleting DNS record: " + err.Error()) - } - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// FindExistingRecordID Query Exoscale to find an existing record for this name. -// Returns nil if no record could be found -func (d *DNSProvider) FindExistingRecordID(zone, recordName string) (int64, error) { - ctx := context.Background() - records, err := d.client.GetRecords(ctx, zone) - if err != nil { - return -1, errors.New("Error while retrievening DNS records: " + err.Error()) - } - for _, record := range records { - if record.Name == recordName { - return record.ID, nil - } - } - return 0, nil -} - -// FindZoneAndRecordName Extract DNS zone and DNS entry name -func (d *DNSProvider) FindZoneAndRecordName(fqdn, domain string) (string, string, error) { - zone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - zone = dns01.UnFqdn(zone) - name := dns01.UnFqdn(fqdn) - name = name[:len(name)-len("."+zone)] - - return zone, name, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.toml b/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.toml deleted file mode 100644 index 0389446..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.toml +++ /dev/null @@ -1,22 +0,0 @@ -Name = "Exoscale" -Description = '''''' -URL = "https://www.exoscale.com/" -Code = "exoscale" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - EXOSCALE_API_KEY = "API key" - EXOSCALE_API_SECRET = "API secret" - EXOSCALE_ENDPOINT = "API endpoint URL" - [Configuration.Additional] - EXOSCALE_POLLING_INTERVAL = "Time between DNS propagation check" - EXOSCALE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - EXOSCALE_TTL = "The TTL of the TXT record used for the DNS challenge" - EXOSCALE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://community.exoscale.com/documentation/dns/api/" - GoClient = "https://github.com/exoscale/egoscale" diff --git a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale_test.go b/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale_test.go deleted file mode 100644 index e51bad2..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package exoscale - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "EXOSCALE_API_SECRET", - "EXOSCALE_API_KEY"). - WithDomain("EXOSCALE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "EXOSCALE_API_KEY": "123", - "EXOSCALE_API_SECRET": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "EXOSCALE_API_KEY": "", - "EXOSCALE_API_SECRET": "", - }, - expected: "exoscale: some credentials information are missing: EXOSCALE_API_KEY,EXOSCALE_API_SECRET", - }, - { - desc: "missing access key", - envVars: map[string]string{ - "EXOSCALE_API_KEY": "", - "EXOSCALE_API_SECRET": "456", - }, - expected: "exoscale: some credentials information are missing: EXOSCALE_API_KEY", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "EXOSCALE_API_KEY": "123", - "EXOSCALE_API_SECRET": "", - }, - expected: "exoscale: some credentials information are missing: EXOSCALE_API_SECRET", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - apiSecret string - expected string - }{ - { - desc: "success", - apiKey: "123", - apiSecret: "456", - }, - { - desc: "missing credentials", - expected: "exoscale: credentials missing", - }, - { - desc: "missing api key", - apiSecret: "456", - expected: "exoscale: credentials missing", - }, - { - desc: "missing secret key", - apiKey: "123", - expected: "exoscale: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.APISecret = test.apiSecret - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_FindZoneAndRecordName(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = "example@example.com" - config.APISecret = "123" - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - type expected struct { - zone string - recordName string - } - - testCases := []struct { - desc string - fqdn string - domain string - expected expected - }{ - { - desc: "Extract root record name", - fqdn: "_acme-challenge.bar.com.", - domain: "bar.com", - expected: expected{ - zone: "bar.com", - recordName: "_acme-challenge", - }, - }, - { - desc: "Extract sub record name", - fqdn: "_acme-challenge.foo.bar.com.", - domain: "foo.bar.com", - expected: expected{ - zone: "bar.com", - recordName: "_acme-challenge.foo", - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - zone, recordName, err := provider.FindZoneAndRecordName(test.fqdn, test.domain) - require.NoError(t, err) - assert.Equal(t, test.expected.zone, zone) - assert.Equal(t, test.expected.recordName, recordName) - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - // Present Twice to handle create / update - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.go b/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.go deleted file mode 100644 index 214e4a9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.go +++ /dev/null @@ -1,158 +0,0 @@ -// Package fastdns implements a DNS provider for solving the DNS-01 challenge using FastDNS. -package fastdns - -import ( - "errors" - "fmt" - "reflect" - "time" - - configdns "github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - edgegrid.Config - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("AKAMAI_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("AKAMAI_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("AKAMAI_TTL", dns01.DefaultTTL), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider uses the supplied environment variables to return a DNSProvider instance: -// AKAMAI_HOST, AKAMAI_CLIENT_TOKEN, AKAMAI_CLIENT_SECRET, AKAMAI_ACCESS_TOKEN -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("AKAMAI_HOST", "AKAMAI_CLIENT_TOKEN", "AKAMAI_CLIENT_SECRET", "AKAMAI_ACCESS_TOKEN") - if err != nil { - return nil, fmt.Errorf("fastdns: %v", err) - } - - config := NewDefaultConfig() - config.Config = edgegrid.Config{ - Host: values["AKAMAI_HOST"], - ClientToken: values["AKAMAI_CLIENT_TOKEN"], - ClientSecret: values["AKAMAI_CLIENT_SECRET"], - AccessToken: values["AKAMAI_ACCESS_TOKEN"], - MaxBody: 131072, - } - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for FastDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("fastdns: the configuration of the DNS provider is nil") - } - - if config.ClientToken == "" || config.ClientSecret == "" || config.AccessToken == "" || config.Host == "" { - return nil, fmt.Errorf("fastdns: credentials are missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fullfil the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zoneName, recordName, err := d.findZoneAndRecordName(fqdn, domain) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - configdns.Init(d.config.Config) - - zone, err := configdns.GetZone(zoneName) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - record := configdns.NewTxtRecord() - _ = record.SetField("name", recordName) - _ = record.SetField("ttl", d.config.TTL) - _ = record.SetField("target", value) - _ = record.SetField("active", true) - - for _, r := range zone.Zone.Txt { - if r != nil && reflect.DeepEqual(r.ToMap(), record.ToMap()) { - return nil - } - } - - return d.createRecord(zone, record) -} - -// CleanUp removes the record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - zoneName, recordName, err := d.findZoneAndRecordName(fqdn, domain) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - configdns.Init(d.config.Config) - - zone, err := configdns.GetZone(zoneName) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - var removed bool - for _, r := range zone.Zone.Txt { - if r != nil && r.Name == recordName { - if zone.RemoveRecord(r) != nil { - return fmt.Errorf("fastdns: %v", err) - } - removed = true - } - } - - if removed { - return zone.Save() - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) findZoneAndRecordName(fqdn, domain string) (string, string, error) { - zone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - zone = dns01.UnFqdn(zone) - name := dns01.UnFqdn(fqdn) - name = name[:len(name)-len("."+zone)] - - return zone, name, nil -} - -func (d *DNSProvider) createRecord(zone *configdns.Zone, record *configdns.TxtRecord) error { - err := zone.AddRecord(record) - if err != nil { - return err - } - - return zone.Save() -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.toml b/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.toml deleted file mode 100644 index 5dbae3b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.toml +++ /dev/null @@ -1,24 +0,0 @@ -Name = "FastDNS" -Description = '''''' -URL = "https://www.akamai.com/us/en/products/security/fast-dns.jsp" -Code = "fastdns" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - AKAMAI_HOST = "API host" - AKAMAI_CLIENT_TOKEN = "Client token" - AKAMAI_CLIENT_SECRET = "Client secret" - AKAMAI_ACCESS_TOKEN = "Access token" - [Configuration.Additional] - AKAMAI_POLLING_INTERVAL = "Time between DNS propagation check" - AKAMAI_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - AKAMAI_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://developer.akamai.com/api/web_performance/fast_dns_record_management/v1.html" - GoClient = "https://github.com/akamai/AkamaiOPEN-edgegrid-golang" - - diff --git a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns_test.go b/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns_test.go deleted file mode 100644 index fe0cfb1..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package fastdns - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "AKAMAI_HOST", - "AKAMAI_CLIENT_TOKEN", - "AKAMAI_CLIENT_SECRET", - "AKAMAI_ACCESS_TOKEN"). - WithDomain("AKAMAI_TEST_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "AKAMAI_HOST": "A", - "AKAMAI_CLIENT_TOKEN": "B", - "AKAMAI_CLIENT_SECRET": "C", - "AKAMAI_ACCESS_TOKEN": "D", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "AKAMAI_HOST": "", - "AKAMAI_CLIENT_TOKEN": "", - "AKAMAI_CLIENT_SECRET": "", - "AKAMAI_ACCESS_TOKEN": "", - }, - expected: "fastdns: some credentials information are missing: AKAMAI_HOST,AKAMAI_CLIENT_TOKEN,AKAMAI_CLIENT_SECRET,AKAMAI_ACCESS_TOKEN", - }, - { - desc: "missing host", - envVars: map[string]string{ - "AKAMAI_HOST": "", - "AKAMAI_CLIENT_TOKEN": "B", - "AKAMAI_CLIENT_SECRET": "C", - "AKAMAI_ACCESS_TOKEN": "D", - }, - expected: "fastdns: some credentials information are missing: AKAMAI_HOST", - }, - { - desc: "missing client token", - envVars: map[string]string{ - "AKAMAI_HOST": "A", - "AKAMAI_CLIENT_TOKEN": "", - "AKAMAI_CLIENT_SECRET": "C", - "AKAMAI_ACCESS_TOKEN": "D", - }, - expected: "fastdns: some credentials information are missing: AKAMAI_CLIENT_TOKEN", - }, - { - desc: "missing client secret", - envVars: map[string]string{ - "AKAMAI_HOST": "A", - "AKAMAI_CLIENT_TOKEN": "B", - "AKAMAI_CLIENT_SECRET": "", - "AKAMAI_ACCESS_TOKEN": "D", - }, - expected: "fastdns: some credentials information are missing: AKAMAI_CLIENT_SECRET", - }, - { - desc: "missing access token", - envVars: map[string]string{ - "AKAMAI_HOST": "A", - "AKAMAI_CLIENT_TOKEN": "B", - "AKAMAI_CLIENT_SECRET": "C", - "AKAMAI_ACCESS_TOKEN": "", - }, - expected: "fastdns: some credentials information are missing: AKAMAI_ACCESS_TOKEN", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - host string - clientToken string - clientSecret string - accessToken string - expected string - }{ - { - desc: "success", - host: "A", - clientToken: "B", - clientSecret: "C", - accessToken: "D", - }, - { - desc: "missing credentials", - expected: "fastdns: credentials are missing", - }, - { - desc: "missing host", - host: "", - clientToken: "B", - clientSecret: "C", - accessToken: "D", - expected: "fastdns: credentials are missing", - }, - { - desc: "missing client token", - host: "A", - clientToken: "", - clientSecret: "C", - accessToken: "D", - expected: "fastdns: credentials are missing", - }, - { - desc: "missing client secret", - host: "A", - clientToken: "B", - clientSecret: "", - accessToken: "B", - expected: "fastdns: credentials are missing", - }, - { - desc: "missing access token", - host: "A", - clientToken: "B", - clientSecret: "C", - accessToken: "", - expected: "fastdns: credentials are missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.ClientToken = test.clientToken - config.ClientSecret = test.clientSecret - config.Host = test.host - config.AccessToken = test.accessToken - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_findZoneAndRecordName(t *testing.T) { - config := NewDefaultConfig() - config.Host = "somehost" - config.ClientToken = "someclienttoken" - config.ClientSecret = "someclientsecret" - config.AccessToken = "someaccesstoken" - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - type expected struct { - zone string - recordName string - } - - testCases := []struct { - desc string - fqdn string - domain string - expected expected - }{ - { - desc: "Extract root record name", - fqdn: "_acme-challenge.bar.com.", - domain: "bar.com", - expected: expected{ - zone: "bar.com", - recordName: "_acme-challenge", - }, - }, - { - desc: "Extract sub record name", - fqdn: "_acme-challenge.foo.bar.com.", - domain: "foo.bar.com", - expected: expected{ - zone: "bar.com", - recordName: "_acme-challenge.foo", - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - zone, recordName, err := provider.findZoneAndRecordName(test.fqdn, test.domain) - require.NoError(t, err) - assert.Equal(t, test.expected.zone, zone) - assert.Equal(t, test.expected.recordName, recordName) - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - // Present Twice to handle create / update - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/client.go b/vendor/github.com/go-acme/lego/providers/dns/gandi/client.go deleted file mode 100644 index 901a789..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/client.go +++ /dev/null @@ -1,316 +0,0 @@ -package gandi - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "io/ioutil" -) - -// types for XML-RPC method calls and parameters - -type param interface { - param() -} - -type paramString struct { - XMLName xml.Name `xml:"param"` - Value string `xml:"value>string"` -} - -type paramInt struct { - XMLName xml.Name `xml:"param"` - Value int `xml:"value>int"` -} - -type structMember interface { - structMember() -} -type structMemberString struct { - Name string `xml:"name"` - Value string `xml:"value>string"` -} -type structMemberInt struct { - Name string `xml:"name"` - Value int `xml:"value>int"` -} -type paramStruct struct { - XMLName xml.Name `xml:"param"` - StructMembers []structMember `xml:"value>struct>member"` -} - -func (p paramString) param() {} -func (p paramInt) param() {} -func (m structMemberString) structMember() {} -func (m structMemberInt) structMember() {} -func (p paramStruct) param() {} - -type methodCall struct { - XMLName xml.Name `xml:"methodCall"` - MethodName string `xml:"methodName"` - Params []param `xml:"params"` -} - -// types for XML-RPC responses - -type response interface { - faultCode() int - faultString() string -} - -type responseFault struct { - FaultCode int `xml:"fault>value>struct>member>value>int"` - FaultString string `xml:"fault>value>struct>member>value>string"` -} - -func (r responseFault) faultCode() int { return r.FaultCode } -func (r responseFault) faultString() string { return r.FaultString } - -type responseStruct struct { - responseFault - StructMembers []struct { - Name string `xml:"name"` - ValueInt int `xml:"value>int"` - } `xml:"params>param>value>struct>member"` -} - -type responseInt struct { - responseFault - Value int `xml:"params>param>value>int"` -} - -type responseBool struct { - responseFault - Value bool `xml:"params>param>value>boolean"` -} - -type rpcError struct { - faultCode int - faultString string -} - -func (e rpcError) Error() string { - return fmt.Sprintf("Gandi DNS: RPC Error: (%d) %s", e.faultCode, e.faultString) -} - -// rpcCall makes an XML-RPC call to Gandi's RPC endpoint by -// marshaling the data given in the call argument to XML and sending -// that via HTTP Post to Gandi. -// The response is then unmarshalled into the resp argument. -func (d *DNSProvider) rpcCall(call *methodCall, resp response) error { - // marshal - b, err := xml.MarshalIndent(call, "", " ") - if err != nil { - return fmt.Errorf("marshal error: %v", err) - } - - // post - b = append([]byte(``+"\n"), b...) - respBody, err := d.httpPost(d.config.BaseURL, "text/xml", bytes.NewReader(b)) - if err != nil { - return err - } - - // unmarshal - err = xml.Unmarshal(respBody, resp) - if err != nil { - return fmt.Errorf("unmarshal error: %v", err) - } - if resp.faultCode() != 0 { - return rpcError{ - faultCode: resp.faultCode(), faultString: resp.faultString()} - } - return nil -} - -// functions to perform API actions - -func (d *DNSProvider) getZoneID(domain string) (int, error) { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.info", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramString{Value: domain}, - }, - }, resp) - if err != nil { - return 0, err - } - - var zoneID int - for _, member := range resp.StructMembers { - if member.Name == "zone_id" { - zoneID = member.ValueInt - } - } - - if zoneID == 0 { - return 0, fmt.Errorf("could not determine zone_id for %s", domain) - } - return zoneID, nil -} - -func (d *DNSProvider) cloneZone(zoneID int, name string) (int, error) { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.clone", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - paramInt{Value: 0}, - paramStruct{ - StructMembers: []structMember{ - structMemberString{ - Name: "name", - Value: name, - }}, - }, - }, - }, resp) - if err != nil { - return 0, err - } - - var newZoneID int - for _, member := range resp.StructMembers { - if member.Name == "id" { - newZoneID = member.ValueInt - } - } - - if newZoneID == 0 { - return 0, fmt.Errorf("could not determine cloned zone_id") - } - return newZoneID, nil -} - -func (d *DNSProvider) newZoneVersion(zoneID int) (int, error) { - resp := &responseInt{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.version.new", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - }, - }, resp) - if err != nil { - return 0, err - } - - if resp.Value == 0 { - return 0, fmt.Errorf("could not create new zone version") - } - return resp.Value, nil -} - -func (d *DNSProvider) addTXTRecord(zoneID int, version int, name string, value string, ttl int) error { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.record.add", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - paramInt{Value: version}, - paramStruct{ - StructMembers: []structMember{ - structMemberString{ - Name: "type", - Value: "TXT", - }, structMemberString{ - Name: "name", - Value: name, - }, structMemberString{ - Name: "value", - Value: value, - }, structMemberInt{ - Name: "ttl", - Value: ttl, - }}, - }, - }, - }, resp) - return err -} - -func (d *DNSProvider) setZoneVersion(zoneID int, version int) error { - resp := &responseBool{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.version.set", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - paramInt{Value: version}, - }, - }, resp) - if err != nil { - return err - } - - if !resp.Value { - return fmt.Errorf("could not set zone version") - } - return nil -} - -func (d *DNSProvider) setZone(domain string, zoneID int) error { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.set", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramString{Value: domain}, - paramInt{Value: zoneID}, - }, - }, resp) - if err != nil { - return err - } - - var respZoneID int - for _, member := range resp.StructMembers { - if member.Name == "zone_id" { - respZoneID = member.ValueInt - } - } - - if respZoneID != zoneID { - return fmt.Errorf("could not set new zone_id for %s", domain) - } - return nil -} - -func (d *DNSProvider) deleteZone(zoneID int) error { - resp := &responseBool{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.delete", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - }, - }, resp) - if err != nil { - return err - } - - if !resp.Value { - return fmt.Errorf("could not delete zone_id") - } - return nil -} - -func (d *DNSProvider) httpPost(url string, bodyType string, body io.Reader) ([]byte, error) { - resp, err := d.config.HTTPClient.Post(url, bodyType, body) - if err != nil { - return nil, fmt.Errorf("HTTP Post Error: %v", err) - } - defer resp.Body.Close() - - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("HTTP Post Error: %v", err) - } - - return b, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.go b/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.go deleted file mode 100644 index ffde8f4..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.go +++ /dev/null @@ -1,214 +0,0 @@ -// Package gandi implements a DNS provider for solving the DNS-01 challenge using Gandi DNS. -package gandi - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Gandi API reference: http://doc.rpc.gandi.net/index.html -// Gandi API domain examples: http://doc.rpc.gandi.net/domain/faq.html - -const ( - // defaultBaseURL Gandi XML-RPC endpoint used by Present and CleanUp - defaultBaseURL = "https://rpc.gandi.net/xmlrpc/" - minTTL = 300 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GANDI_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GANDI_PROPAGATION_TIMEOUT", 40*time.Minute), - PollingInterval: env.GetOrDefaultSecond("GANDI_POLLING_INTERVAL", 60*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GANDI_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// inProgressInfo contains information about an in-progress challenge -type inProgressInfo struct { - zoneID int // zoneID of gandi zone to restore in CleanUp - newZoneID int // zoneID of temporary gandi zone containing TXT record - authZone string // the domain name registered at gandi with trailing "." -} - -// DNSProvider is an implementation of the -// acme.ChallengeProviderTimeout interface that uses Gandi's XML-RPC -// API to manage TXT records for a domain. -type DNSProvider struct { - inProgressFQDNs map[string]inProgressInfo - inProgressAuthZones map[string]struct{} - inProgressMu sync.Mutex - config *Config - // findZoneByFqdn determines the DNS zone of an fqdn. It is overridden during tests. - findZoneByFqdn func(fqdn string) (string, error) -} - -// NewDNSProvider returns a DNSProvider instance configured for Gandi. -// Credentials must be passed in the environment variable: GANDI_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GANDI_API_KEY") - if err != nil { - return nil, fmt.Errorf("gandi: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["GANDI_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Gandi. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("gandi: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("gandi: no API Key given") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - return &DNSProvider{ - config: config, - inProgressFQDNs: make(map[string]inProgressInfo), - inProgressAuthZones: make(map[string]struct{}), - findZoneByFqdn: dns01.FindZoneByFqdn, - }, nil -} - -// Present creates a TXT record using the specified parameters. It -// does this by creating and activating a new temporary Gandi DNS -// zone. This new zone contains the TXT record. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - if d.config.TTL < minTTL { - d.config.TTL = minTTL // 300 is gandi minimum value for ttl - } - - // find authZone and Gandi zone_id for fqdn - authZone, err := d.findZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("gandi: findZoneByFqdn failure: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - // determine name of TXT record - if !strings.HasSuffix( - strings.ToLower(fqdn), strings.ToLower("."+authZone)) { - return fmt.Errorf("gandi: unexpected authZone %s for fqdn %s", authZone, fqdn) - } - name := fqdn[:len(fqdn)-len("."+authZone)] - - // acquire lock and check there is not a challenge already in - // progress for this value of authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - if _, ok := d.inProgressAuthZones[authZone]; ok { - return fmt.Errorf("gandi: challenge already in progress for authZone %s", authZone) - } - - // perform API actions to create and activate new gandi zone - // containing the required TXT record - newZoneName := fmt.Sprintf("%s [ACME Challenge %s]", dns01.UnFqdn(authZone), time.Now().Format(time.RFC822Z)) - - newZoneID, err := d.cloneZone(zoneID, newZoneName) - if err != nil { - return err - } - - newZoneVersion, err := d.newZoneVersion(newZoneID) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - err = d.addTXTRecord(newZoneID, newZoneVersion, name, value, d.config.TTL) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - err = d.setZoneVersion(newZoneID, newZoneVersion) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - err = d.setZone(authZone, newZoneID) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - // save data necessary for CleanUp - d.inProgressFQDNs[fqdn] = inProgressInfo{ - zoneID: zoneID, - newZoneID: newZoneID, - authZone: authZone, - } - d.inProgressAuthZones[authZone] = struct{}{} - - return nil -} - -// CleanUp removes the TXT record matching the specified -// parameters. It does this by restoring the old Gandi DNS zone and -// removing the temporary one created by Present. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // acquire lock and retrieve zoneID, newZoneID and authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - if _, ok := d.inProgressFQDNs[fqdn]; !ok { - // if there is no cleanup information then just return - return nil - } - - zoneID := d.inProgressFQDNs[fqdn].zoneID - newZoneID := d.inProgressFQDNs[fqdn].newZoneID - authZone := d.inProgressFQDNs[fqdn].authZone - delete(d.inProgressFQDNs, fqdn) - delete(d.inProgressAuthZones, authZone) - - // perform API actions to restore old gandi zone for authZone - err := d.setZone(authZone, zoneID) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - return d.deleteZone(newZoneID) -} - -// Timeout returns the values (40*time.Minute, 60*time.Second) which -// are used by the acme package as timeout and check interval values -// when checking for DNS record propagation with Gandi. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.toml b/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.toml deleted file mode 100644 index ec866b8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Gandi" -Description = """""" -URL = "https://www.gandi.net" -Code = "gandi" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - GANDI_API_KEY = "API key" - [Configuration.Additional] - GANDI_POLLING_INTERVAL = "Time between DNS propagation check" - GANDI_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - GANDI_TTL = "The TTL of the TXT record used for the DNS challenge" - GANDI_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "http://doc.rpc.gandi.net/index.html" diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi_mock_test.go b/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi_mock_test.go deleted file mode 100644 index 66c63fa..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi_mock_test.go +++ /dev/null @@ -1,817 +0,0 @@ -package gandi - -// CleanUp Request->Response 1 (setZone) -const cleanup1RequestMock = ` - - domain.zone.set - - - 123412341234123412341234 - - - - - example.com. - - - - - 1234567 - - -` - -// CleanUp Request->Response 1 (setZone) -const cleanup1ResponseMock = ` - - - - - -date_updated -20160216T16:24:38 - - -date_delete -20170331T16:04:06 - - -is_premium -0 - - -date_hold_begin -20170215T02:04:06 - - -date_registry_end -20170215T02:04:06 - - -authinfo_expiration_date -20161211T21:31:20 - - -contacts - - -owner - - -handle -LEGO-GANDI - - -id -111111 - - - - -admin - - -handle -LEGO-GANDI - - -id -111111 - - - - -bill - - -handle -LEGO-GANDI - - -id -111111 - - - - -tech - - -handle -LEGO-GANDI - - -id -111111 - - - - -reseller - - - - -nameservers - -a.dns.gandi.net -b.dns.gandi.net -c.dns.gandi.net - - - -date_restore_end -20170501T02:04:06 - - -id -2222222 - - -authinfo -ABCDABCDAB - - -status - -clientTransferProhibited -serverTransferProhibited - - - -tags - - - - -date_hold_end -20170401T02:04:06 - - -services - -gandidns -gandimail - - - -date_pending_delete_end -20170506T02:04:06 - - -zone_id -1234567 - - -date_renew_begin -20120101T00:00:00 - - -fqdn -example.com - - -autorenew - - -date_registry_creation -20150215T02:04:06 - - -tld -org - - -date_created -20150215T03:04:06 - - - - - -` - -// CleanUp Request->Response 2 (deleteZone) -const cleanup2RequestMock = ` - - domain.zone.delete - - - 123412341234123412341234 - - - - - 7654321 - - -` - -// CleanUp Request->Response 2 (deleteZone) -const cleanup2ResponseMock = ` - - - -1 - - - -` - -// Present Request->Response 1 (getZoneID) -const present1RequestMock = ` - - domain.info - - - 123412341234123412341234 - - - - - example.com. - - -` - -// Present Request->Response 1 (getZoneID) -const present1ResponseMock = ` - - - - - -date_updated -20160216T16:14:23 - - -date_delete -20170331T16:04:06 - - -is_premium -0 - - -date_hold_begin -20170215T02:04:06 - - -date_registry_end -20170215T02:04:06 - - -authinfo_expiration_date -20161211T21:31:20 - - -contacts - - -owner - - -handle -LEGO-GANDI - - -id -111111 - - - - -admin - - -handle -LEGO-GANDI - - -id -111111 - - - - -bill - - -handle -LEGO-GANDI - - -id -111111 - - - - -tech - - -handle -LEGO-GANDI - - -id -111111 - - - - -reseller - - - - -nameservers - -a.dns.gandi.net -b.dns.gandi.net -c.dns.gandi.net - - - -date_restore_end -20170501T02:04:06 - - -id -2222222 - - -authinfo -ABCDABCDAB - - -status - -clientTransferProhibited -serverTransferProhibited - - - -tags - - - - -date_hold_end -20170401T02:04:06 - - -services - -gandidns -gandimail - - - -date_pending_delete_end -20170506T02:04:06 - - -zone_id -1234567 - - -date_renew_begin -20120101T00:00:00 - - -fqdn -example.com - - -autorenew - - -date_registry_creation -20150215T02:04:06 - - -tld -org - - -date_created -20150215T03:04:06 - - - - - -` - -// Present Request->Response 2 (cloneZone) -const present2RequestMock = ` - - domain.zone.clone - - - 123412341234123412341234 - - - - - 1234567 - - - - - 0 - - - - - - - name - - example.com [ACME Challenge 01 Jan 16 00:00 +0000] - - - - - -` - -// Present Request->Response 2 (cloneZone) -const present2ResponseMock = ` - - - - - -name -example.com [ACME Challenge 01 Jan 16 00:00 +0000] - - -versions - -1 - - - -date_updated -20160216T16:24:29 - - -id -7654321 - - -owner -LEGO-GANDI - - -version -1 - - -domains -0 - - -public -0 - - - - - -` - -// Present Request->Response 3 (newZoneVersion) -const present3RequestMock = ` - - domain.zone.version.new - - - 123412341234123412341234 - - - - - 7654321 - - -` - -// Present Request->Response 3 (newZoneVersion) -const present3ResponseMock = ` - - - -2 - - - -` - -// Present Request->Response 4 (addTXTRecord) -const present4RequestMock = ` - - domain.zone.record.add - - - 123412341234123412341234 - - - - - 7654321 - - - - - 2 - - - - - - - type - - TXT - - - - name - - _acme-challenge.abc.def - - - - value - - ezRpBPY8wH8djMLYjX2uCKPwiKDkFZ1SFMJ6ZXGlHrQ - - - - ttl - - 300 - - - - - -` - -// Present Request->Response 4 (addTXTRecord) -const present4ResponseMock = ` - - - - - -name -_acme-challenge.abc.def - - -type -TXT - - -id -333333333 - - -value -"ezRpBPY8wH8djMLYjX2uCKPwiKDkFZ1SFMJ6ZXGlHrQ" - - -ttl -300 - - - - - -` - -// Present Request->Response 5 (setZoneVersion) -const present5RequestMock = ` - - domain.zone.version.set - - - 123412341234123412341234 - - - - - 7654321 - - - - - 2 - - -` - -// Present Request->Response 5 (setZoneVersion) -const present5ResponseMock = ` - - - -1 - - - -` - -// Present Request->Response 6 (setZone) -const present6RequestMock = ` - - domain.zone.set - - - 123412341234123412341234 - - - - - example.com. - - - - - 7654321 - - -` - -// Present Request->Response 6 (setZone) -const present6ResponseMock = ` - - - - - -date_updated -20160216T16:14:23 - - -date_delete -20170331T16:04:06 - - -is_premium -0 - - -date_hold_begin -20170215T02:04:06 - - -date_registry_end -20170215T02:04:06 - - -authinfo_expiration_date -20161211T21:31:20 - - -contacts - - -owner - - -handle -LEGO-GANDI - - -id -111111 - - - - -admin - - -handle -LEGO-GANDI - - -id -111111 - - - - -bill - - -handle -LEGO-GANDI - - -id -111111 - - - - -tech - - -handle -LEGO-GANDI - - -id -111111 - - - - -reseller - - - - -nameservers - -a.dns.gandi.net -b.dns.gandi.net -c.dns.gandi.net - - - -date_restore_end -20170501T02:04:06 - - -id -2222222 - - -authinfo -ABCDABCDAB - - -status - -clientTransferProhibited -serverTransferProhibited - - - -tags - - - - -date_hold_end -20170401T02:04:06 - - -services - -gandidns -gandimail - - - -date_pending_delete_end -20170506T02:04:06 - - -zone_id -7654321 - - -date_renew_begin -20120101T00:00:00 - - -fqdn -example.com - - -autorenew - - -date_registry_creation -20150215T02:04:06 - - -tld -org - - -date_created -20150215T03:04:06 - - - - - -` diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi_test.go b/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi_test.go deleted file mode 100644 index 2b8f63b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package gandi - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "regexp" - "strings" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("GANDI_API_KEY") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "GANDI_API_KEY": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "GANDI_API_KEY": "", - }, - expected: "gandi: some credentials information are missing: GANDI_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.inProgressFQDNs) - require.NotNil(t, p.inProgressAuthZones) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "gandi: no API Key given", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.inProgressFQDNs) - require.NotNil(t, p.inProgressAuthZones) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -// TestDNSProvider runs Present and CleanUp against a fake Gandi RPC -// Server, whose responses are predetermined for particular requests. -func TestDNSProvider(t *testing.T) { - // serverResponses is the XML-RPC Request->Response map used by the - // fake RPC server. It was generated by recording a real RPC session - // which resulted in the successful issue of a cert, and then - // anonymizing the RPC data. - var serverResponses = map[string]string{ - // Present Request->Response 1 (getZoneID) - present1RequestMock: present1ResponseMock, - // Present Request->Response 2 (cloneZone) - present2RequestMock: present2ResponseMock, - // Present Request->Response 3 (newZoneVersion) - present3RequestMock: present3ResponseMock, - // Present Request->Response 4 (addTXTRecord) - present4RequestMock: present4ResponseMock, - // Present Request->Response 5 (setZoneVersion) - present5RequestMock: present5ResponseMock, - // Present Request->Response 6 (setZone) - present6RequestMock: present6ResponseMock, - // CleanUp Request->Response 1 (setZone) - cleanup1RequestMock: cleanup1ResponseMock, - // CleanUp Request->Response 2 (deleteZone) - cleanup2RequestMock: cleanup2ResponseMock, - } - - fakeKeyAuth := "XXXX" - - regexpDate := regexp.MustCompile(`\[ACME Challenge [^\]:]*:[^\]]*\]`) - - // start fake RPC server - fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, "text/xml", r.Header.Get("Content-Type"), "invalid content type") - - req, errS := ioutil.ReadAll(r.Body) - require.NoError(t, errS) - - req = regexpDate.ReplaceAllLiteral(req, []byte(`[ACME Challenge 01 Jan 16 00:00 +0000]`)) - resp, ok := serverResponses[string(req)] - require.True(t, ok, "Server response for request not found") - - _, errS = io.Copy(w, strings.NewReader(resp)) - require.NoError(t, errS) - })) - defer fakeServer.Close() - - // define function to override findZoneByFqdn with - fakeFindZoneByFqdn := func(fqdn string) (string, error) { - return "example.com.", nil - } - - config := NewDefaultConfig() - config.BaseURL = fakeServer.URL + "/" - config.APIKey = "123412341234123412341234" - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - // override findZoneByFqdn function - savedFindZoneByFqdn := provider.findZoneByFqdn - defer func() { - provider.findZoneByFqdn = savedFindZoneByFqdn - }() - provider.findZoneByFqdn = fakeFindZoneByFqdn - - // run Present - err = provider.Present("abc.def.example.com", "", fakeKeyAuth) - require.NoError(t, err) - - // run CleanUp - err = provider.CleanUp("abc.def.example.com", "", fakeKeyAuth) - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/client.go b/vendor/github.com/go-acme/lego/providers/dns/gandiv5/client.go deleted file mode 100644 index 5c2c248..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/client.go +++ /dev/null @@ -1,199 +0,0 @@ -package gandiv5 - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - - "github.com/go-acme/lego/log" -) - -const apiKeyHeader = "X-Api-Key" - -// types for JSON responses with only a message -type apiResponse struct { - Message string `json:"message"` - UUID string `json:"uuid,omitempty"` -} - -// Record TXT record representation -type Record struct { - RRSetTTL int `json:"rrset_ttl"` - RRSetValues []string `json:"rrset_values"` - RRSetName string `json:"rrset_name,omitempty"` - RRSetType string `json:"rrset_type,omitempty"` -} - -func (d *DNSProvider) addTXTRecord(domain string, name string, value string, ttl int) error { - // Get exiting values for the TXT records - // Needed to create challenges for both wildcard and base name domains - txtRecord, err := d.getTXTRecord(domain, name) - if err != nil { - return err - } - - values := []string{value} - if len(txtRecord.RRSetValues) > 0 { - values = append(values, txtRecord.RRSetValues...) - } - - target := fmt.Sprintf("domains/%s/records/%s/TXT", domain, name) - - newRecord := &Record{RRSetTTL: ttl, RRSetValues: values} - req, err := d.newRequest(http.MethodPut, target, newRecord) - if err != nil { - return err - } - - message := apiResponse{} - err = d.do(req, &message) - if err != nil { - return fmt.Errorf("unable to create TXT record for domain %s and name %s: %v", domain, name, err) - } - - if len(message.Message) > 0 { - log.Infof("API response: %s", message.Message) - } - - return nil -} - -func (d *DNSProvider) getTXTRecord(domain, name string) (*Record, error) { - target := fmt.Sprintf("domains/%s/records/%s/TXT", domain, name) - - // Get exiting values for the TXT records - // Needed to create challenges for both wildcard and base name domains - req, err := d.newRequest(http.MethodGet, target, nil) - if err != nil { - return nil, err - } - - txtRecord := &Record{} - err = d.do(req, txtRecord) - if err != nil { - return nil, fmt.Errorf("unable to get TXT records for domain %s and name %s: %v", domain, name, err) - } - - return txtRecord, nil -} - -func (d *DNSProvider) deleteTXTRecord(domain string, name string) error { - target := fmt.Sprintf("domains/%s/records/%s/TXT", domain, name) - - req, err := d.newRequest(http.MethodDelete, target, nil) - if err != nil { - return err - } - - message := apiResponse{} - err = d.do(req, &message) - if err != nil { - return fmt.Errorf("unable to delete TXT record for domain %s and name %s: %v", domain, name, err) - } - - if len(message.Message) > 0 { - log.Infof("API response: %s", message.Message) - } - - return nil -} - -func (d *DNSProvider) newRequest(method, resource string, body interface{}) (*http.Request, error) { - u := fmt.Sprintf("%s/%s", d.config.BaseURL, resource) - - if body == nil { - req, err := http.NewRequest(method, u, nil) - if err != nil { - return nil, err - } - - return req, nil - } - - reqBody, err := json.Marshal(body) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, u, bytes.NewBuffer(reqBody)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - - return req, nil -} - -func (d *DNSProvider) do(req *http.Request, v interface{}) error { - if len(d.config.APIKey) > 0 { - req.Header.Set(apiKeyHeader, d.config.APIKey) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - - err = checkResponse(resp) - if err != nil { - return err - } - - if v == nil { - return nil - } - - raw, err := readBody(resp) - if err != nil { - return fmt.Errorf("failed to read body: %v", err) - } - - if len(raw) > 0 { - err = json.Unmarshal(raw, v) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(raw)) - } - } - - return nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode == 404 && resp.Request.Method == http.MethodGet { - return nil - } - - if resp.StatusCode >= 400 { - data, err := readBody(resp) - if err != nil { - return fmt.Errorf("%d [%s] request failed: %v", resp.StatusCode, http.StatusText(resp.StatusCode), err) - } - - message := &apiResponse{} - err = json.Unmarshal(data, message) - if err != nil { - return fmt.Errorf("%d [%s] request failed: %v: %s", resp.StatusCode, http.StatusText(resp.StatusCode), err, data) - } - return fmt.Errorf("%d [%s] request failed: %s", resp.StatusCode, http.StatusText(resp.StatusCode), message.Message) - } - - return nil -} - -func readBody(resp *http.Response) ([]byte, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil") - } - - defer resp.Body.Close() - - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return rawBody, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.go b/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.go deleted file mode 100644 index e7d326b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.go +++ /dev/null @@ -1,167 +0,0 @@ -// Package gandiv5 implements a DNS provider for solving the DNS-01 challenge using Gandi LiveDNS api. -package gandiv5 - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Gandi API reference: http://doc.livedns.gandi.net/ - -const ( - // defaultBaseURL endpoint is the Gandi API endpoint used by Present and CleanUp. - defaultBaseURL = "https://dns.api.gandi.net/api/v5" - minTTL = 300 -) - -// inProgressInfo contains information about an in-progress challenge -type inProgressInfo struct { - fieldName string - authZone string -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GANDIV5_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GANDIV5_PROPAGATION_TIMEOUT", 20*time.Minute), - PollingInterval: env.GetOrDefaultSecond("GANDIV5_POLLING_INTERVAL", 20*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GANDIV5_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the -// acme.ChallengeProviderTimeout interface that uses Gandi's LiveDNS -// API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - inProgressFQDNs map[string]inProgressInfo - inProgressMu sync.Mutex - // findZoneByFqdn determines the DNS zone of an fqdn. It is overridden during tests. - findZoneByFqdn func(fqdn string) (string, error) -} - -// NewDNSProvider returns a DNSProvider instance configured for Gandi. -// Credentials must be passed in the environment variable: GANDIV5_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GANDIV5_API_KEY") - if err != nil { - return nil, fmt.Errorf("gandi: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["GANDIV5_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Gandi. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("gandiv5: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("gandiv5: no API Key given") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("gandiv5: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{ - config: config, - inProgressFQDNs: make(map[string]inProgressInfo), - findZoneByFqdn: dns01.FindZoneByFqdn, - }, nil -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // find authZone - authZone, err := d.findZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("gandiv5: findZoneByFqdn failure: %v", err) - } - - // determine name of TXT record - if !strings.HasSuffix( - strings.ToLower(fqdn), strings.ToLower("."+authZone)) { - return fmt.Errorf("gandiv5: unexpected authZone %s for fqdn %s", authZone, fqdn) - } - name := fqdn[:len(fqdn)-len("."+authZone)] - - // acquire lock and check there is not a challenge already in - // progress for this value of authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - // add TXT record into authZone - err = d.addTXTRecord(dns01.UnFqdn(authZone), name, value, d.config.TTL) - if err != nil { - return err - } - - // save data necessary for CleanUp - d.inProgressFQDNs[fqdn] = inProgressInfo{ - authZone: authZone, - fieldName: name, - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // acquire lock and retrieve authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - if _, ok := d.inProgressFQDNs[fqdn]; !ok { - // if there is no cleanup information then just return - return nil - } - - fieldName := d.inProgressFQDNs[fqdn].fieldName - authZone := d.inProgressFQDNs[fqdn].authZone - delete(d.inProgressFQDNs, fqdn) - - // delete TXT record from authZone - err := d.deleteTXTRecord(dns01.UnFqdn(authZone), fieldName) - if err != nil { - return fmt.Errorf("gandiv5: %v", err) - } - return nil -} - -// Timeout returns the values (20*time.Minute, 20*time.Second) which -// are used by the acme package as timeout and check interval values -// when checking for DNS record propagation with Gandi. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.toml b/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.toml deleted file mode 100644 index bd2ffd9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Gandi Live DNS (v5)" -Description = '''''' -URL = "https://www.gandi.net" -Code = "gandiv5" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - GANDIV5_API_KEY = "API key" - [Configuration.Additional] - GANDIV5_POLLING_INTERVAL = "Time between DNS propagation check" - GANDIV5_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - GANDIV5_TTL = "The TTL of the TXT record used for the DNS challenge" - GANDIV5_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "http://doc.livedns.gandi.net" diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5_test.go b/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5_test.go deleted file mode 100644 index 238a68e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5_test.go +++ /dev/null @@ -1,187 +0,0 @@ -package gandiv5 - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "regexp" - "testing" - - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("GANDIV5_API_KEY") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "GANDIV5_API_KEY": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "GANDIV5_API_KEY": "", - }, - expected: "gandi: some credentials information are missing: GANDIV5_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.inProgressFQDNs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "gandiv5: no API Key given", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.inProgressFQDNs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -// TestDNSProvider runs Present and CleanUp against a fake Gandi RPC -// Server, whose responses are predetermined for particular requests. -func TestDNSProvider(t *testing.T) { - // serverResponses is the JSON Request->Response map used by the - // fake JSON server. - var serverResponses = map[string]map[string]string{ - http.MethodGet: { - ``: `{"rrset_ttl":300,"rrset_values":[],"rrset_name":"_acme-challenge.abc.def","rrset_type":"TXT"}`, - }, - http.MethodPut: { - `{"rrset_ttl":300,"rrset_values":["TOKEN"]}`: `{"message": "Zone Record Created"}`, - }, - http.MethodDelete: { - ``: ``, - }, - } - - fakeKeyAuth := "XXXX" - - regexpToken := regexp.MustCompile(`"rrset_values":\[".+"\]`) - - // start fake RPC server - handler := http.NewServeMux() - handler.HandleFunc("/domains/example.com/records/_acme-challenge.abc.def/TXT", func(rw http.ResponseWriter, req *http.Request) { - log.Infof("request: %s %s", req.Method, req.URL) - - if req.Header.Get(apiKeyHeader) == "" { - http.Error(rw, `{"message": "missing API key"}`, http.StatusUnauthorized) - return - } - - if req.Method == http.MethodPost && req.Header.Get("Content-Type") != "application/json" { - http.Error(rw, `{"message": "invalid content type"}`, http.StatusBadRequest) - return - } - - body, errS := ioutil.ReadAll(req.Body) - if errS != nil { - http.Error(rw, fmt.Sprintf(`{"message": "read body error: %v"}`, errS), http.StatusInternalServerError) - return - } - - body = regexpToken.ReplaceAllLiteral(body, []byte(`"rrset_values":["TOKEN"]`)) - - responses, ok := serverResponses[req.Method] - if !ok { - http.Error(rw, fmt.Sprintf(`{"message": "Server response for request not found: %#q"}`, string(body)), http.StatusInternalServerError) - return - } - - resp := responses[string(body)] - - _, errS = rw.Write([]byte(resp)) - if errS != nil { - http.Error(rw, fmt.Sprintf(`{"message": "failed to write response: %v"}`, errS), http.StatusInternalServerError) - return - } - }) - handler.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { - log.Infof("request: %s %s", req.Method, req.URL) - http.Error(rw, fmt.Sprintf(`{"message": "URL doesn't match: %s"}`, req.URL), http.StatusNotFound) - }) - - server := httptest.NewServer(handler) - defer server.Close() - - // define function to override findZoneByFqdn with - fakeFindZoneByFqdn := func(fqdn string) (string, error) { - return "example.com.", nil - } - - config := NewDefaultConfig() - config.APIKey = "123412341234123412341234" - config.BaseURL = server.URL - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - // override findZoneByFqdn function - savedFindZoneByFqdn := provider.findZoneByFqdn - defer func() { - provider.findZoneByFqdn = savedFindZoneByFqdn - }() - provider.findZoneByFqdn = fakeFindZoneByFqdn - - // run Present - err = provider.Present("abc.def.example.com", "", fakeKeyAuth) - require.NoError(t, err) - - // run CleanUp - err = provider.CleanUp("abc.def.example.com", "", fakeKeyAuth) - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gcloud/fixtures/gce_account_service_file.json b/vendor/github.com/go-acme/lego/providers/dns/gcloud/fixtures/gce_account_service_file.json deleted file mode 100644 index c9b6168..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gcloud/fixtures/gce_account_service_file.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "project_id": "A", - "type": "service_account", - "client_email": "foo@bar.com", - "private_key_id": "pki", - "private_key": "pk", - "token_uri": "/token", - "client_secret": "secret", - "client_id": "C", - "refresh_token": "D" -} \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/providers/dns/gcloud/gcloud.toml b/vendor/github.com/go-acme/lego/providers/dns/gcloud/gcloud.toml deleted file mode 100644 index e5b7580..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gcloud/gcloud.toml +++ /dev/null @@ -1,22 +0,0 @@ -Name = "Google Cloud" -Description = '''''' -URL = "https://cloud.google.com" -Code = "gcloud" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - GCE_PROJECT = "Project name" - 'Application Default Credentials' = "[Documentation](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application)" - GCE_SERVICE_ACCOUNT_FILE = "Account file path" - GCE_SERVICE_ACCOUNT = "Account" - [Configuration.Additional] - GCE_POLLING_INTERVAL = "Time between DNS propagation check" - GCE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - GCE_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://community.exoscale.com/documentation/dns/api/" - GoClient = "https://github.com/googleapis/google-api-go-client" diff --git a/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud.go b/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud.go deleted file mode 100644 index 331a5c0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud.go +++ /dev/null @@ -1,337 +0,0 @@ -// Package gcloud implements a DNS provider for solving the DNS-01 challenge using Google Cloud DNS. -package gcloud - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/platform/wait" - "golang.org/x/net/context" - "golang.org/x/oauth2/google" - "google.golang.org/api/dns/v1" - "google.golang.org/api/googleapi" - "google.golang.org/api/option" -) - -const ( - changeStatusDone = "done" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Debug bool - Project string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - Debug: env.GetOrDefaultBool("GCE_DEBUG", false), - TTL: env.GetOrDefaultInt("GCE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("GCE_PROPAGATION_TIMEOUT", 180*time.Second), - PollingInterval: env.GetOrDefaultSecond("GCE_POLLING_INTERVAL", 5*time.Second), - } -} - -// DNSProvider is an implementation of the DNSProvider interface. -type DNSProvider struct { - config *Config - client *dns.Service -} - -// NewDNSProvider returns a DNSProvider instance configured for Google Cloud DNS. -// Project name must be passed in the environment variable: GCE_PROJECT. -// A Service Account can be passed in the environment variable: GCE_SERVICE_ACCOUNT -// or by specifying the keyfile location: GCE_SERVICE_ACCOUNT_FILE -func NewDNSProvider() (*DNSProvider, error) { - // Use a service account file if specified via environment variable. - if saKey := env.GetOrFile("GCE_SERVICE_ACCOUNT"); len(saKey) > 0 { - return NewDNSProviderServiceAccountKey([]byte(saKey)) - } - - // Use default credentials. - project := env.GetOrDefaultString("GCE_PROJECT", "") - return NewDNSProviderCredentials(project) -} - -// NewDNSProviderCredentials uses the supplied credentials -// to return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderCredentials(project string) (*DNSProvider, error) { - if project == "" { - return nil, fmt.Errorf("googlecloud: project name missing") - } - - client, err := google.DefaultClient(context.Background(), dns.NdevClouddnsReadwriteScope) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to get Google Cloud client: %v", err) - } - - config := NewDefaultConfig() - config.Project = project - config.HTTPClient = client - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderServiceAccountKey uses the supplied service account JSON -// to return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderServiceAccountKey(saKey []byte) (*DNSProvider, error) { - if len(saKey) == 0 { - return nil, fmt.Errorf("googlecloud: Service Account is missing") - } - - // If GCE_PROJECT is non-empty it overrides the project in the service - // account file. - project := env.GetOrDefaultString("GCE_PROJECT", "") - if project == "" { - // read project id from service account file - var datJSON struct { - ProjectID string `json:"project_id"` - } - err := json.Unmarshal(saKey, &datJSON) - if err != nil || datJSON.ProjectID == "" { - return nil, fmt.Errorf("googlecloud: project ID not found in Google Cloud Service Account file") - } - project = datJSON.ProjectID - } - - conf, err := google.JWTConfigFromJSON(saKey, dns.NdevClouddnsReadwriteScope) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to acquire config: %v", err) - } - client := conf.Client(context.Background()) - - config := NewDefaultConfig() - config.Project = project - config.HTTPClient = client - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderServiceAccount uses the supplied service account JSON file -// to return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderServiceAccount(saFile string) (*DNSProvider, error) { - if saFile == "" { - return nil, fmt.Errorf("googlecloud: Service Account file missing") - } - - saKey, err := ioutil.ReadFile(saFile) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to read Service Account file: %v", err) - } - - return NewDNSProviderServiceAccountKey(saKey) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("googlecloud: the configuration of the DNS provider is nil") - } - if config.HTTPClient == nil { - return nil, fmt.Errorf("googlecloud: unable to create Google Cloud DNS service: client is nil") - } - - svc, err := dns.NewService(context.Background(), option.WithHTTPClient(config.HTTPClient)) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to create Google Cloud DNS service: %v", err) - } - - return &DNSProvider{config: config, client: svc}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - // Look for existing records. - existingRrSet, err := d.findTxtRecords(zone, fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - for _, rrSet := range existingRrSet { - var rrd []string - for _, rr := range rrSet.Rrdatas { - data := mustUnquote(rr) - rrd = append(rrd, data) - - if data == value { - log.Printf("skip: the record already exists: %s", value) - return nil - } - } - rrSet.Rrdatas = rrd - } - - // Attempt to delete the existing records before adding the new one. - if len(existingRrSet) > 0 { - if err = d.applyChanges(zone, &dns.Change{Deletions: existingRrSet}); err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - } - - rec := &dns.ResourceRecordSet{ - Name: fqdn, - Rrdatas: []string{value}, - Ttl: int64(d.config.TTL), - Type: "TXT", - } - - // Append existing TXT record data to the new TXT record data - for _, rrSet := range existingRrSet { - for _, rr := range rrSet.Rrdatas { - if rr != value { - rec.Rrdatas = append(rec.Rrdatas, rr) - } - } - } - - change := &dns.Change{ - Additions: []*dns.ResourceRecordSet{rec}, - } - - if err = d.applyChanges(zone, change); err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - return nil -} - -func (d *DNSProvider) applyChanges(zone string, change *dns.Change) error { - if d.config.Debug { - data, _ := json.Marshal(change) - log.Printf("change (Create): %s", string(data)) - } - - chg, err := d.client.Changes.Create(d.config.Project, zone, change).Do() - if err != nil { - if v, ok := err.(*googleapi.Error); ok { - if v.Code == http.StatusNotFound { - return nil - } - } - - data, _ := json.Marshal(change) - return fmt.Errorf("failed to perform changes [zone %s, change %s]: %v", zone, string(data), err) - } - - if chg.Status == changeStatusDone { - return nil - } - - chgID := chg.Id - - // wait for change to be acknowledged - return wait.For("apply change", 30*time.Second, 3*time.Second, func() (bool, error) { - if d.config.Debug { - data, _ := json.Marshal(change) - log.Printf("change (Get): %s", string(data)) - } - - chg, err = d.client.Changes.Get(d.config.Project, zone, chgID).Do() - if err != nil { - data, _ := json.Marshal(change) - return false, fmt.Errorf("failed to get changes [zone %s, change %s]: %v", zone, string(data), err) - } - - if chg.Status == changeStatusDone { - return true, nil - } - - return false, fmt.Errorf("status: %s", chg.Status) - }) -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - records, err := d.findTxtRecords(zone, fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - if len(records) == 0 { - return nil - } - - _, err = d.client.Changes.Create(d.config.Project, zone, &dns.Change{Deletions: records}).Do() - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - return nil -} - -// Timeout customizes the timeout values used by the ACME package for checking -// DNS record validity. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// getHostedZone returns the managed-zone -func (d *DNSProvider) getHostedZone(domain string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", err - } - - zones, err := d.client.ManagedZones. - List(d.config.Project). - DnsName(authZone). - Do() - if err != nil { - return "", fmt.Errorf("API call failed: %v", err) - } - - if len(zones.ManagedZones) == 0 { - return "", fmt.Errorf("no matching domain found for domain %s", authZone) - } - - for _, z := range zones.ManagedZones { - if z.Visibility == "public" || z.Visibility == "" { - return z.Name, nil - } - } - - return "", fmt.Errorf("no public zone found for domain %s", authZone) -} - -func (d *DNSProvider) findTxtRecords(zone, fqdn string) ([]*dns.ResourceRecordSet, error) { - recs, err := d.client.ResourceRecordSets.List(d.config.Project, zone).Name(fqdn).Type("TXT").Do() - if err != nil { - return nil, err - } - - return recs.Rrsets, nil -} - -func mustUnquote(raw string) string { - clean, err := strconv.Unquote(raw) - if err != nil { - return raw - } - return clean -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud_test.go b/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud_test.go deleted file mode 100644 index 14e5828..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud_test.go +++ /dev/null @@ -1,419 +0,0 @@ -package gcloud - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "sort" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" - "golang.org/x/net/context" - "golang.org/x/oauth2/google" - "google.golang.org/api/dns/v1" -) - -var envTest = tester.NewEnvTest( - "GCE_PROJECT", - "GCE_SERVICE_ACCOUNT_FILE", - "GOOGLE_APPLICATION_CREDENTIALS", - "GCE_SERVICE_ACCOUNT"). - WithDomain("GCE_DOMAIN"). - WithLiveTestExtra(func() bool { - _, err := google.DefaultClient(context.Background(), dns.NdevClouddnsReadwriteScope) - return err == nil - }) - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "invalid credentials", - envVars: map[string]string{ - "GCE_PROJECT": "123", - "GCE_SERVICE_ACCOUNT_FILE": "", - // as Travis run on GCE, we have to alter env - "GOOGLE_APPLICATION_CREDENTIALS": "not-a-secret-file", - }, - expected: "googlecloud: unable to get Google Cloud client: google: error getting credentials using GOOGLE_APPLICATION_CREDENTIALS environment variable: open not-a-secret-file: no such file or directory", - }, - { - desc: "missing project", - envVars: map[string]string{ - "GCE_PROJECT": "", - "GCE_SERVICE_ACCOUNT_FILE": "", - }, - expected: "googlecloud: project name missing", - }, - { - desc: "success key file", - envVars: map[string]string{ - "GCE_PROJECT": "", - "GCE_SERVICE_ACCOUNT_FILE": "fixtures/gce_account_service_file.json", - }, - }, - { - desc: "success key", - envVars: map[string]string{ - "GCE_PROJECT": "", - "GCE_SERVICE_ACCOUNT": `{"project_id": "A","type": "service_account","client_email": "foo@bar.com","private_key_id": "pki","private_key": "pk","token_uri": "/token","client_secret": "secret","client_id": "C","refresh_token": "D"}`, - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - project string - expected string - }{ - { - desc: "invalid project", - project: "123", - expected: "googlecloud: unable to create Google Cloud DNS service: client is nil", - }, - { - desc: "missing project", - expected: "googlecloud: unable to create Google Cloud DNS service: client is nil", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - config := NewDefaultConfig() - config.Project = test.project - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestPresentNoExistingRR(t *testing.T) { - mux := http.NewServeMux() - - // getHostedZone: /manhattan/managedZones?alt=json&dnsName=lego.wtf. - mux.HandleFunc("/manhattan/managedZones", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - mzlrs := &dns.ManagedZonesListResponse{ - ManagedZones: []*dns.ManagedZone{ - {Name: "test", Visibility: "public"}, - }, - } - - err := json.NewEncoder(w).Encode(mzlrs) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - // findTxtRecords: /manhattan/managedZones/test/rrsets?alt=json&name=_acme-challenge.lego.wtf.&type=TXT - mux.HandleFunc("/manhattan/managedZones/test/rrsets", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - rrslr := &dns.ResourceRecordSetsListResponse{ - Rrsets: []*dns.ResourceRecordSet{}, - } - - err := json.NewEncoder(w).Encode(rrslr) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - // applyChanges [Create]: /manhattan/managedZones/test/changes?alt=json - mux.HandleFunc("/manhattan/managedZones/test/changes", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - var chgReq dns.Change - if err := json.NewDecoder(r.Body).Decode(&chgReq); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - chgResp := chgReq - chgResp.Status = changeStatusDone - - if err := json.NewEncoder(w).Encode(chgResp); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.HTTPClient = &http.Client{} - config.Project = "manhattan" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - p.client.BasePath = server.URL - - domain := "lego.wtf" - - err = p.Present(domain, "", "") - require.NoError(t, err) -} - -func TestPresentWithExistingRR(t *testing.T) { - mux := http.NewServeMux() - - // getHostedZone: /manhattan/managedZones?alt=json&dnsName=lego.wtf. - mux.HandleFunc("/manhattan/managedZones", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - mzlrs := &dns.ManagedZonesListResponse{ - ManagedZones: []*dns.ManagedZone{ - {Name: "test", Visibility: "public"}, - }, - } - - err := json.NewEncoder(w).Encode(mzlrs) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - // findTxtRecords: /manhattan/managedZones/test/rrsets?alt=json&name=_acme-challenge.lego.wtf.&type=TXT - mux.HandleFunc("/manhattan/managedZones/test/rrsets", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - rrslr := &dns.ResourceRecordSetsListResponse{ - Rrsets: []*dns.ResourceRecordSet{{ - Name: "_acme-challenge.lego.wtf.", - Rrdatas: []string{`"X7DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU"`, `"huji"`}, - Ttl: 120, - Type: "TXT", - }}, - } - - err := json.NewEncoder(w).Encode(rrslr) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - // applyChanges [Create]: /manhattan/managedZones/test/changes?alt=json - mux.HandleFunc("/manhattan/managedZones/test/changes", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - var chgReq dns.Change - if err := json.NewDecoder(r.Body).Decode(&chgReq); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - if len(chgReq.Additions) > 0 { - sort.Strings(chgReq.Additions[0].Rrdatas) - } - - var prevVal string - for _, addition := range chgReq.Additions { - for _, value := range addition.Rrdatas { - if prevVal == value { - http.Error(w, fmt.Sprintf("The resource %s already exists", value), http.StatusConflict) - return - } - prevVal = value - } - } - - chgResp := chgReq - chgResp.Status = changeStatusDone - - if err := json.NewEncoder(w).Encode(chgResp); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.HTTPClient = &http.Client{} - config.Project = "manhattan" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - p.client.BasePath = server.URL - - domain := "lego.wtf" - - err = p.Present(domain, "", "") - require.NoError(t, err) -} - -func TestPresentSkipExistingRR(t *testing.T) { - mux := http.NewServeMux() - - // getHostedZone: /manhattan/managedZones?alt=json&dnsName=lego.wtf. - mux.HandleFunc("/manhattan/managedZones", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - mzlrs := &dns.ManagedZonesListResponse{ - ManagedZones: []*dns.ManagedZone{ - {Name: "test", Visibility: "public"}, - }, - } - - err := json.NewEncoder(w).Encode(mzlrs) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - // findTxtRecords: /manhattan/managedZones/test/rrsets?alt=json&name=_acme-challenge.lego.wtf.&type=TXT - mux.HandleFunc("/manhattan/managedZones/test/rrsets", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - rrslr := &dns.ResourceRecordSetsListResponse{ - Rrsets: []*dns.ResourceRecordSet{{ - Name: "_acme-challenge.lego.wtf.", - Rrdatas: []string{`"47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU"`, `"X7DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU"`, `"huji"`}, - Ttl: 120, - Type: "TXT", - }}, - } - - err := json.NewEncoder(w).Encode(rrslr) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.HTTPClient = &http.Client{} - config.Project = "manhattan" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - p.client.BasePath = server.URL - - domain := "lego.wtf" - - err = p.Present(domain, "", "") - require.NoError(t, err) -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - provider, err := NewDNSProviderCredentials(envTest.GetValue("GCE_PROJECT")) - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLivePresentMultiple(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - provider, err := NewDNSProviderCredentials(envTest.GetValue("GCE_PROJECT")) - require.NoError(t, err) - - // Check that we're able to create multiple entries - err = provider.Present(envTest.GetDomain(), "1", "123d==") - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "2", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - provider, err := NewDNSProviderCredentials(envTest.GetValue("GCE_PROJECT")) - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/glesys/client.go b/vendor/github.com/go-acme/lego/providers/dns/glesys/client.go deleted file mode 100644 index ea64f6b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/glesys/client.go +++ /dev/null @@ -1,91 +0,0 @@ -package glesys - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - - "github.com/go-acme/lego/log" -) - -// types for JSON method calls, parameters, and responses - -type addRecordRequest struct { - DomainName string `json:"domainname"` - Host string `json:"host"` - Type string `json:"type"` - Data string `json:"data"` - TTL int `json:"ttl,omitempty"` -} - -type deleteRecordRequest struct { - RecordID int `json:"recordid"` -} - -type responseStruct struct { - Response struct { - Status struct { - Code int `json:"code"` - } `json:"status"` - Record deleteRecordRequest `json:"record"` - } `json:"response"` -} - -func (d *DNSProvider) addTXTRecord(fqdn string, domain string, name string, value string, ttl int) (int, error) { - response, err := d.sendRequest(http.MethodPost, "addrecord", addRecordRequest{ - DomainName: domain, - Host: name, - Type: "TXT", - Data: value, - TTL: ttl, - }) - - if response != nil && response.Response.Status.Code == http.StatusOK { - log.Infof("[%s]: Successfully created record id %d", fqdn, response.Response.Record.RecordID) - return response.Response.Record.RecordID, nil - } - return 0, err -} - -func (d *DNSProvider) deleteTXTRecord(fqdn string, recordid int) error { - response, err := d.sendRequest(http.MethodPost, "deleterecord", deleteRecordRequest{ - RecordID: recordid, - }) - if response != nil && response.Response.Status.Code == 200 { - log.Infof("[%s]: Successfully deleted record id %d", fqdn, recordid) - } - return err -} - -func (d *DNSProvider) sendRequest(method string, resource string, payload interface{}) (*responseStruct, error) { - url := fmt.Sprintf("%s/%s", defaultBaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.SetBasicAuth(d.config.APIUser, d.config.APIKey) - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("request failed with HTTP status code %d", resp.StatusCode) - } - - var response responseStruct - err = json.NewDecoder(resp.Body).Decode(&response) - - return &response, err -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.go b/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.go deleted file mode 100644 index 6b481cf..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.go +++ /dev/null @@ -1,146 +0,0 @@ -// Package glesys implements a DNS provider for solving the DNS-01 challenge using GleSYS api. -package glesys - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - // defaultBaseURL is the GleSYS API endpoint used by Present and CleanUp. - defaultBaseURL = "https://api.glesys.com/domain" - minTTL = 60 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIUser string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GLESYS_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GLESYS_PROPAGATION_TIMEOUT", 20*time.Minute), - PollingInterval: env.GetOrDefaultSecond("GLESYS_POLLING_INTERVAL", 20*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GLESYS_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the -// acme.ChallengeProviderTimeout interface that uses GleSYS -// API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - activeRecords map[string]int - inProgressMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for GleSYS. -// Credentials must be passed in the environment variables: -// GLESYS_API_USER and GLESYS_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GLESYS_API_USER", "GLESYS_API_KEY") - if err != nil { - return nil, fmt.Errorf("glesys: %v", err) - } - - config := NewDefaultConfig() - config.APIUser = values["GLESYS_API_USER"] - config.APIKey = values["GLESYS_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for GleSYS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("glesys: the configuration of the DNS provider is nil") - } - - if config.APIUser == "" || config.APIKey == "" { - return nil, fmt.Errorf("glesys: incomplete credentials provided") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("glesys: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{ - config: config, - activeRecords: make(map[string]int), - }, nil -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // find authZone - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("glesys: findZoneByFqdn failure: %v", err) - } - - // determine name of TXT record - if !strings.HasSuffix( - strings.ToLower(fqdn), strings.ToLower("."+authZone)) { - return fmt.Errorf("glesys: unexpected authZone %s for fqdn %s", authZone, fqdn) - } - name := fqdn[:len(fqdn)-len("."+authZone)] - - // acquire lock and check there is not a challenge already in - // progress for this value of authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - // add TXT record into authZone - recordID, err := d.addTXTRecord(domain, dns01.UnFqdn(authZone), name, value, d.config.TTL) - if err != nil { - return err - } - - // save data necessary for CleanUp - d.activeRecords[fqdn] = recordID - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // acquire lock and retrieve authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - if _, ok := d.activeRecords[fqdn]; !ok { - // if there is no cleanup information then just return - return nil - } - - recordID := d.activeRecords[fqdn] - delete(d.activeRecords, fqdn) - - // delete TXT record from authZone - return d.deleteTXTRecord(domain, recordID) -} - -// Timeout returns the values (20*time.Minute, 20*time.Second) which -// are used by the acme package as timeout and check interval values -// when checking for DNS record propagation with GleSYS. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.toml b/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.toml deleted file mode 100644 index c65c32f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Glesys" -Description = '''''' -URL = "https://glesys.com/" -Code = "glesys" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - GLESYS_API_USER = "API user" - GLESYS_API_KEY = "API key" - [Configuration.Additional] - GLESYS_POLLING_INTERVAL = "Time between DNS propagation check" - GLESYS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - GLESYS_TTL = "The TTL of the TXT record used for the DNS challenge" - GLESYS_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://github.com/GleSYS/API/wiki/API-Documentation" diff --git a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys_test.go b/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys_test.go deleted file mode 100644 index ebb9050..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package glesys - -import ( - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "GLESYS_API_USER", - "GLESYS_API_KEY"). - WithDomain("GLESYS_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "GLESYS_API_USER": "A", - "GLESYS_API_KEY": "B", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "GLESYS_API_USER": "", - "GLESYS_API_KEY": "", - }, - expected: "glesys: some credentials information are missing: GLESYS_API_USER,GLESYS_API_KEY", - }, - { - desc: "missing api user", - envVars: map[string]string{ - "GLESYS_API_USER": "", - "GLESYS_API_KEY": "B", - }, - expected: "glesys: some credentials information are missing: GLESYS_API_USER", - }, - { - desc: "missing api key", - envVars: map[string]string{ - "GLESYS_API_USER": "A", - "GLESYS_API_KEY": "", - }, - expected: "glesys: some credentials information are missing: GLESYS_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.activeRecords) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiUser string - apiKey string - expected string - }{ - { - desc: "success", - apiUser: "A", - apiKey: "B", - }, - { - desc: "missing credentials", - expected: "glesys: incomplete credentials provided", - }, - { - desc: "missing api user", - apiUser: "", - apiKey: "B", - expected: "glesys: incomplete credentials provided", - }, - { - desc: "missing api key", - apiUser: "A", - apiKey: "", - expected: "glesys: incomplete credentials provided", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.APIUser = test.apiUser - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.activeRecords) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/godaddy/client.go b/vendor/github.com/go-acme/lego/providers/dns/godaddy/client.go deleted file mode 100644 index 212b8e6..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/godaddy/client.go +++ /dev/null @@ -1,53 +0,0 @@ -package godaddy - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" -) - -// DNSRecord a DNS record -type DNSRecord struct { - Type string `json:"type"` - Name string `json:"name"` - Data string `json:"data"` - Priority int `json:"priority,omitempty"` - TTL int `json:"ttl,omitempty"` -} - -func (d *DNSProvider) updateRecords(records []DNSRecord, domainZone string, recordName string) error { - body, err := json.Marshal(records) - if err != nil { - return err - } - - var resp *http.Response - resp, err = d.makeRequest(http.MethodPut, fmt.Sprintf("/v1/domains/%s/records/TXT/%s", domainZone, recordName), bytes.NewReader(body)) - if err != nil { - return err - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - bodyBytes, _ := ioutil.ReadAll(resp.Body) - return fmt.Errorf("could not create record %v; Status: %v; Body: %s", string(body), resp.StatusCode, string(bodyBytes)) - } - return nil -} - -func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest(method, fmt.Sprintf("%s%s", defaultBaseURL, uri), body) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", "application/json") - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("sso-key %s:%s", d.config.APIKey, d.config.APISecret)) - - return d.config.HTTPClient.Do(req) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.go b/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.go deleted file mode 100644 index 7e803ca..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.go +++ /dev/null @@ -1,151 +0,0 @@ -// Package godaddy implements a DNS provider for solving the DNS-01 challenge using godaddy DNS. -package godaddy - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - // defaultBaseURL represents the API endpoint to call. - defaultBaseURL = "https://api.godaddy.com" - minTTL = 600 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - APISecret string - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GODADDY_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GODADDY_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("GODADDY_POLLING_INTERVAL", 2*time.Second), - SequenceInterval: env.GetOrDefaultSecond("GODADDY_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GODADDY_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for godaddy. -// Credentials must be passed in the environment variables: -// GODADDY_API_KEY and GODADDY_API_SECRET. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GODADDY_API_KEY", "GODADDY_API_SECRET") - if err != nil { - return nil, fmt.Errorf("godaddy: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["GODADDY_API_KEY"] - config.APISecret = values["GODADDY_API_SECRET"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for godaddy. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("godaddy: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" || config.APISecret == "" { - return nil, fmt.Errorf("godaddy: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("godaddy: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - domainZone, err := d.getZone(fqdn) - if err != nil { - return err - } - - recordName := d.extractRecordName(fqdn, domainZone) - rec := []DNSRecord{ - { - Type: "TXT", - Name: recordName, - Data: value, - TTL: d.config.TTL, - }, - } - - return d.updateRecords(rec, domainZone, recordName) -} - -// CleanUp sets null value in the TXT DNS record as GoDaddy has no proper DELETE record method -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - domainZone, err := d.getZone(fqdn) - if err != nil { - return err - } - - recordName := d.extractRecordName(fqdn, domainZone) - rec := []DNSRecord{ - { - Type: "TXT", - Name: recordName, - Data: "null", - }, - } - - return d.updateRecords(rec, domainZone, recordName) -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} - -func (d *DNSProvider) getZone(fqdn string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - return dns01.UnFqdn(authZone), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.toml b/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.toml deleted file mode 100644 index eb4acb6..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Go Daddy" -Description = '''''' -URL = "https://godaddy.com" -Code = "godaddy" -Since = "v0.5.0" - -[Configuration] - [Configuration.Credentials] - GODADDY_API_KEY = "API key" - GODADDY_API_SECRET = "API secret" - [Configuration.Additional] - GODADDY_POLLING_INTERVAL = "Time between DNS propagation check" - GODADDY_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - GODADDY_TTL = "The TTL of the TXT record used for the DNS challenge" - GODADDY_HTTP_TIMEOUT = "API request timeout" - GODADDY_SEQUENCE_INTERVAL = "Interval between iteration" - -[Links] - API = "https://developer.godaddy.com/doc/endpoint/domains" diff --git a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy_test.go b/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy_test.go deleted file mode 100644 index d7ecf99..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package godaddy - -import ( - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "GODADDY_API_KEY", - "GODADDY_API_SECRET"). - WithDomain("GODADDY_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "GODADDY_API_KEY": "123", - "GODADDY_API_SECRET": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "GODADDY_API_KEY": "", - "GODADDY_API_SECRET": "", - }, - expected: "godaddy: some credentials information are missing: GODADDY_API_KEY,GODADDY_API_SECRET", - }, - { - desc: "missing access key", - envVars: map[string]string{ - "GODADDY_API_KEY": "", - "GODADDY_API_SECRET": "456", - }, - expected: "godaddy: some credentials information are missing: GODADDY_API_KEY", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "GODADDY_API_KEY": "123", - "GODADDY_API_SECRET": "", - }, - expected: "godaddy: some credentials information are missing: GODADDY_API_SECRET", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - apiSecret string - expected string - }{ - { - desc: "success", - apiKey: "123", - apiSecret: "456", - }, - { - desc: "missing credentials", - expected: "godaddy: credentials missing", - }, - { - desc: "missing api key", - apiSecret: "456", - expected: "godaddy: credentials missing", - }, - { - desc: "missing secret key", - apiKey: "123", - expected: "godaddy: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.APISecret = test.apiSecret - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/client.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/client.go deleted file mode 100644 index b1a23a3..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/client.go +++ /dev/null @@ -1,127 +0,0 @@ -package hostingde - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "time" - - "github.com/cenkalti/backoff" -) - -const defaultBaseURL = "https://secure.hosting.de/api/dns/v1/json" - -// https://www.hosting.de/api/?json#list-zoneconfigs -func (d *DNSProvider) listZoneConfigs(findRequest ZoneConfigsFindRequest) (*ZoneConfigsFindResponse, error) { - uri := defaultBaseURL + "/zoneConfigsFind" - - findResponse := &ZoneConfigsFindResponse{} - - rawResp, err := d.post(uri, findRequest, findResponse) - if err != nil { - return nil, err - } - - if len(findResponse.Response.Data) == 0 { - return nil, fmt.Errorf("%v: %s", err, toUnreadableBodyMessage(uri, rawResp)) - } - - if findResponse.Status != "success" && findResponse.Status != "pending" { - return findResponse, errors.New(toUnreadableBodyMessage(uri, rawResp)) - } - - return findResponse, nil -} - -// https://www.hosting.de/api/?json#updating-zones -func (d *DNSProvider) updateZone(updateRequest ZoneUpdateRequest) (*ZoneUpdateResponse, error) { - uri := defaultBaseURL + "/zoneUpdate" - - // but we'll need the ID later to delete the record - updateResponse := &ZoneUpdateResponse{} - - rawResp, err := d.post(uri, updateRequest, updateResponse) - if err != nil { - return nil, err - } - - if updateResponse.Status != "success" && updateResponse.Status != "pending" { - return nil, errors.New(toUnreadableBodyMessage(uri, rawResp)) - } - - return updateResponse, nil -} - -func (d *DNSProvider) getZone(findRequest ZoneConfigsFindRequest) (*ZoneConfig, error) { - ctx, cancel := context.WithCancel(context.Background()) - - var zoneConfig *ZoneConfig - - operation := func() error { - findResponse, err := d.listZoneConfigs(findRequest) - if err != nil { - cancel() - return err - } - - if findResponse.Response.Data[0].Status != "active" { - return fmt.Errorf("unexpected status: %q", findResponse.Response.Data[0].Status) - } - - zoneConfig = &findResponse.Response.Data[0] - - return nil - } - - bo := backoff.NewExponentialBackOff() - bo.InitialInterval = 3 * time.Second - bo.MaxInterval = 10 * bo.InitialInterval - bo.MaxElapsedTime = 100 * bo.InitialInterval - - // retry in case the zone was edited recently and is not yet active - err := backoff.Retry(operation, backoff.WithContext(bo, ctx)) - if err != nil { - return nil, err - } - - return zoneConfig, nil -} - -func (d *DNSProvider) post(uri string, request interface{}, response interface{}) ([]byte, error) { - body, err := json.Marshal(request) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(http.MethodPost, uri, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error querying API: %v", err) - } - - defer resp.Body.Close() - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.New(toUnreadableBodyMessage(uri, content)) - } - - err = json.Unmarshal(content, response) - if err != nil { - return nil, fmt.Errorf("%v: %s", err, toUnreadableBodyMessage(uri, content)) - } - - return content, nil -} - -func toUnreadableBodyMessage(uri string, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", uri, string(rawBody)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.go deleted file mode 100644 index 4a00f04..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.go +++ /dev/null @@ -1,183 +0,0 @@ -// Package hostingde implements a DNS provider for solving the DNS-01 challenge using hosting.de. -package hostingde - -import ( - "errors" - "fmt" - "net/http" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - ZoneName string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("HOSTINGDE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("HOSTINGDE_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("HOSTINGDE_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("HOSTINGDE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - recordIDs map[string]string - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for hosting.de. -// Credentials must be passed in the environment variables: -// HOSTINGDE_ZONE_NAME and HOSTINGDE_API_KEY -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("HOSTINGDE_API_KEY", "HOSTINGDE_ZONE_NAME") - if err != nil { - return nil, fmt.Errorf("hostingde: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["HOSTINGDE_API_KEY"] - config.ZoneName = values["HOSTINGDE_ZONE_NAME"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for hosting.de. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("hostingde: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, errors.New("hostingde: API key missing") - } - - if config.ZoneName == "" { - return nil, errors.New("hostingde: Zone Name missing") - } - - return &DNSProvider{ - config: config, - recordIDs: make(map[string]string), - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // get the ZoneConfig for that domain - zonesFind := ZoneConfigsFindRequest{ - Filter: Filter{ - Field: "zoneName", - Value: d.config.ZoneName, - }, - Limit: 1, - Page: 1, - } - zonesFind.AuthToken = d.config.APIKey - - zoneConfig, err := d.getZone(zonesFind) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - zoneConfig.Name = d.config.ZoneName - - rec := []DNSRecord{{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - Content: value, - TTL: d.config.TTL, - }} - - req := ZoneUpdateRequest{ - ZoneConfig: *zoneConfig, - RecordsToAdd: rec, - } - req.AuthToken = d.config.APIKey - - resp, err := d.updateZone(req) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - - for _, record := range resp.Response.Records { - if record.Name == dns01.UnFqdn(fqdn) && record.Content == fmt.Sprintf(`"%s"`, value) { - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = record.ID - d.recordIDsMu.Unlock() - } - } - - if d.recordIDs[fqdn] == "" { - return fmt.Errorf("hostingde: error getting ID of just created record, for domain %s", domain) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - rec := []DNSRecord{{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - Content: `"` + value + `"`, - }} - - // get the ZoneConfig for that domain - zonesFind := ZoneConfigsFindRequest{ - Filter: Filter{ - Field: "zoneName", - Value: d.config.ZoneName, - }, - Limit: 1, - Page: 1, - } - zonesFind.AuthToken = d.config.APIKey - - zoneConfig, err := d.getZone(zonesFind) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - zoneConfig.Name = d.config.ZoneName - - req := ZoneUpdateRequest{ - ZoneConfig: *zoneConfig, - RecordsToDelete: rec, - } - req.AuthToken = d.config.APIKey - - // Delete record ID from map - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - _, err = d.updateZone(req) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.toml b/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.toml deleted file mode 100644 index f19c494..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Hosting.de" -Description = '''''' -URL = "https://www.hosting.de/" -Code = "hostingde" -Since = "v1.1.0" - -[Configuration] - [Configuration.Credentials] - HOSTINGDE_API_KEY = "API key" - HOSTINGDE_ZONE_NAME = "Zone name in ACE format" - [Configuration.Additional] - HOSTINGDE_POLLING_INTERVAL = "Time between DNS propagation check" - HOSTINGDE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - HOSTINGDE_TTL = "The TTL of the TXT record used for the DNS challenge" - HOSTINGDE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.hosting.de/api/#dns" - - diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde_test.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde_test.go deleted file mode 100644 index ba07790..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package hostingde - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "HOSTINGDE_API_KEY", - "HOSTINGDE_ZONE_NAME"). - WithDomain("HOSTINGDE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "HOSTINGDE_API_KEY": "123", - "HOSTINGDE_ZONE_NAME": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "HOSTINGDE_API_KEY": "", - "HOSTINGDE_ZONE_NAME": "", - }, - expected: "hostingde: some credentials information are missing: HOSTINGDE_API_KEY,HOSTINGDE_ZONE_NAME", - }, - { - desc: "missing access key", - envVars: map[string]string{ - "HOSTINGDE_API_KEY": "", - "HOSTINGDE_ZONE_NAME": "456", - }, - expected: "hostingde: some credentials information are missing: HOSTINGDE_API_KEY", - }, - { - desc: "missing zone name", - envVars: map[string]string{ - "HOSTINGDE_API_KEY": "123", - "HOSTINGDE_ZONE_NAME": "", - }, - expected: "hostingde: some credentials information are missing: HOSTINGDE_ZONE_NAME", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.recordIDs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - zoneName string - expected string - }{ - { - desc: "success", - apiKey: "123", - zoneName: "456", - }, - { - desc: "missing credentials", - expected: "hostingde: API key missing", - }, - { - desc: "missing api key", - zoneName: "456", - expected: "hostingde: API key missing", - }, - { - desc: "missing zone name", - apiKey: "123", - expected: "hostingde: Zone Name missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.ZoneName = test.zoneName - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.recordIDs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/model.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/model.go deleted file mode 100644 index 9c67784..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/model.go +++ /dev/null @@ -1,139 +0,0 @@ -package hostingde - -import "encoding/json" - -// APIError represents an error in an API response. -// https://www.hosting.de/api/?json#warnings-and-errors -type APIError struct { - Code int `json:"code"` - ContextObject string `json:"contextObject"` - ContextPath string `json:"contextPath"` - Details []string `json:"details"` - Text string `json:"text"` - Value string `json:"value"` -} - -// Filter is used to filter FindRequests to the API. -// https://www.hosting.de/api/?json#filter-object -type Filter struct { - Field string `json:"field"` - Value string `json:"value"` -} - -// Sort is used to sort FindRequests from the API. -// https://www.hosting.de/api/?json#filtering-and-sorting -type Sort struct { - Field string `json:"zoneName"` - Order string `json:"order"` -} - -// Metadata represents the metadata in an API response. -// https://www.hosting.de/api/?json#metadata-object -type Metadata struct { - ClientTransactionID string `json:"clientTransactionId"` - ServerTransactionID string `json:"serverTransactionId"` -} - -// ZoneConfig The ZoneConfig object defines a zone. -// https://www.hosting.de/api/?json#the-zoneconfig-object -type ZoneConfig struct { - ID string `json:"id"` - AccountID string `json:"accountId"` - Status string `json:"status"` - Name string `json:"name"` - NameUnicode string `json:"nameUnicode"` - MasterIP string `json:"masterIp"` - Type string `json:"type"` - EMailAddress string `json:"emailAddress"` - ZoneTransferWhitelist []string `json:"zoneTransferWhitelist"` - LastChangeDate string `json:"lastChangeDate"` - DNSServerGroupID string `json:"dnsServerGroupId"` - DNSSecMode string `json:"dnsSecMode"` - SOAValues *SOAValues `json:"soaValues,omitempty"` - TemplateValues json.RawMessage `json:"templateValues,omitempty"` -} - -// SOAValues The SOA values object contains the time (seconds) used in a zone’s SOA record. -// https://www.hosting.de/api/?json#the-soa-values-object -type SOAValues struct { - Refresh int `json:"refresh"` - Retry int `json:"retry"` - Expire int `json:"expire"` - TTL int `json:"ttl"` - NegativeTTL int `json:"negativeTtl"` -} - -// DNSRecord The DNS Record object is part of a zone. It is used to manage DNS resource records. -// https://www.hosting.de/api/?json#the-record-object -type DNSRecord struct { - ID string `json:"id,omitempty"` - ZoneID string `json:"zoneId,omitempty"` - RecordTemplateID string `json:"recordTemplateId,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` - Content string `json:"content,omitempty"` - TTL int `json:"ttl,omitempty"` - Priority int `json:"priority,omitempty"` - LastChangeDate string `json:"lastChangeDate,omitempty"` -} - -// Zone The Zone Object. -// https://www.hosting.de/api/?json#the-zone-object -type Zone struct { - Records []DNSRecord `json:"records"` - ZoneConfig ZoneConfig `json:"zoneConfig"` -} - -// ZoneUpdateRequest represents a API ZoneUpdate request. -// https://www.hosting.de/api/?json#updating-zones -type ZoneUpdateRequest struct { - BaseRequest - ZoneConfig `json:"zoneConfig"` - RecordsToAdd []DNSRecord `json:"recordsToAdd"` - RecordsToDelete []DNSRecord `json:"recordsToDelete"` -} - -// ZoneUpdateResponse represents a response from the API. -// https://www.hosting.de/api/?json#updating-zones -type ZoneUpdateResponse struct { - BaseResponse - Response Zone `json:"response"` -} - -// ZoneConfigsFindRequest represents a API ZonesFind request. -// https://www.hosting.de/api/?json#list-zoneconfigs -type ZoneConfigsFindRequest struct { - BaseRequest - Filter Filter `json:"filter"` - Limit int `json:"limit"` - Page int `json:"page"` - Sort *Sort `json:"sort,omitempty"` -} - -// ZoneConfigsFindResponse represents the API response for ZoneConfigsFind. -// https://www.hosting.de/api/?json#list-zoneconfigs -type ZoneConfigsFindResponse struct { - BaseResponse - Response struct { - Limit int `json:"limit"` - Page int `json:"page"` - TotalEntries int `json:"totalEntries"` - TotalPages int `json:"totalPages"` - Type string `json:"type"` - Data []ZoneConfig `json:"data"` - } `json:"response"` -} - -// BaseResponse Common response struct. -// https://www.hosting.de/api/?json#responses -type BaseResponse struct { - Errors []APIError `json:"errors"` - Metadata Metadata `json:"metadata"` - Warnings []string `json:"warnings"` - Status string `json:"status"` -} - -// BaseRequest Common request struct. -type BaseRequest struct { - AuthToken string `json:"authToken"` -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.go b/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.go deleted file mode 100644 index e626f2a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.go +++ /dev/null @@ -1,195 +0,0 @@ -// Package httpreq implements a DNS provider for solving the DNS-01 challenge through a HTTP server. -package httpreq - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "path" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -type message struct { - FQDN string `json:"fqdn"` - Value string `json:"value"` -} - -type messageRaw struct { - Domain string `json:"domain"` - Token string `json:"token"` - KeyAuth string `json:"keyAuth"` -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Endpoint *url.URL - Mode string - Username string - Password string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("HTTPREQ_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("HTTPREQ_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("HTTPREQ_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider describes a provider for acme-proxy -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("HTTPREQ_ENDPOINT") - if err != nil { - return nil, fmt.Errorf("httpreq: %v", err) - } - - endpoint, err := url.Parse(values["HTTPREQ_ENDPOINT"]) - if err != nil { - return nil, fmt.Errorf("httpreq: %v", err) - } - - config := NewDefaultConfig() - config.Mode = os.Getenv("HTTPREQ_MODE") - config.Username = os.Getenv("HTTPREQ_USERNAME") - config.Password = os.Getenv("HTTPREQ_PASSWORD") - config.Endpoint = endpoint - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider . -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("httpreq: the configuration of the DNS provider is nil") - } - - if config.Endpoint == nil { - return nil, errors.New("httpreq: the endpoint is missing") - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - if d.config.Mode == "RAW" { - msg := &messageRaw{ - Domain: domain, - Token: token, - KeyAuth: keyAuth, - } - - err := d.doPost("/present", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - msg := &message{ - FQDN: fqdn, - Value: value, - } - - err := d.doPost("/present", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - if d.config.Mode == "RAW" { - msg := &messageRaw{ - Domain: domain, - Token: token, - KeyAuth: keyAuth, - } - - err := d.doPost("/cleanup", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - msg := &message{ - FQDN: fqdn, - Value: value, - } - - err := d.doPost("/cleanup", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil -} - -func (d *DNSProvider) doPost(uri string, msg interface{}) error { - reqBody := &bytes.Buffer{} - err := json.NewEncoder(reqBody).Encode(msg) - if err != nil { - return err - } - - newURI := path.Join(d.config.Endpoint.EscapedPath(), uri) - endpoint, err := d.config.Endpoint.Parse(newURI) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, endpoint.String(), reqBody) - if err != nil { - return err - } - - req.Header.Set("Content-Type", "application/json") - - if len(d.config.Username) > 0 && len(d.config.Password) > 0 { - req.SetBasicAuth(d.config.Username, d.config.Password) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode >= http.StatusBadRequest { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("%d: failed to read response body: %v", resp.StatusCode, err) - } - - return fmt.Errorf("%d: request failed: %v", resp.StatusCode, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.toml b/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.toml deleted file mode 100644 index 6475067..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.toml +++ /dev/null @@ -1,61 +0,0 @@ -Name = "HTTP request" -Description = '''''' -URL = "/dns/httpreq/" -Code = "httpreq" -Since = "v2.0.0" - -Example = ''' -HTTPREQ_ENDPOINT=http://my.server.com:9090 \ -lego --dns httpreq --domains my.domain.com --email my@email.com run -''' - -Additional = ''' -## Description - -The server must provide: - -- `POST` `/present` -- `POST` `/cleanup` - -The URL of the server must be define by `HTTPREQ_ENDPOINT`. - -### Mode - -There are 2 modes (`HTTPREQ_MODE`): - -- default mode: -```json -{ - "fqdn": "_acme-challenge.domain.", - "value": "LHDhK3oGRvkiefQnx7OOczTY5Tic_xZ6HcMOc_gmtoM" -} -``` - -- `RAW` -```json -{ - "domain": "domain", - "token": "token", - "keyAuth": "key" -} -``` - -### Authentication - -Basic authentication (optional) can be set with some environment variables: - -- `HTTPREQ_USERNAME` and `HTTPREQ_PASSWORD` -- both values must be set, otherwise basic authentication is not defined. - -''' - -[Configuration] - [Configuration.Credentials] - HTTPREQ_MODE = "`RAW`, none" - HTTPREQ_ENDPOINT = "The URL of the server" - [Configuration.Additional] - HTTPREQ_USERNAME = "Basic authentication username" - HTTPREQ_PASSWORD = "Basic authentication password" - HTTPREQ_POLLING_INTERVAL = "Time between DNS propagation check" - HTTPREQ_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - HTTPREQ_HTTP_TIMEOUT = "API request timeout" diff --git a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq_test.go b/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq_test.go deleted file mode 100644 index 33a98b6..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq_test.go +++ /dev/null @@ -1,295 +0,0 @@ -package httpreq - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "path" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("HTTPREQ_ENDPOINT", "HTTPREQ_MODE", "HTTPREQ_USERNAME", "HTTPREQ_PASSWORD") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "HTTPREQ_ENDPOINT": "http://localhost:8090", - }, - }, - { - desc: "invalid URL", - envVars: map[string]string{ - "HTTPREQ_ENDPOINT": ":", - }, - expected: "httpreq: parse :: missing protocol scheme", - }, - { - desc: "missing endpoint", - envVars: map[string]string{ - "HTTPREQ_ENDPOINT": "", - }, - expected: "httpreq: some credentials information are missing: HTTPREQ_ENDPOINT", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - endpoint *url.URL - expected string - }{ - { - desc: "success", - endpoint: mustParse("http://localhost:8090"), - }, - { - desc: "missing endpoint", - expected: "httpreq: the endpoint is missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Endpoint = test.endpoint - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProvider_Present(t *testing.T) { - envTest.RestoreEnv() - - testCases := []struct { - desc string - mode string - username string - password string - pathPrefix string - handler http.HandlerFunc - expectedError string - }{ - { - desc: "success", - handler: successHandler, - }, - { - desc: "success with path prefix", - handler: successHandler, - pathPrefix: "/api/acme/", - }, - { - desc: "error", - handler: http.NotFound, - expectedError: "httpreq: 404: request failed: 404 page not found\n", - }, - { - desc: "success raw mode", - mode: "RAW", - handler: successRawModeHandler, - }, - { - desc: "error raw mode", - mode: "RAW", - handler: http.NotFound, - expectedError: "httpreq: 404: request failed: 404 page not found\n", - }, - { - desc: "basic auth", - username: "bar", - password: "foo", - handler: func(rw http.ResponseWriter, req *http.Request) { - username, password, ok := req.BasicAuth() - if username != "bar" || password != "foo" || !ok { - rw.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, "Please enter your username and password.")) - http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - - fmt.Fprint(rw, "lego") - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - mux := http.NewServeMux() - mux.HandleFunc(path.Join("/", test.pathPrefix, "present"), test.handler) - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.Endpoint = mustParse(server.URL + test.pathPrefix) - config.Mode = test.mode - config.Username = test.username - config.Password = test.password - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = p.Present("domain", "token", "key") - if test.expectedError == "" { - require.NoError(t, err) - } else { - require.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestNewDNSProvider_Cleanup(t *testing.T) { - envTest.RestoreEnv() - - testCases := []struct { - desc string - mode string - username string - password string - handler http.HandlerFunc - expectedError string - }{ - { - desc: "success", - handler: successHandler, - }, - { - desc: "error", - handler: http.NotFound, - expectedError: "httpreq: 404: request failed: 404 page not found\n", - }, - { - desc: "success raw mode", - mode: "RAW", - handler: successRawModeHandler, - }, - { - desc: "error raw mode", - mode: "RAW", - handler: http.NotFound, - expectedError: "httpreq: 404: request failed: 404 page not found\n", - }, - { - desc: "basic auth", - username: "bar", - password: "foo", - handler: func(rw http.ResponseWriter, req *http.Request) { - username, password, ok := req.BasicAuth() - if username != "bar" || password != "foo" || !ok { - rw.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, "Please enter your username and password.")) - http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - fmt.Fprint(rw, "lego") - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - mux := http.NewServeMux() - mux.HandleFunc("/cleanup", test.handler) - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.Endpoint = mustParse(server.URL) - config.Mode = test.mode - config.Username = test.username - config.Password = test.password - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = p.CleanUp("domain", "token", "key") - if test.expectedError == "" { - require.NoError(t, err) - } else { - require.EqualError(t, err, test.expectedError) - } - }) - } -} - -func successHandler(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - msg := &message{} - err := json.NewDecoder(req.Body).Decode(msg) - if err != nil { - http.Error(rw, err.Error(), http.StatusBadRequest) - return - } - - fmt.Fprint(rw, "lego") -} - -func successRawModeHandler(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - msg := &messageRaw{} - err := json.NewDecoder(req.Body).Decode(msg) - if err != nil { - http.Error(rw, err.Error(), http.StatusBadRequest) - return - } - - fmt.Fprint(rw, "lego") -} - -func mustParse(rawURL string) *url.URL { - uri, err := url.Parse(rawURL) - if err != nil { - panic(err) - } - return uri -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/iij/iij.go b/vendor/github.com/go-acme/lego/providers/dns/iij/iij.go deleted file mode 100644 index cceae69..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/iij/iij.go +++ /dev/null @@ -1,239 +0,0 @@ -// Package iij implements a DNS provider for solving the DNS-01 challenge using IIJ DNS. -package iij - -import ( - "fmt" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/iij/doapi" - "github.com/iij/doapi/protocol" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AccessKey string - SecretKey string - DoServiceCode string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("IIJ_TTL", 300), - PropagationTimeout: env.GetOrDefaultSecond("IIJ_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("IIJ_POLLING_INTERVAL", 4*time.Second), - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - api *doapi.API - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for IIJ DO -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("IIJ_API_ACCESS_KEY", "IIJ_API_SECRET_KEY", "IIJ_DO_SERVICE_CODE") - if err != nil { - return nil, fmt.Errorf("iij: %v", err) - } - - config := NewDefaultConfig() - config.AccessKey = values["IIJ_API_ACCESS_KEY"] - config.SecretKey = values["IIJ_API_SECRET_KEY"] - config.DoServiceCode = values["IIJ_DO_SERVICE_CODE"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig takes a given config -// and returns a custom configured DNSProvider instance -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config.SecretKey == "" || config.AccessKey == "" || config.DoServiceCode == "" { - return nil, fmt.Errorf("iij: credentials missing") - } - - return &DNSProvider{ - api: doapi.NewAPI(config.AccessKey, config.SecretKey), - config: config, - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - - err := d.addTxtRecord(domain, value) - if err != nil { - return fmt.Errorf("iij: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - - err := d.deleteTxtRecord(domain, value) - if err != nil { - return fmt.Errorf("iij: %v", err) - } - return nil -} - -func (d *DNSProvider) addTxtRecord(domain, value string) error { - zones, err := d.listZones() - if err != nil { - return err - } - - owner, zone, err := splitDomain(domain, zones) - if err != nil { - return err - } - - request := protocol.RecordAdd{ - DoServiceCode: d.config.DoServiceCode, - ZoneName: zone, - Owner: owner, - TTL: strconv.Itoa(d.config.TTL), - RecordType: "TXT", - RData: value, - } - - response := &protocol.RecordAddResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return err - } - - return d.commit() -} - -func (d *DNSProvider) deleteTxtRecord(domain, value string) error { - zones, err := d.listZones() - if err != nil { - return err - } - - owner, zone, err := splitDomain(domain, zones) - if err != nil { - return err - } - - id, err := d.findTxtRecord(owner, zone, value) - if err != nil { - return err - } - - request := protocol.RecordDelete{ - DoServiceCode: d.config.DoServiceCode, - ZoneName: zone, - RecordID: id, - } - - response := &protocol.RecordDeleteResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return err - } - - return d.commit() -} - -func (d *DNSProvider) commit() error { - request := protocol.Commit{ - DoServiceCode: d.config.DoServiceCode, - } - - response := &protocol.CommitResponse{} - - return doapi.Call(*d.api, request, response) -} - -func (d *DNSProvider) findTxtRecord(owner, zone, value string) (string, error) { - request := protocol.RecordListGet{ - DoServiceCode: d.config.DoServiceCode, - ZoneName: zone, - } - - response := &protocol.RecordListGetResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return "", err - } - - var id string - - for _, record := range response.RecordList { - if record.Owner == owner && record.RecordType == "TXT" && record.RData == "\""+value+"\"" { - id = record.Id - } - } - - if id == "" { - return "", fmt.Errorf("%s record in %s not found", owner, zone) - } - - return id, nil -} - -func (d *DNSProvider) listZones() ([]string, error) { - request := protocol.ZoneListGet{ - DoServiceCode: d.config.DoServiceCode, - } - - response := &protocol.ZoneListGetResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return nil, err - } - - return response.ZoneList, nil -} - -func splitDomain(domain string, zones []string) (string, string, error) { - parts := strings.Split(strings.Trim(domain, "."), ".") - - var owner string - var zone string - - for i := 0; i < len(parts)-1; i++ { - zone = strings.Join(parts[i:], ".") - if zoneContains(zone, zones) { - baseOwner := strings.Join(parts[0:i], ".") - if len(baseOwner) > 0 { - baseOwner = "." + baseOwner - } - owner = "_acme-challenge" + baseOwner - break - } - } - - if len(owner) == 0 { - return "", "", fmt.Errorf("%s not found", domain) - } - - return owner, zone, nil -} - -func zoneContains(zone string, zones []string) bool { - for _, z := range zones { - if zone == z { - return true - } - } - return false -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/iij/iij.toml b/vendor/github.com/go-acme/lego/providers/dns/iij/iij.toml deleted file mode 100644 index 5232af0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/iij/iij.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Internet Initiative Japan" -Description = '''''' -URL = "https://www.iij.ad.jp/en/" -Code = "iij" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - IIJ_API_ACCESS_KEY = "API access key" - IIJ_API_SECRET_KEY = "API secret key" - IIJ_DO_SERVICE_CODE = "DO service code" - [Configuration.Additional] - IIJ_POLLING_INTERVAL = "Time between DNS propagation check" - IIJ_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - IIJ_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "http://manual.iij.jp/p2/pubapi/http://manual.iij.jp/p2/pubapi/" - GoClient = "https://github.com/iij/doapi" diff --git a/vendor/github.com/go-acme/lego/providers/dns/iij/iij_test.go b/vendor/github.com/go-acme/lego/providers/dns/iij/iij_test.go deleted file mode 100644 index ea2fc8f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/iij/iij_test.go +++ /dev/null @@ -1,229 +0,0 @@ -package iij - -import ( - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "IIJ_API_ACCESS_KEY", - "IIJ_API_SECRET_KEY", - "IIJ_DO_SERVICE_CODE"). - WithDomain("IIJ_API_TESTDOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "IIJ_API_ACCESS_KEY": "A", - "IIJ_API_SECRET_KEY": "B", - "IIJ_DO_SERVICE_CODE": "C", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "IIJ_API_ACCESS_KEY": "", - "IIJ_API_SECRET_KEY": "", - "IIJ_DO_SERVICE_CODE": "", - }, - expected: "iij: some credentials information are missing: IIJ_API_ACCESS_KEY,IIJ_API_SECRET_KEY,IIJ_DO_SERVICE_CODE", - }, - { - desc: "missing api access key", - envVars: map[string]string{ - "IIJ_API_ACCESS_KEY": "", - "IIJ_API_SECRET_KEY": "B", - "IIJ_DO_SERVICE_CODE": "C", - }, - expected: "iij: some credentials information are missing: IIJ_API_ACCESS_KEY", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "IIJ_API_ACCESS_KEY": "A", - "IIJ_API_SECRET_KEY": "", - "IIJ_DO_SERVICE_CODE": "C", - }, - expected: "iij: some credentials information are missing: IIJ_API_SECRET_KEY", - }, - { - desc: "missing do service code", - envVars: map[string]string{ - "IIJ_API_ACCESS_KEY": "A", - "IIJ_API_SECRET_KEY": "B", - "IIJ_DO_SERVICE_CODE": "", - }, - expected: "iij: some credentials information are missing: IIJ_DO_SERVICE_CODE", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.api) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - accessKey string - secretKey string - doServiceCode string - expected string - }{ - { - desc: "success", - accessKey: "A", - secretKey: "B", - doServiceCode: "C", - }, - { - desc: "missing credentials", - expected: "iij: credentials missing", - }, - { - desc: "missing access key", - accessKey: "", - secretKey: "B", - doServiceCode: "C", - expected: "iij: credentials missing", - }, - { - desc: "missing secret key", - accessKey: "A", - secretKey: "", - doServiceCode: "C", - expected: "iij: credentials missing", - }, - { - desc: "missing do service code", - accessKey: "A", - secretKey: "B", - doServiceCode: "", - expected: "iij: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.AccessKey = test.accessKey - config.SecretKey = test.secretKey - config.DoServiceCode = test.doServiceCode - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.api) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestSplitDomain(t *testing.T) { - testCases := []struct { - desc string - domain string - zones []string - expectedOwner string - expectedZone string - }{ - { - desc: "domain equals zone", - domain: "domain.com", - zones: []string{"domain.com"}, - expectedOwner: "_acme-challenge", - expectedZone: "domain.com", - }, - { - desc: "with a sub domain", - domain: "my.domain.com", - zones: []string{"domain.com"}, - expectedOwner: "_acme-challenge.my", - expectedZone: "domain.com", - }, - { - desc: "with a sub domain in a zone", - domain: "my.sub.domain.com", - zones: []string{"sub.domain.com", "domain.com"}, - expectedOwner: "_acme-challenge.my", - expectedZone: "sub.domain.com", - }, - { - desc: "with a sub sub domain", - domain: "my.sub.domain.com", - zones: []string{"domain1.com", "domain.com"}, - expectedOwner: "_acme-challenge.my.sub", - expectedZone: "domain.com", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - owner, zone, err := splitDomain(test.domain, test.zones) - require.NoError(t, err) - - assert.Equal(t, test.expectedOwner, owner) - assert.Equal(t, test.expectedZone, zone) - }) - } - -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.go b/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.go deleted file mode 100644 index 8b2e34c..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.go +++ /dev/null @@ -1,166 +0,0 @@ -// Package inwx implements a DNS provider for solving the DNS-01 challenge using inwx dom robot -package inwx - -import ( - "errors" - "fmt" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "github.com/nrdcg/goinwx" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Username string - Password string - Sandbox bool - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("INWX_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("INWX_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("INWX_TTL", 300), - Sandbox: env.GetOrDefaultBool("INWX_SANDBOX", false), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *goinwx.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Dyn DNS. -// Credentials must be passed in the environment variables: -// INWX_USERNAME and INWX_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("INWX_USERNAME", "INWX_PASSWORD") - if err != nil { - return nil, fmt.Errorf("inwx: %v", err) - } - - config := NewDefaultConfig() - config.Username = values["INWX_USERNAME"] - config.Password = values["INWX_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Dyn DNS -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("inwx: the configuration of the DNS provider is nil") - } - - if config.Username == "" || config.Password == "" { - return nil, fmt.Errorf("inwx: credentials missing") - } - - if config.Sandbox { - log.Infof("inwx: sandbox mode is enabled") - } - - client := goinwx.NewClient(config.Username, config.Password, &goinwx.ClientOptions{Sandbox: config.Sandbox}) - - return &DNSProvider{config: config, client: client}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - err = d.client.Account.Login() - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - defer func() { - errL := d.client.Account.Logout() - if errL != nil { - log.Infof("inwx: failed to logout: %v", errL) - } - }() - - var request = &goinwx.NameserverRecordRequest{ - Domain: dns01.UnFqdn(authZone), - Name: dns01.UnFqdn(fqdn), - Type: "TXT", - Content: value, - TTL: d.config.TTL, - } - - _, err = d.client.Nameservers.CreateRecord(request) - if err != nil { - switch er := err.(type) { - case *goinwx.ErrorResponse: - if er.Message == "Object exists" { - return nil - } - return fmt.Errorf("inwx: %v", err) - default: - return fmt.Errorf("inwx: %v", err) - } - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - err = d.client.Account.Login() - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - defer func() { - errL := d.client.Account.Logout() - if errL != nil { - log.Infof("inwx: failed to logout: %v", errL) - } - }() - - response, err := d.client.Nameservers.Info(&goinwx.NameserverInfoRequest{ - Domain: dns01.UnFqdn(authZone), - Name: dns01.UnFqdn(fqdn), - Type: "TXT", - }) - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - var lastErr error - for _, record := range response.Records { - err = d.client.Nameservers.DeleteRecord(record.ID) - if err != nil { - lastErr = fmt.Errorf("inwx: %v", err) - } - } - - return lastErr -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.toml b/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.toml deleted file mode 100644 index 3143480..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "INWX" -Description = '''''' -URL = "https://www.inwx.de/en" -Code = "inwx" -Since = "v2.0.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - INWX_USERNAME = "Username" - INWX_PASSWORD = "Password" - [Configuration.Additional] - INWX_POLLING_INTERVAL = "Time between DNS propagation check" - INWX_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - INWX_TTL = "The TTL of the TXT record used for the DNS challenge" - INWX_SANDBOX = "Activate the sandbox (boolean)" - -[Links] - API = "https://www.inwx.de/en/help/apidoc" - GoClient = "https://github.com/nrdcg/goinwx" diff --git a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx_test.go b/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx_test.go deleted file mode 100644 index c521eef..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package inwx - -import ( - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "INWX_USERNAME", - "INWX_PASSWORD", - "INWX_SANDBOX", - "INWX_TTL"). - WithDomain("INWX_DOMAIN"). - WithLiveTestRequirements("INWX_USERNAME", "INWX_PASSWORD", "INWX_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "INWX_USERNAME": "123", - "INWX_PASSWORD": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "INWX_USERNAME": "", - "INWX_PASSWORD": "", - }, - expected: "inwx: some credentials information are missing: INWX_USERNAME,INWX_PASSWORD", - }, - { - desc: "missing username", - envVars: map[string]string{ - "INWX_USERNAME": "", - "INWX_PASSWORD": "456", - }, - expected: "inwx: some credentials information are missing: INWX_USERNAME", - }, - { - desc: "missing password", - envVars: map[string]string{ - "INWX_USERNAME": "123", - "INWX_PASSWORD": "", - }, - expected: "inwx: some credentials information are missing: INWX_PASSWORD", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - username string - password string - expected string - }{ - { - desc: "success", - username: "123", - password: "456", - }, - { - desc: "missing credentials", - expected: "inwx: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Username = test.username - config.Password = test.password - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresentAndCleanup(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - envTest.Apply(map[string]string{ - "INWX_SANDBOX": "true", - "INWX_TTL": "3600", // In sandbox mode, the minimum allowed TTL is 3600 - }) - defer envTest.RestoreEnv() - - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - // Verify that no error is thrown if record already exists - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/client.go b/vendor/github.com/go-acme/lego/providers/dns/joker/client.go deleted file mode 100644 index 18265a8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/client.go +++ /dev/null @@ -1,197 +0,0 @@ -package joker - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" -) - -const defaultBaseURL = "https://dmapi.joker.com/request/" - -// Joker DMAPI Response -type response struct { - Headers url.Values - Body string - StatusCode int - StatusText string - AuthSid string -} - -// parseResponse parses HTTP response body -func parseResponse(message string) *response { - r := &response{Headers: url.Values{}, StatusCode: -1} - - parts := strings.SplitN(message, "\n\n", 2) - - for _, line := range strings.Split(parts[0], "\n") { - if strings.TrimSpace(line) == "" { - continue - } - - kv := strings.SplitN(line, ":", 2) - - val := "" - if len(kv) == 2 { - val = strings.TrimSpace(kv[1]) - } - - r.Headers.Add(kv[0], val) - - switch kv[0] { - case "Status-Code": - i, err := strconv.Atoi(val) - if err == nil { - r.StatusCode = i - } - case "Status-Text": - r.StatusText = val - case "Auth-Sid": - r.AuthSid = val - } - } - - if len(parts) > 1 { - r.Body = parts[1] - } - - return r -} - -// login performs a login to Joker's DMAPI -func (d *DNSProvider) login() (*response, error) { - if d.config.AuthSid != "" { - // already logged in - return nil, nil - } - - response, err := d.postRequest("login", url.Values{"api-key": {d.config.APIKey}}) - if err != nil { - return response, err - } - - if response == nil { - return nil, fmt.Errorf("login returned nil response") - } - - if response.AuthSid == "" { - return response, fmt.Errorf("login did not return valid Auth-Sid") - } - - d.config.AuthSid = response.AuthSid - - return response, nil -} - -// logout closes authenticated session with Joker's DMAPI -func (d *DNSProvider) logout() (*response, error) { - if d.config.AuthSid == "" { - return nil, fmt.Errorf("already logged out") - } - - response, err := d.postRequest("logout", url.Values{}) - if err == nil { - d.config.AuthSid = "" - } - return response, err -} - -// getZone returns content of DNS zone for domain -func (d *DNSProvider) getZone(domain string) (*response, error) { - if d.config.AuthSid == "" { - return nil, fmt.Errorf("must be logged in to get zone") - } - - return d.postRequest("dns-zone-get", url.Values{"domain": {dns01.UnFqdn(domain)}}) -} - -// putZone uploads DNS zone to Joker DMAPI -func (d *DNSProvider) putZone(domain, zone string) (*response, error) { - if d.config.AuthSid == "" { - return nil, fmt.Errorf("must be logged in to put zone") - } - - return d.postRequest("dns-zone-put", url.Values{"domain": {dns01.UnFqdn(domain)}, "zone": {strings.TrimSpace(zone)}}) -} - -// postRequest performs actual HTTP request -func (d *DNSProvider) postRequest(cmd string, data url.Values) (*response, error) { - uri := d.config.BaseURL + cmd - - if d.config.AuthSid != "" { - data.Set("auth-sid", d.config.AuthSid) - } - - if d.config.Debug { - log.Infof("postRequest:\n\tURL: %q\n\tData: %v", uri, data) - } - - resp, err := d.config.HTTPClient.PostForm(uri, data) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("HTTP error %d [%s]: %v", resp.StatusCode, http.StatusText(resp.StatusCode), string(body)) - } - - return parseResponse(string(body)), nil -} - -// Temporary workaround, until it get fixed on API side -func fixTxtLines(line string) string { - fields := strings.Fields(line) - - if len(fields) < 6 || fields[1] != "TXT" { - return line - } - - if fields[3][0] == '"' && fields[4] == `"` { - fields[3] = strings.TrimSpace(fields[3]) + `"` - fields = append(fields[:4], fields[5:]...) - } - - return strings.Join(fields, " ") -} - -// removeTxtEntryFromZone clean-ups all TXT records with given name -func removeTxtEntryFromZone(zone, relative string) (string, bool) { - prefix := fmt.Sprintf("%s TXT 0 ", relative) - - modified := false - var zoneEntries []string - for _, line := range strings.Split(zone, "\n") { - if strings.HasPrefix(line, prefix) { - modified = true - continue - } - zoneEntries = append(zoneEntries, line) - } - - return strings.TrimSpace(strings.Join(zoneEntries, "\n")), modified -} - -// addTxtEntryToZone returns DNS zone with added TXT record -func addTxtEntryToZone(zone, relative, value string, ttl int) string { - var zoneEntries []string - - for _, line := range strings.Split(zone, "\n") { - zoneEntries = append(zoneEntries, fixTxtLines(line)) - } - - newZoneEntry := fmt.Sprintf("%s TXT 0 %q %d", relative, value, ttl) - zoneEntries = append(zoneEntries, newZoneEntry) - - return strings.TrimSpace(strings.Join(zoneEntries, "\n")) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/joker/client_test.go deleted file mode 100644 index e0ead7b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/client_test.go +++ /dev/null @@ -1,447 +0,0 @@ -package joker - -import ( - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - correctAuth = "123" - incorrectAuth = "321" - serverErrorAuth = "500" -) - -func setup() (*http.ServeMux, *httptest.Server) { - mux := http.NewServeMux() - server := httptest.NewServer(mux) - return mux, server -} - -func TestDNSProvider_login(t *testing.T) { - testCases := []struct { - desc string - authKey string - expectedError bool - expectedStatusCode int - expectedAuthSid string - }{ - { - desc: "correct key", - authKey: correctAuth, - expectedStatusCode: 0, - expectedAuthSid: correctAuth, - }, - { - desc: "incorrect key", - authKey: incorrectAuth, - expectedStatusCode: 2200, - expectedError: true, - }, - { - desc: "server error", - authKey: serverErrorAuth, - expectedStatusCode: -500, - expectedError: true, - }, - { - desc: "non-ok status code", - authKey: "333", - expectedStatusCode: 2202, - expectedError: true, - }, - } - - mux, server := setup() - defer server.Close() - - mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, "POST", r.Method) - - switch r.FormValue("api-key") { - case correctAuth: - _, _ = io.WriteString(w, "Status-Code: 0\nStatus-Text: OK\nAuth-Sid: 123\n\ncom\nnet") - case incorrectAuth: - _, _ = io.WriteString(w, "Status-Code: 2200\nStatus-Text: Authentication error") - case serverErrorAuth: - http.NotFound(w, r) - default: - _, _ = io.WriteString(w, "Status-Code: 2202\nStatus-Text: OK\n\ncom\nnet") - } - }) - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.BaseURL = server.URL - config.APIKey = test.authKey - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - require.NotNil(t, p) - - response, err := p.login() - if test.expectedError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.NotNil(t, response) - assert.Equal(t, test.expectedStatusCode, response.StatusCode) - assert.Equal(t, test.expectedAuthSid, response.AuthSid) - } - }) - } -} - -func TestDNSProvider_logout(t *testing.T) { - testCases := []struct { - desc string - authSid string - expectedError bool - expectedStatusCode int - }{ - { - desc: "correct auth-sid", - authSid: correctAuth, - expectedStatusCode: 0, - }, - { - desc: "incorrect auth-sid", - authSid: incorrectAuth, - expectedStatusCode: 2200, - }, - { - desc: "already logged out", - authSid: "", - expectedError: true, - }, - { - desc: "server error", - authSid: serverErrorAuth, - expectedError: true, - }, - } - - mux, server := setup() - defer server.Close() - - mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, "POST", r.Method) - - switch r.FormValue("auth-sid") { - case correctAuth: - _, _ = io.WriteString(w, "Status-Code: 0\nStatus-Text: OK\n") - case incorrectAuth: - _, _ = io.WriteString(w, "Status-Code: 2200\nStatus-Text: Authentication error") - default: - http.NotFound(w, r) - } - }) - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.BaseURL = server.URL - config.APIKey = "12345" - config.AuthSid = test.authSid - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - require.NotNil(t, p) - - response, err := p.logout() - if test.expectedError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.NotNil(t, response) - assert.Equal(t, test.expectedStatusCode, response.StatusCode) - } - }) - } -} - -func TestDNSProvider_getZone(t *testing.T) { - var testZone = "@ A 0 192.0.2.2 3600" - - testCases := []struct { - desc string - authSid string - domain string - zone string - expectedError bool - expectedStatusCode int - }{ - { - desc: "correct auth-sid, known domain", - authSid: correctAuth, - domain: "known", - zone: testZone, - expectedStatusCode: 0, - }, - { - desc: "incorrect auth-sid, known domain", - authSid: incorrectAuth, - domain: "known", - expectedStatusCode: 2202, - }, - { - desc: "correct auth-sid, unknown domain", - authSid: correctAuth, - domain: "unknown", - expectedStatusCode: 2202, - }, - { - desc: "server error", - authSid: "500", - expectedError: true, - }, - } - - mux, server := setup() - defer server.Close() - - mux.HandleFunc("/dns-zone-get", func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, "POST", r.Method) - - authSid := r.FormValue("auth-sid") - domain := r.FormValue("domain") - - switch { - case authSid == correctAuth && domain == "known": - _, _ = io.WriteString(w, "Status-Code: 0\nStatus-Text: OK\n\n"+testZone) - case authSid == incorrectAuth || (authSid == correctAuth && domain == "unknown"): - _, _ = io.WriteString(w, "Status-Code: 2202\nStatus-Text: Authorization error") - default: - http.NotFound(w, r) - } - }) - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.BaseURL = server.URL - config.APIKey = "12345" - config.AuthSid = test.authSid - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - require.NotNil(t, p) - - response, err := p.getZone(test.domain) - if test.expectedError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.NotNil(t, response) - assert.Equal(t, test.expectedStatusCode, response.StatusCode) - assert.Equal(t, test.zone, response.Body) - } - }) - } -} - -func Test_parseResponse(t *testing.T) { - testCases := []struct { - desc string - input string - expected *response - }{ - { - desc: "Empty response", - input: "", - expected: &response{ - Headers: url.Values{}, - StatusCode: -1, - }, - }, - { - desc: "No headers, just body", - input: "\n\nTest body", - expected: &response{ - Headers: url.Values{}, - Body: "Test body", - StatusCode: -1, - }, - }, - { - desc: "Headers and body", - input: "Test-Header: value\n\nTest body", - expected: &response{ - Headers: url.Values{"Test-Header": {"value"}}, - Body: "Test body", - StatusCode: -1, - }, - }, - { - desc: "Headers and body + Auth-Sid", - input: "Test-Header: value\nAuth-Sid: 123\n\nTest body", - expected: &response{ - Headers: url.Values{"Test-Header": {"value"}, "Auth-Sid": {"123"}}, - Body: "Test body", - StatusCode: -1, - AuthSid: "123", - }, - }, - { - desc: "Headers and body + Status-Text", - input: "Test-Header: value\nStatus-Text: OK\n\nTest body", - expected: &response{ - Headers: url.Values{"Test-Header": {"value"}, "Status-Text": {"OK"}}, - Body: "Test body", - StatusText: "OK", - StatusCode: -1, - }, - }, - { - desc: "Headers and body + Status-Code", - input: "Test-Header: value\nStatus-Code: 2020\n\nTest body", - expected: &response{ - Headers: url.Values{"Test-Header": {"value"}, "Status-Code": {"2020"}}, - Body: "Test body", - StatusCode: 2020, - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - response := parseResponse(test.input) - - assert.Equal(t, test.expected, response) - }) - } -} - -func Test_removeTxtEntryFromZone(t *testing.T) { - testCases := []struct { - desc string - input string - expected string - modified bool - }{ - { - desc: "empty zone", - input: "", - expected: "", - modified: false, - }, - { - desc: "zone with only A entry", - input: "@ A 0 192.0.2.2 3600", - expected: "@ A 0 192.0.2.2 3600", - modified: false, - }, - { - desc: "zone with only clenup entry", - input: "_acme-challenge TXT 0 \"old \" 120", - expected: "", - modified: true, - }, - { - desc: "zone with one A and one cleanup entries", - input: "@ A 0 192.0.2.2 3600\n_acme-challenge TXT 0 \"old \" 120", - expected: "@ A 0 192.0.2.2 3600", - modified: true, - }, - { - desc: "zone with one A and multiple cleanup entries", - input: "@ A 0 192.0.2.2 3600\n_acme-challenge TXT 0 \"old \" 120\n_acme-challenge TXT 0 \"another \" 120", - expected: "@ A 0 192.0.2.2 3600", - modified: true, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - zone, modified := removeTxtEntryFromZone(test.input, "_acme-challenge") - assert.Equal(t, zone, test.expected) - assert.Equal(t, modified, test.modified) - }) - } -} - -func Test_addTxtEntryToZone(t *testing.T) { - testCases := []struct { - desc string - input string - expected string - }{ - { - desc: "empty zone", - input: "", - expected: "_acme-challenge TXT 0 \"test\" 120", - }, - { - desc: "zone with A entry", - input: "@ A 0 192.0.2.2 3600", - expected: "@ A 0 192.0.2.2 3600\n_acme-challenge TXT 0 \"test\" 120", - }, - { - desc: "zone with required cleanup entry", - input: "_acme-challenge TXT 0 \"old \" 120", - expected: "_acme-challenge TXT 0 \"old\" 120\n_acme-challenge TXT 0 \"test\" 120", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - zone := addTxtEntryToZone(test.input, "_acme-challenge", "test", 120) - assert.Equal(t, zone, test.expected) - }) - } -} - -func Test_fixTxtLines(t *testing.T) { - testCases := []struct { - desc string - input string - expected string - }{ - { - desc: "clean-up", - input: `_acme-challenge TXT 0 "SrqD25Gpm3WtIGKCqhgsLeXWE_FAD5Hv9CRoLAHxlIE " 120`, - expected: `_acme-challenge TXT 0 "SrqD25Gpm3WtIGKCqhgsLeXWE_FAD5Hv9CRoLAHxlIE" 120`, - }, - { - desc: "already cleaned", - input: `_acme-challenge TXT 0 "SrqD25Gpm3WtIGKCqhgsLeXWE_FAD5Hv9CRoLAHxlIE" 120`, - expected: `_acme-challenge TXT 0 "SrqD25Gpm3WtIGKCqhgsLeXWE_FAD5Hv9CRoLAHxlIE" 120`, - }, - { - desc: "special DNS entry", - input: "$dyndns=yes:username:password", - expected: "$dyndns=yes:username:password", - }, - { - desc: "SRV entry", - input: "_jabber._tcp SRV 20/0 xmpp-server1.l.google.com:5269 300", - expected: "_jabber._tcp SRV 20/0 xmpp-server1.l.google.com:5269 300", - }, - { - desc: "MX entry", - input: "@ MX 10 ASPMX.L.GOOGLE.COM 300", - expected: "@ MX 10 ASPMX.L.GOOGLE.COM 300", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - line := fixTxtLines(test.input) - assert.Equal(t, line, test.expected) - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/joker.go b/vendor/github.com/go-acme/lego/providers/dns/joker/joker.go deleted file mode 100644 index d2dc1ca..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/joker.go +++ /dev/null @@ -1,174 +0,0 @@ -// Package joker implements a DNS provider for solving the DNS-01 challenge using joker.com DMAPI. -package joker - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider. -type Config struct { - Debug bool - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client - AuthSid string -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - Debug: env.GetOrDefaultBool("JOKER_DEBUG", false), - TTL: env.GetOrDefaultInt("JOKER_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("JOKER_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("JOKER_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("JOKER_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// DNSProvider is an implementation of the ChallengeProviderTimeout interface -// that uses Joker's DMAPI to manage TXT records for a domain. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for Joker DMAPI. -// Credentials must be passed in the environment variable JOKER_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("JOKER_API_KEY") - if err != nil { - return nil, fmt.Errorf("joker: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["JOKER_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Joker DMAPI. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("joker: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("joker: credentials missing") - } - - if !strings.HasSuffix(config.BaseURL, "/") { - config.BaseURL += "/" - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present installs a TXT record for the DNS challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("joker: %v", err) - } - - relative := getRelative(fqdn, zone) - - if d.config.Debug { - log.Infof("[%s] joker: adding TXT record %q to zone %q with value %q", domain, relative, zone, value) - } - - response, err := d.login() - if err != nil { - return formatResponseError(response, err) - } - - response, err = d.getZone(zone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - - dnsZone := addTxtEntryToZone(response.Body, relative, value, d.config.TTL) - - response, err = d.putZone(zone, dnsZone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - - return nil -} - -// CleanUp removes a TXT record used for a previous DNS challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("joker: %v", err) - } - - relative := getRelative(fqdn, zone) - - if d.config.Debug { - log.Infof("[%s] joker: removing entry %q from zone %q", domain, relative, zone) - } - - response, err := d.login() - if err != nil { - return formatResponseError(response, err) - } - - defer func() { - // Try to logout in case of errors - _, _ = d.logout() - }() - - response, err = d.getZone(zone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - - dnsZone, modified := removeTxtEntryFromZone(response.Body, relative) - if modified { - response, err = d.putZone(zone, dnsZone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - } - - response, err = d.logout() - if err != nil { - return formatResponseError(response, err) - } - return nil -} - -func getRelative(fqdn, zone string) string { - return dns01.UnFqdn(strings.TrimSuffix(fqdn, dns01.ToFqdn(zone))) -} - -// formatResponseError formats error with optional details from DMAPI response -func formatResponseError(response *response, err error) error { - if response != nil { - return fmt.Errorf("joker: DMAPI error: %v Response: %v", err, response.Headers) - } - return fmt.Errorf("joker: DMAPI error: %v", err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/joker.toml b/vendor/github.com/go-acme/lego/providers/dns/joker/joker.toml deleted file mode 100644 index 0cdace4..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/joker.toml +++ /dev/null @@ -1,22 +0,0 @@ -Name = "Joker" -Description = '''''' -URL = "https://joker.com" -Code = "joker" -Since = "v2.6.0" - -Example = ''' -JOKER_API_KEY= \ -lego --dns joker --domains my.domain.com --email my@email.com run -''' - -[Configuration] - [Configuration.Credentials] - JOKER_API_KEY = "API key" - [Configuration.Additional] - JOKER_POLLING_INTERVAL = "Time between DNS propagation check" - JOKER_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - JOKER_TTL = "The TTL of the TXT record used for the DNS challenge" - JOKER_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://joker.com/faq/category/39/22-dmapi.html" diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/joker_test.go b/vendor/github.com/go-acme/lego/providers/dns/joker/joker_test.go deleted file mode 100644 index 427ac29..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/joker_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package joker - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("JOKER_API_KEY").WithDomain("JOKER_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "JOKER_API_KEY": "123", - }, - }, - { - desc: "missing key", - envVars: map[string]string{ - "JOKER_API_KEY": "", - }, - expected: "joker: some credentials information are missing: JOKER_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - authKey string - baseURL string - expected string - expectedBaseURL string - }{ - { - desc: "success", - authKey: "123", - expectedBaseURL: defaultBaseURL, - }, - { - desc: "missing credentials", - expected: "joker: credentials missing", - expectedBaseURL: defaultBaseURL, - }, - { - desc: "Base URL should ends with /", - authKey: "123", - baseURL: "http://example.com", - expectedBaseURL: "http://example.com/", - }, - { - desc: "Base URL already ends with /", - authKey: "123", - baseURL: "http://example.com/", - expectedBaseURL: "http://example.com/", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.authKey - if test.baseURL != "" { - config.BaseURL = test.baseURL - } - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.Equal(t, test.expectedBaseURL, p.config.BaseURL) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.go b/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.go deleted file mode 100644 index eb3f833..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.go +++ /dev/null @@ -1,153 +0,0 @@ -// Package lightsail implements a DNS provider for solving the DNS-01 challenge using AWS Lightsail DNS. -package lightsail - -import ( - "errors" - "fmt" - "math/rand" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lightsail" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - maxRetries = 5 -) - -// customRetryer implements the client.Retryer interface by composing the DefaultRetryer. -// It controls the logic for retrying recoverable request errors (e.g. when rate limits are exceeded). -type customRetryer struct { - client.DefaultRetryer -} - -// RetryRules overwrites the DefaultRetryer's method. -// It uses a basic exponential backoff algorithm that returns an initial -// delay of ~400ms with an upper limit of ~30 seconds which should prevent -// causing a high number of consecutive throttling errors. -// For reference: Route 53 enforces an account-wide(!) 5req/s query limit. -func (c customRetryer) RetryRules(r *request.Request) time.Duration { - retryCount := r.RetryCount - if retryCount > 7 { - retryCount = 7 - } - - delay := (1 << uint(retryCount)) * (rand.Intn(50) + 200) - return time.Duration(delay) * time.Millisecond -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - DNSZone string - Region string - PropagationTimeout time.Duration - PollingInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - DNSZone: env.GetOrFile("DNS_ZONE"), - PropagationTimeout: env.GetOrDefaultSecond("LIGHTSAIL_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("LIGHTSAIL_POLLING_INTERVAL", dns01.DefaultPollingInterval), - Region: env.GetOrDefaultString("LIGHTSAIL_REGION", "us-east-1"), - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - client *lightsail.Lightsail - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for the AWS Lightsail service. -// -// AWS Credentials are automatically detected in the following locations -// and prioritized in the following order: -// 1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, -// [AWS_SESSION_TOKEN], [DNS_ZONE], [LIGHTSAIL_REGION] -// 2. Shared credentials file (defaults to ~/.aws/credentials) -// 3. Amazon EC2 IAM role -// -// public hosted zone via the FQDN. -// -// See also: https://github.com/aws/aws-sdk-go/wiki/configuring-sdk -func NewDNSProvider() (*DNSProvider, error) { - return NewDNSProviderConfig(NewDefaultConfig()) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for AWS Lightsail. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("lightsail: the configuration of the DNS provider is nil") - } - - retryer := customRetryer{} - retryer.NumMaxRetries = maxRetries - - conf := aws.NewConfig().WithRegion(config.Region) - sess, err := session.NewSession(request.WithRetryer(conf, retryer)) - if err != nil { - return nil, err - } - - return &DNSProvider{ - config: config, - client: lightsail.New(sess), - }, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.newTxtRecord(fqdn, `"`+value+`"`) - if err != nil { - return fmt.Errorf("lightsail: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - params := &lightsail.DeleteDomainEntryInput{ - DomainName: aws.String(d.config.DNSZone), - DomainEntry: &lightsail.DomainEntry{ - Name: aws.String(fqdn), - Type: aws.String("TXT"), - Target: aws.String(`"` + value + `"`), - }, - } - - _, err := d.client.DeleteDomainEntry(params) - if err != nil { - return fmt.Errorf("lightsail: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) newTxtRecord(fqdn string, value string) error { - params := &lightsail.CreateDomainEntryInput{ - DomainName: aws.String(d.config.DNSZone), - DomainEntry: &lightsail.DomainEntry{ - Name: aws.String(fqdn), - Target: aws.String(value), - Type: aws.String("TXT"), - }, - } - _, err := d.client.CreateDomainEntry(params) - return err -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.toml b/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.toml deleted file mode 100644 index a94851a..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Amazon Lightsail" -Description = '''''' -URL = "https://aws.amazon.com/lightsail/" -Code = "lightsail" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - AWS_ACCESS_KEY_ID = "Access key ID" - AWS_SECRET_ACCESS_KEY = "Secret access key" - DNS_ZONE = "DNS zone" - [Configuration.Additional] - LIGHTSAIL_POLLING_INTERVAL = "Time between DNS propagation check" - LIGHTSAIL_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - -[Links] - GoClient = "https://github.com/aws/aws-sdk-go/aws" diff --git a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail_integration_test.go b/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail_integration_test.go deleted file mode 100644 index 4eb7997..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail_integration_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package lightsail - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lightsail" - "github.com/stretchr/testify/require" -) - -func TestLiveTTL(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - provider, err := NewDNSProvider() - require.NoError(t, err) - - domain := envTest.GetDomain() - - err = provider.Present(domain, "foo", "bar") - require.NoError(t, err) - - // we need a separate Lightsail client here as the one in the DNS provider is - // unexported. - fqdn := "_acme-challenge." + domain - sess, err := session.NewSession() - require.NoError(t, err) - - svc := lightsail.New(sess) - require.NoError(t, err) - - defer func() { - errC := provider.CleanUp(domain, "foo", "bar") - if errC != nil { - t.Log(errC) - } - }() - - params := &lightsail.GetDomainInput{ - DomainName: aws.String(domain), - } - - resp, err := svc.GetDomain(params) - require.NoError(t, err) - - entries := resp.Domain.DomainEntries - for _, entry := range entries { - if aws.StringValue(entry.Type) == "TXT" && aws.StringValue(entry.Name) == fqdn { - return - } - } - - t.Fatalf("Could not find a TXT record for _acme-challenge.%s", domain) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail_test.go b/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail_test.go deleted file mode 100644 index cfc1cd5..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package lightsail - -import ( - "net/http/httptest" - "os" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lightsail" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "AWS_ACCESS_KEY_ID", - "AWS_SECRET_ACCESS_KEY", - "AWS_REGION", - "AWS_HOSTED_ZONE_ID"). - WithDomain("DNS_ZONE"). - WithLiveTestRequirements("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "DNS_ZONE") - -func makeProvider(ts *httptest.Server) (*DNSProvider, error) { - config := &aws.Config{ - Credentials: credentials.NewStaticCredentials("abc", "123", " "), - Endpoint: aws.String(ts.URL), - Region: aws.String("mock-region"), - MaxRetries: aws.Int(1), - } - - sess, err := session.NewSession(config) - if err != nil { - return nil, err - } - - conf := NewDefaultConfig() - - client := lightsail.New(sess) - return &DNSProvider{client: client, config: conf}, nil -} - -func TestCredentialsFromEnv(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - os.Setenv("AWS_ACCESS_KEY_ID", "123") - os.Setenv("AWS_SECRET_ACCESS_KEY", "123") - os.Setenv("AWS_REGION", "us-east-1") - - config := &aws.Config{ - CredentialsChainVerboseErrors: aws.Bool(true), - } - - sess, err := session.NewSession(config) - require.NoError(t, err) - - _, err = sess.Config.Credentials.Get() - require.NoError(t, err, "Expected credentials to be set from environment") -} - -func TestDNSProvider_Present(t *testing.T) { - mockResponses := map[string]MockResponse{ - "/": {StatusCode: 200, Body: ""}, - } - - ts := newMockServer(t, mockResponses) - defer ts.Close() - - provider, err := makeProvider(ts) - require.NoError(t, err) - - domain := "example.com" - keyAuth := "123456d==" - - err = provider.Present(domain, "", keyAuth) - require.NoError(t, err, "Expected Present to return no error") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/lightsail/mock_server_test.go b/vendor/github.com/go-acme/lego/providers/dns/lightsail/mock_server_test.go deleted file mode 100644 index a90d2f7..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/lightsail/mock_server_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package lightsail - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -// MockResponse represents a predefined response used by a mock server -type MockResponse struct { - StatusCode int - Body string -} - -func newMockServer(t *testing.T, responses map[string]MockResponse) *httptest.Server { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - path := r.URL.Path - resp, ok := responses[path] - if !ok { - msg := fmt.Sprintf("Requested path not found in response map: %s", path) - require.FailNow(t, msg) - } - - w.Header().Set("Content-Type", "application/xml") - w.WriteHeader(resp.StatusCode) - _, err := w.Write([]byte(resp.Body)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - })) - - time.Sleep(100 * time.Millisecond) - return ts -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/linode/linode.go b/vendor/github.com/go-acme/lego/providers/dns/linode/linode.go deleted file mode 100644 index 9ac8f85..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linode/linode.go +++ /dev/null @@ -1,164 +0,0 @@ -// Package linode implements a DNS provider for solving the DNS-01 challenge using Linode DNS. -package linode - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/timewasted/linode/dns" -) - -const ( - minTTL = 300 - dnsUpdateFreqMins = 15 - dnsUpdateFudgeSecs = 120 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PollingInterval: env.GetOrDefaultSecond("LINODE_POLLING_INTERVAL", 15*time.Second), - TTL: env.GetOrDefaultInt("LINODE_TTL", minTTL), - } -} - -type hostedZoneInfo struct { - domainID int - resourceName string -} - -// DNSProvider implements the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *dns.DNS -} - -// NewDNSProvider returns a DNSProvider instance configured for Linode. -// Credentials must be passed in the environment variable: LINODE_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("LINODE_API_KEY") - if err != nil { - return nil, fmt.Errorf("linode: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["LINODE_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Linode. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("linode: the configuration of the DNS provider is nil") - } - - if len(config.APIKey) == 0 { - return nil, errors.New("linode: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("linode: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{ - config: config, - client: dns.New(config.APIKey), - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - // Since Linode only updates their zone files every X minutes, we need - // to figure out how many minutes we have to wait until we hit the next - // interval of X. We then wait another couple of minutes, just to be - // safe. Hopefully at some point during all of this, the record will - // have propagated throughout Linode's network. - minsRemaining := dnsUpdateFreqMins - (time.Now().Minute() % dnsUpdateFreqMins) - - timeout = (time.Duration(minsRemaining) * time.Minute) + - (minTTL * time.Second) + - (dnsUpdateFudgeSecs * time.Second) - interval = d.config.PollingInterval - return -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - if _, err = d.client.CreateDomainResourceTXT(zone.domainID, dns01.UnFqdn(fqdn), value, d.config.TTL); err != nil { - return err - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - // Get all TXT records for the specified domain. - resources, err := d.client.GetResourcesByType(zone.domainID, "TXT") - if err != nil { - return err - } - - // Remove the specified resource, if it exists. - for _, resource := range resources { - if resource.Name == zone.resourceName && resource.Target == value { - resp, err := d.client.DeleteDomainResource(resource.DomainID, resource.ResourceID) - if err != nil { - return err - } - - if resp.ResourceID != resource.ResourceID { - return errors.New("error deleting resource: resource IDs do not match") - } - break - } - } - - return nil -} - -func (d *DNSProvider) getHostedZoneInfo(fqdn string) (*hostedZoneInfo, error) { - // Lookup the zone that handles the specified FQDN. - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - resourceName := strings.TrimSuffix(fqdn, "."+authZone) - - // Query the authority zone. - domain, err := d.client.GetDomain(dns01.UnFqdn(authZone)) - if err != nil { - return nil, err - } - - return &hostedZoneInfo{ - domainID: domain.DomainID, - resourceName: resourceName, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/linode/linode.toml b/vendor/github.com/go-acme/lego/providers/dns/linode/linode.toml deleted file mode 100644 index 0e912f0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linode/linode.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Linode (deprecated)" -Description = '''''' -URL = "https://www.linode.com/" -Code = "linode" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - LINODE_API_KEY = "API key" - [Configuration.Additional] - LINODE_POLLING_INTERVAL = "Time between DNS propagation check" - LINODE_TTL = "The TTL of the TXT record used for the DNS challenge" - LINODE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.linode.com/api/dns" - GoClient = "https://github.com/timewasted/linode" diff --git a/vendor/github.com/go-acme/lego/providers/dns/linode/linode_test.go b/vendor/github.com/go-acme/lego/providers/dns/linode/linode_test.go deleted file mode 100644 index 9576287..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linode/linode_test.go +++ /dev/null @@ -1,358 +0,0 @@ -package linode - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "os" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/timewasted/linode" - "github.com/timewasted/linode/dns" -) - -type ( - apiResponse struct { - Action string `json:"ACTION"` - Data interface{} `json:"DATA"` - Errors []linode.ResponseError `json:"ERRORARRAY"` - } - MockResponse struct { - Response interface{} - Errors []linode.ResponseError - } - MockResponseMap map[string]MockResponse -) - -var envTest = tester.NewEnvTest("LINODE_API_KEY") - -func newMockServer(responses MockResponseMap) *httptest.Server { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Ensure that we support the requested action. - action := r.URL.Query().Get("api_action") - resp, ok := responses[action] - if !ok { - http.Error(w, fmt.Sprintf("Unsupported mock action: %q", action), http.StatusInternalServerError) - return - } - - // Build the response that the server will return. - response := apiResponse{ - Action: action, - Data: resp.Response, - Errors: resp.Errors, - } - - rawResponse, err := json.Marshal(response) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to JSON encode response: %v", err), http.StatusInternalServerError) - return - } - - // Send the response. - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, err = w.Write(rawResponse) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - })) - - time.Sleep(100 * time.Millisecond) - return srv -} - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "LINODE_API_KEY": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "LINODE_API_KEY": "", - }, - expected: "linode: some credentials information are missing: LINODE_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "linode: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - defer envTest.RestoreEnv() - os.Setenv("LINODE_API_KEY", "testing") - - p, err := NewDNSProvider() - require.NoError(t, err) - - domain := "example.com" - keyAuth := "dGVzdGluZw==" - - testCases := []struct { - desc string - mockResponses MockResponseMap - expectedError string - }{ - { - desc: "success", - mockResponses: MockResponseMap{ - "domain.list": MockResponse{ - Response: []dns.Domain{ - { - Domain: domain, - DomainID: 1234, - }, - }, - }, - "domain.resource.create": MockResponse{ - Response: dns.ResourceResponse{ - ResourceID: 1234, - }, - }, - }, - }, - { - desc: "NoDomain", - mockResponses: MockResponseMap{ - "domain.list": MockResponse{ - Response: []dns.Domain{{ - Domain: "foobar.com", - DomainID: 1234, - }}, - }, - }, - expectedError: "dns: requested domain not found", - }, - { - desc: "CreateFailed", - mockResponses: MockResponseMap{ - "domain.list": MockResponse{ - Response: []dns.Domain{ - { - Domain: domain, - DomainID: 1234, - }, - }, - }, - "domain.resource.create": MockResponse{ - Response: nil, - Errors: []linode.ResponseError{ - { - Code: 1234, - Message: "Failed to create domain resource", - }, - }, - }, - }, - expectedError: "Failed to create domain resource", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - server := newMockServer(test.mockResponses) - defer server.Close() - - p.client.ToLinode().SetEndpoint(server.URL) - - err = p.Present(domain, "", keyAuth) - if len(test.expectedError) == 0 { - assert.NoError(t, err) - } else { - assert.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestDNSProvider_CleanUp(t *testing.T) { - defer envTest.RestoreEnv() - os.Setenv("LINODE_API_KEY", "testing") - - p, err := NewDNSProvider() - require.NoError(t, err) - - domain := "example.com" - keyAuth := "dGVzdGluZw==" - - testCases := []struct { - desc string - mockResponses MockResponseMap - expectedError string - }{ - { - desc: "success", - mockResponses: MockResponseMap{ - "domain.list": MockResponse{ - Response: []dns.Domain{ - { - Domain: domain, - DomainID: 1234, - }, - }, - }, - "domain.resource.list": MockResponse{ - Response: []dns.Resource{ - { - DomainID: 1234, - Name: "_acme-challenge", - ResourceID: 1234, - Target: "ElbOJKOkFWiZLQeoxf-wb3IpOsQCdvoM0y_wn0TEkxM", - Type: "TXT", - }, - }, - }, - "domain.resource.delete": MockResponse{ - Response: dns.ResourceResponse{ - ResourceID: 1234, - }, - }, - }, - }, - { - desc: "NoDomain", - mockResponses: MockResponseMap{ - "domain.list": MockResponse{ - Response: []dns.Domain{ - { - Domain: "foobar.com", - DomainID: 1234, - }, - }, - }, - }, - expectedError: "dns: requested domain not found", - }, - { - desc: "DeleteFailed", - mockResponses: MockResponseMap{ - "domain.list": MockResponse{ - Response: []dns.Domain{ - { - Domain: domain, - DomainID: 1234, - }, - }, - }, - "domain.resource.list": MockResponse{ - Response: []dns.Resource{ - { - DomainID: 1234, - Name: "_acme-challenge", - ResourceID: 1234, - Target: "ElbOJKOkFWiZLQeoxf-wb3IpOsQCdvoM0y_wn0TEkxM", - Type: "TXT", - }, - }, - }, - "domain.resource.delete": MockResponse{ - Response: nil, - Errors: []linode.ResponseError{ - { - Code: 1234, - Message: "Failed to delete domain resource", - }, - }, - }, - }, - expectedError: "Failed to delete domain resource", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - server := newMockServer(test.mockResponses) - defer server.Close() - - p.client.ToLinode().SetEndpoint(server.URL) - - err = p.CleanUp(domain, "", keyAuth) - if len(test.expectedError) == 0 { - assert.NoError(t, err) - } else { - assert.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("Skipping live test") - } - // TODO implement this test -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("Skipping live test") - } - // TODO implement this test -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.go b/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.go deleted file mode 100644 index 5d5a9fc..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.go +++ /dev/null @@ -1,190 +0,0 @@ -// Package linodev4 implements a DNS provider for solving the DNS-01 challenge using Linode DNS and Linode's APIv4 -package linodev4 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/linode/linodego" - "golang.org/x/oauth2" -) - -const ( - minTTL = 300 - dnsUpdateFreqMins = 15 - dnsUpdateFudgeSecs = 120 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - PollingInterval time.Duration - TTL int - HTTPTimeout time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PollingInterval: env.GetOrDefaultSecond("LINODE_POLLING_INTERVAL", 15*time.Second), - TTL: env.GetOrDefaultInt("LINODE_TTL", minTTL), - HTTPTimeout: env.GetOrDefaultSecond("LINODE_HTTP_TIMEOUT", 0), - } -} - -type hostedZoneInfo struct { - domainID int - resourceName string -} - -// DNSProvider implements the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *linodego.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Linode. -// Credentials must be passed in the environment variable: LINODE_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("LINODE_TOKEN") - if err != nil { - return nil, fmt.Errorf("linodev4: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["LINODE_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Linode. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("linodev4: the configuration of the DNS provider is nil") - } - - if len(config.Token) == 0 { - return nil, errors.New("linodev4: Linode Access Token missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("linodev4: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: config.Token}) - oauth2Client := &http.Client{ - Timeout: config.HTTPTimeout, - Transport: &oauth2.Transport{ - Source: tokenSource, - }, - } - - client := linodego.NewClient(oauth2Client) - client.SetUserAgent(fmt.Sprintf("lego-dns linodego/%s", linodego.Version)) - - return &DNSProvider{ - config: config, - client: &client, - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - // Since Linode only updates their zone files every X minutes, we need - // to figure out how many minutes we have to wait until we hit the next - // interval of X. We then wait another couple of minutes, just to be - // safe. Hopefully at some point during all of this, the record will - // have propagated throughout Linode's network. - minsRemaining := dnsUpdateFreqMins - (time.Now().Minute() % dnsUpdateFreqMins) - - timeout = (time.Duration(minsRemaining) * time.Minute) + - (minTTL * time.Second) + - (dnsUpdateFudgeSecs * time.Second) - interval = d.config.PollingInterval - return -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - createOpts := linodego.DomainRecordCreateOptions{ - Name: dns01.UnFqdn(fqdn), - Target: value, - TTLSec: d.config.TTL, - Type: linodego.RecordTypeTXT, - } - - _, err = d.client.CreateDomainRecord(context.Background(), zone.domainID, createOpts) - return err -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - // Get all TXT records for the specified domain. - listOpts := linodego.NewListOptions(0, "{\"type\":\"TXT\"}") - resources, err := d.client.ListDomainRecords(context.Background(), zone.domainID, listOpts) - if err != nil { - return err - } - - // Remove the specified resource, if it exists. - for _, resource := range resources { - if (resource.Name == strings.TrimSuffix(fqdn, ".") || resource.Name == zone.resourceName) && - resource.Target == value { - if err := d.client.DeleteDomainRecord(context.Background(), zone.domainID, resource.ID); err != nil { - return err - } - } - } - - return nil -} - -func (d *DNSProvider) getHostedZoneInfo(fqdn string) (*hostedZoneInfo, error) { - // Lookup the zone that handles the specified FQDN. - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - // Query the authority zone. - data, err := json.Marshal(map[string]string{"domain": dns01.UnFqdn(authZone)}) - if err != nil { - return nil, err - } - - listOpts := linodego.NewListOptions(0, string(data)) - domains, err := d.client.ListDomains(context.Background(), listOpts) - if err != nil { - return nil, err - } - - if len(domains) == 0 { - return nil, fmt.Errorf("domain not found") - } - - return &hostedZoneInfo{ - domainID: domains[0].ID, - resourceName: strings.TrimSuffix(fqdn, "."+authZone), - }, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.toml b/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.toml deleted file mode 100644 index 6111c3e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.toml +++ /dev/null @@ -1,19 +0,0 @@ -Name = "Linode (v4)" -Description = '''''' -URL = "https://www.linode.com/" -Code = "linodev4" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - LINODE_TOKEN = "API token" - [Configuration.Additional] - LINODE_POLLING_INTERVAL = "Time between DNS propagation check" - LINODE_TTL = "The TTL of the TXT record used for the DNS challenge" - LINODE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://developers.linode.com/api/v4" - GoClient = "https://github.com/linode/linodego" diff --git a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4_test.go b/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4_test.go deleted file mode 100644 index 692d829..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4_test.go +++ /dev/null @@ -1,356 +0,0 @@ -package linodev4 - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "os" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/linode/linodego" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type ( - MockResponseMap map[string]interface{} -) - -var envTest = tester.NewEnvTest("LINODE_TOKEN") - -func newMockServer(responses MockResponseMap) *httptest.Server { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Ensure that we support the requested action. - action := r.Method + ":" + r.URL.Path - resp, ok := responses[action] - if !ok { - http.Error(w, fmt.Sprintf("Unsupported mock action: %q", action), http.StatusInternalServerError) - return - } - - rawResponse, err := json.Marshal(resp) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to JSON encode response: %v", err), http.StatusInternalServerError) - return - } - - // Send the response. - w.Header().Set("Content-Type", "application/json") - if err, ok := resp.(linodego.APIError); ok { - if err.Errors[0].Reason == "Not found" { - w.WriteHeader(http.StatusNotFound) - } else { - w.WriteHeader(http.StatusBadRequest) - } - } else { - w.WriteHeader(http.StatusOK) - } - - _, err = w.Write(rawResponse) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - })) - - time.Sleep(100 * time.Millisecond) - return srv -} - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "LINODE_TOKEN": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "LINODE_TOKEN": "", - }, - expected: "linodev4: some credentials information are missing: LINODE_TOKEN", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "linodev4: Linode Access Token missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Token = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - defer envTest.RestoreEnv() - os.Setenv("LINODE_TOKEN", "testing") - - p, err := NewDNSProvider() - require.NoError(t, err) - require.NotNil(t, p) - - domain := "example.com" - keyAuth := "dGVzdGluZw==" - - testCases := []struct { - desc string - mockResponses MockResponseMap - expectedError string - }{ - { - desc: "Success", - mockResponses: MockResponseMap{ - "GET:/domains": linodego.DomainsPagedResponse{ - PageOptions: &linodego.PageOptions{ - Pages: 1, - Results: 1, - Page: 1, - }, - Data: []linodego.Domain{{ - Domain: domain, - ID: 1234, - }}, - }, - "POST:/domains/1234/records": linodego.DomainRecord{ - ID: 1234, - }, - }, - }, - { - desc: "NoDomain", - mockResponses: MockResponseMap{ - "GET:/domains": linodego.APIError{ - Errors: []linodego.APIErrorReason{{ - Reason: "Not found", - }}, - }, - }, - expectedError: "[404] Not found", - }, - { - desc: "CreateFailed", - mockResponses: MockResponseMap{ - "GET:/domains": &linodego.DomainsPagedResponse{ - PageOptions: &linodego.PageOptions{ - Pages: 1, - Results: 1, - Page: 1, - }, - Data: []linodego.Domain{{ - Domain: "foobar.com", - ID: 1234, - }}, - }, - "POST:/domains/1234/records": linodego.APIError{ - Errors: []linodego.APIErrorReason{{ - Reason: "Failed to create domain resource", - Field: "somefield", - }}, - }, - }, - expectedError: "[400] [somefield] Failed to create domain resource", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - - server := newMockServer(test.mockResponses) - defer server.Close() - - assert.NotNil(t, p.client) - p.client.SetBaseURL(server.URL) - - err = p.Present(domain, "", keyAuth) - if len(test.expectedError) == 0 { - assert.NoError(t, err) - } else { - assert.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestDNSProvider_CleanUp(t *testing.T) { - defer envTest.RestoreEnv() - os.Setenv("LINODE_TOKEN", "testing") - - p, err := NewDNSProvider() - require.NoError(t, err) - - domain := "example.com" - keyAuth := "dGVzdGluZw==" - - testCases := []struct { - desc string - mockResponses MockResponseMap - expectedError string - }{ - { - desc: "Success", - mockResponses: MockResponseMap{ - "GET:/domains": &linodego.DomainsPagedResponse{ - PageOptions: &linodego.PageOptions{ - Pages: 1, - Results: 1, - Page: 1, - }, - Data: []linodego.Domain{{ - Domain: "foobar.com", - ID: 1234, - }}, - }, - "GET:/domains/1234/records": &linodego.DomainRecordsPagedResponse{ - PageOptions: &linodego.PageOptions{ - Pages: 1, - Results: 1, - Page: 1, - }, - Data: []linodego.DomainRecord{{ - ID: 1234, - Name: "_acme-challenge", - Target: "ElbOJKOkFWiZLQeoxf-wb3IpOsQCdvoM0y_wn0TEkxM", - Type: "TXT", - }}, - }, - "DELETE:/domains/1234/records/1234": struct{}{}, - }, - }, - { - desc: "NoDomain", - mockResponses: MockResponseMap{ - "GET:/domains": linodego.APIError{ - Errors: []linodego.APIErrorReason{{ - Reason: "Not found", - }}, - }, - "GET:/domains/1234/records": linodego.APIError{ - Errors: []linodego.APIErrorReason{{ - Reason: "Not found", - }}, - }, - }, - expectedError: "[404] Not found", - }, - { - desc: "DeleteFailed", - mockResponses: MockResponseMap{ - "GET:/domains": linodego.DomainsPagedResponse{ - PageOptions: &linodego.PageOptions{ - Pages: 1, - Results: 1, - Page: 1, - }, - Data: []linodego.Domain{{ - ID: 1234, - Domain: "example.com", - }}, - }, - "GET:/domains/1234/records": linodego.DomainRecordsPagedResponse{ - PageOptions: &linodego.PageOptions{ - Pages: 1, - Results: 1, - Page: 1, - }, - Data: []linodego.DomainRecord{{ - ID: 1234, - Name: "_acme-challenge", - Target: "ElbOJKOkFWiZLQeoxf-wb3IpOsQCdvoM0y_wn0TEkxM", - Type: "TXT", - }}, - }, - "DELETE:/domains/1234/records/1234": linodego.APIError{ - Errors: []linodego.APIErrorReason{{ - Reason: "Failed to delete domain resource", - }}, - }, - }, - expectedError: "[400] Failed to delete domain resource", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - server := newMockServer(test.mockResponses) - defer server.Close() - - p.client.SetBaseURL(server.URL) - - err = p.CleanUp(domain, "", keyAuth) - if len(test.expectedError) == 0 { - assert.NoError(t, err) - } else { - assert.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("Skipping live test") - } - // TODO implement this test -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("Skipping live test") - } - // TODO implement this test -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/client.go b/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/client.go deleted file mode 100644 index d8fc584..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/client.go +++ /dev/null @@ -1,52 +0,0 @@ -package mydnsjp - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -func (d *DNSProvider) doRequest(domain, value string, cmd string) error { - req, err := d.buildRequest(domain, value, cmd) - if err != nil { - return err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return fmt.Errorf("error querying API: %v", err) - } - - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - var content []byte - content, err = ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - return fmt.Errorf("request %s failed [status code %d]: %s", req.URL, resp.StatusCode, string(content)) - } - - return nil -} - -func (d *DNSProvider) buildRequest(domain, value string, cmd string) (*http.Request, error) { - params := url.Values{} - params.Set("CERTBOT_DOMAIN", domain) - params.Set("CERTBOT_VALIDATION", value) - params.Set("EDIT_CMD", cmd) - - req, err := http.NewRequest(http.MethodPost, defaultBaseURL, strings.NewReader(params.Encode())) - if err != nil { - return nil, fmt.Errorf("invalid request: %v", err) - } - - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetBasicAuth(d.config.MasterID, d.config.Password) - - return req, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.go b/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.go deleted file mode 100644 index 0a4bc51..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.go +++ /dev/null @@ -1,93 +0,0 @@ -// Package mydnsjp implements a DNS provider for solving the DNS-01 challenge using MyDNS.jp. -package mydnsjp - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultBaseURL = "https://www.mydns.jp/directedit.html" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - MasterID string - Password string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("MYDNSJP_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("MYDNSJP_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("MYDNSJP_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for MyDNS.jp. -// Credentials must be passed in the environment variables: MYDNSJP_MASTER_ID and MYDNSJP_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("MYDNSJP_MASTER_ID", "MYDNSJP_PASSWORD") - if err != nil { - return nil, fmt.Errorf("mydnsjp: %v", err) - } - - config := NewDefaultConfig() - config.MasterID = values["MYDNSJP_MASTER_ID"] - config.Password = values["MYDNSJP_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for MyDNS.jp. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("mydnsjp: the configuration of the DNS provider is nil") - } - - if config.MasterID == "" || config.Password == "" { - return nil, errors.New("mydnsjp: some credentials information are missing") - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - err := d.doRequest(domain, value, "REGIST") - if err != nil { - return fmt.Errorf("mydnsjp: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - err := d.doRequest(domain, value, "DELETE") - if err != nil { - return fmt.Errorf("mydnsjp: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.toml b/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.toml deleted file mode 100644 index 37b6bb8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "MyDNS.jp" -Description = '''''' -URL = "https://www.mydns.jp" -Code = "mydnsjp" -Since = "v1.2.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - MYDNSJP_MASTER_ID = "Master ID" - MYDNSJP_PASSWORD = "Password" - [Configuration.Additional] - MYDNSJP_POLLING_INTERVAL = "Time between DNS propagation check" - MYDNSJP_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - MYDNSJP_TTL = "The TTL of the TXT record used for the DNS challenge" - MYDNSJP_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.mydns.jp/?MENU=030" diff --git a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp_test.go b/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp_test.go deleted file mode 100644 index 017bd05..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package mydnsjp - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("MYDNSJP_MASTER_ID", "MYDNSJP_PASSWORD"). - WithDomain("MYDNSJP_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "MYDNSJP_MASTER_ID": "test@example.com", - "MYDNSJP_PASSWORD": "123", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "MYDNSJP_MASTER_ID": "", - "MYDNSJP_PASSWORD": "", - }, - expected: "mydnsjp: some credentials information are missing: MYDNSJP_MASTER_ID,MYDNSJP_PASSWORD", - }, - { - desc: "missing email", - envVars: map[string]string{ - "MYDNSJP_MASTER_ID": "", - "MYDNSJP_PASSWORD": "key", - }, - expected: "mydnsjp: some credentials information are missing: MYDNSJP_MASTER_ID", - }, - { - desc: "missing api key", - envVars: map[string]string{ - "MYDNSJP_MASTER_ID": "awesome@possum.com", - "MYDNSJP_PASSWORD": "", - }, - expected: "mydnsjp: some credentials information are missing: MYDNSJP_PASSWORD", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - assert.NoError(t, err) - assert.NotNil(t, p) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - masterID string - password string - expected string - }{ - { - desc: "success", - masterID: "test@example.com", - password: "123", - }, - { - desc: "missing credentials", - expected: "mydnsjp: some credentials information are missing", - }, - { - desc: "missing email", - password: "123", - expected: "mydnsjp: some credentials information are missing", - }, - { - desc: "missing api key", - masterID: "test@example.com", - expected: "mydnsjp: some credentials information are missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.MasterID = test.masterID - config.Password = test.password - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - assert.NoError(t, err) - assert.NotNil(t, p) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - assert.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - assert.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namecheap/client.go b/vendor/github.com/go-acme/lego/providers/dns/namecheap/client.go deleted file mode 100644 index 85bec85..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namecheap/client.go +++ /dev/null @@ -1,225 +0,0 @@ -package namecheap - -import ( - "encoding/xml" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -// Record describes a DNS record returned by the Namecheap DNS gethosts API. -// Namecheap uses the term "host" to refer to all DNS records that include -// a host field (A, AAAA, CNAME, NS, TXT, URL). -type Record struct { - Type string `xml:",attr"` - Name string `xml:",attr"` - Address string `xml:",attr"` - MXPref string `xml:",attr"` - TTL string `xml:",attr"` -} - -// apiError describes an error record in a namecheap API response. -type apiError struct { - Number int `xml:",attr"` - Description string `xml:",innerxml"` -} - -type setHostsResponse struct { - XMLName xml.Name `xml:"ApiResponse"` - Status string `xml:"Status,attr"` - Errors []apiError `xml:"Errors>Error"` - Result struct { - IsSuccess string `xml:",attr"` - } `xml:"CommandResponse>DomainDNSSetHostsResult"` -} - -type getHostsResponse struct { - XMLName xml.Name `xml:"ApiResponse"` - Status string `xml:"Status,attr"` - Errors []apiError `xml:"Errors>Error"` - Hosts []Record `xml:"CommandResponse>DomainDNSGetHostsResult>host"` -} - -type getTldsResponse struct { - XMLName xml.Name `xml:"ApiResponse"` - Errors []apiError `xml:"Errors>Error"` - Result []struct { - Name string `xml:",attr"` - } `xml:"CommandResponse>Tlds>Tld"` -} - -// getTLDs requests the list of available TLDs. -// https://www.namecheap.com/support/api/methods/domains/get-tld-list.aspx -func (d *DNSProvider) getTLDs() (map[string]string, error) { - request, err := d.newRequestGet("namecheap.domains.getTldList") - if err != nil { - return nil, err - } - - var gtr getTldsResponse - err = d.do(request, >r) - if err != nil { - return nil, err - } - - if len(gtr.Errors) > 0 { - return nil, fmt.Errorf("%s [%d]", gtr.Errors[0].Description, gtr.Errors[0].Number) - } - - tlds := make(map[string]string) - for _, t := range gtr.Result { - tlds[t.Name] = t.Name - } - return tlds, nil -} - -// getHosts reads the full list of DNS host records. -// https://www.namecheap.com/support/api/methods/domains-dns/get-hosts.aspx -func (d *DNSProvider) getHosts(sld, tld string) ([]Record, error) { - request, err := d.newRequestGet("namecheap.domains.dns.getHosts", - addParam("SLD", sld), - addParam("TLD", tld), - ) - if err != nil { - return nil, err - } - - var ghr getHostsResponse - err = d.do(request, &ghr) - if err != nil { - return nil, err - } - - if len(ghr.Errors) > 0 { - return nil, fmt.Errorf("%s [%d]", ghr.Errors[0].Description, ghr.Errors[0].Number) - } - - return ghr.Hosts, nil -} - -// setHosts writes the full list of DNS host records . -// https://www.namecheap.com/support/api/methods/domains-dns/set-hosts.aspx -func (d *DNSProvider) setHosts(sld, tld string, hosts []Record) error { - req, err := d.newRequestPost("namecheap.domains.dns.setHosts", - addParam("SLD", sld), - addParam("TLD", tld), - func(values url.Values) { - for i, h := range hosts { - ind := fmt.Sprintf("%d", i+1) - values.Add("HostName"+ind, h.Name) - values.Add("RecordType"+ind, h.Type) - values.Add("Address"+ind, h.Address) - values.Add("MXPref"+ind, h.MXPref) - values.Add("TTL"+ind, h.TTL) - } - }, - ) - if err != nil { - return err - } - - var shr setHostsResponse - err = d.do(req, &shr) - if err != nil { - return err - } - - if len(shr.Errors) > 0 { - return fmt.Errorf("%s [%d]", shr.Errors[0].Description, shr.Errors[0].Number) - } - if shr.Result.IsSuccess != "true" { - return fmt.Errorf("setHosts failed") - } - - return nil -} - -func (d *DNSProvider) do(req *http.Request, out interface{}) error { - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - - if resp.StatusCode >= 400 { - var body []byte - body, err = readBody(resp) - if err != nil { - return fmt.Errorf("HTTP error %d [%s]: %v", resp.StatusCode, http.StatusText(resp.StatusCode), err) - } - return fmt.Errorf("HTTP error %d [%s]: %s", resp.StatusCode, http.StatusText(resp.StatusCode), string(body)) - } - - body, err := readBody(resp) - if err != nil { - return err - } - - if err := xml.Unmarshal(body, out); err != nil { - return err - } - - return nil -} - -func (d *DNSProvider) newRequestGet(cmd string, params ...func(url.Values)) (*http.Request, error) { - query := d.makeQuery(cmd, params...) - - reqURL, err := url.Parse(d.config.BaseURL) - if err != nil { - return nil, err - } - - reqURL.RawQuery = query.Encode() - - return http.NewRequest(http.MethodGet, reqURL.String(), nil) -} - -func (d *DNSProvider) newRequestPost(cmd string, params ...func(url.Values)) (*http.Request, error) { - query := d.makeQuery(cmd, params...) - - req, err := http.NewRequest(http.MethodPost, d.config.BaseURL, strings.NewReader(query.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - return req, nil -} - -func (d *DNSProvider) makeQuery(cmd string, params ...func(url.Values)) url.Values { - queryParams := make(url.Values) - queryParams.Set("ApiUser", d.config.APIUser) - queryParams.Set("ApiKey", d.config.APIKey) - queryParams.Set("UserName", d.config.APIUser) - queryParams.Set("Command", cmd) - queryParams.Set("ClientIp", d.config.ClientIP) - - for _, param := range params { - param(queryParams) - } - - return queryParams -} - -func addParam(key, value string) func(url.Values) { - return func(values url.Values) { - values.Set(key, value) - } -} - -func readBody(resp *http.Response) ([]byte, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil") - } - - defer resp.Body.Close() - - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return rawBody, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.go b/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.go deleted file mode 100644 index 2f1290f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.go +++ /dev/null @@ -1,260 +0,0 @@ -// Package namecheap implements a DNS provider for solving the DNS-01 challenge using namecheap DNS. -package namecheap - -import ( - "errors" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Notes about namecheap's tool API: -// 1. Using the API requires registration. Once registered, use your account -// name and API key to access the API. -// 2. There is no API to add or modify a single DNS record. Instead you must -// read the entire list of records, make modifications, and then write the -// entire updated list of records. (Yuck.) -// 3. Namecheap's DNS updates can be slow to propagate. I've seen them take -// as long as an hour. -// 4. Namecheap requires you to whitelist the IP address from which you call -// its APIs. It also requires all API calls to include the whitelisted IP -// address as a form or query string value. This code uses a namecheap -// service to query the client's IP address. - -const ( - defaultBaseURL = "https://api.namecheap.com/xml.response" - getIPURL = "https://dynamicdns.park-your-domain.com/getip" -) - -// A challenge represents all the data needed to specify a dns-01 challenge -// to lets-encrypt. -type challenge struct { - domain string - key string - keyFqdn string - keyValue string - tld string - sld string - host string -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Debug bool - BaseURL string - APIUser string - APIKey string - ClientIP string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - Debug: env.GetOrDefaultBool("NAMECHEAP_DEBUG", false), - TTL: env.GetOrDefaultInt("NAMECHEAP_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NAMECHEAP_PROPAGATION_TIMEOUT", 60*time.Minute), - PollingInterval: env.GetOrDefaultSecond("NAMECHEAP_POLLING_INTERVAL", 15*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NAMECHEAP_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// DNSProvider is an implementation of the ChallengeProviderTimeout interface -// that uses Namecheap's tool API to manage TXT records for a domain. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for namecheap. -// Credentials must be passed in the environment variables: -// NAMECHEAP_API_USER and NAMECHEAP_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NAMECHEAP_API_USER", "NAMECHEAP_API_KEY") - if err != nil { - return nil, fmt.Errorf("namecheap: %v", err) - } - - config := NewDefaultConfig() - config.APIUser = values["NAMECHEAP_API_USER"] - config.APIKey = values["NAMECHEAP_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for namecheap. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("namecheap: the configuration of the DNS provider is nil") - } - - if config.APIUser == "" || config.APIKey == "" { - return nil, fmt.Errorf("namecheap: credentials missing") - } - - if len(config.ClientIP) == 0 { - clientIP, err := getClientIP(config.HTTPClient, config.Debug) - if err != nil { - return nil, fmt.Errorf("namecheap: %v", err) - } - config.ClientIP = clientIP - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Namecheap can sometimes take a long time to complete an update, so wait up to 60 minutes for the update to propagate. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present installs a TXT record for the DNS challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - tlds, err := d.getTLDs() - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - ch, err := newChallenge(domain, keyAuth, tlds) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - records, err := d.getHosts(ch.sld, ch.tld) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - record := Record{ - Name: ch.key, - Type: "TXT", - Address: ch.keyValue, - MXPref: "10", - TTL: strconv.Itoa(d.config.TTL), - } - - records = append(records, record) - - if d.config.Debug { - for _, h := range records { - log.Printf("%-5.5s %-30.30s %-6s %-70.70s", h.Type, h.Name, h.TTL, h.Address) - } - } - - err = d.setHosts(ch.sld, ch.tld, records) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - return nil -} - -// CleanUp removes a TXT record used for a previous DNS challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - tlds, err := d.getTLDs() - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - ch, err := newChallenge(domain, keyAuth, tlds) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - records, err := d.getHosts(ch.sld, ch.tld) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - // Find the challenge TXT record and remove it if found. - var found bool - var newRecords []Record - for _, h := range records { - if h.Name == ch.key && h.Type == "TXT" { - found = true - } else { - newRecords = append(newRecords, h) - } - } - - if !found { - return nil - } - - err = d.setHosts(ch.sld, ch.tld, newRecords) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - return nil -} - -// getClientIP returns the client's public IP address. -// It uses namecheap's IP discovery service to perform the lookup. -func getClientIP(client *http.Client, debug bool) (addr string, err error) { - resp, err := client.Get(getIPURL) - if err != nil { - return "", err - } - defer resp.Body.Close() - - clientIP, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - if debug { - log.Println("Client IP:", string(clientIP)) - } - return string(clientIP), nil -} - -// newChallenge builds a challenge record from a domain name, a challenge -// authentication key, and a map of available TLDs. -func newChallenge(domain, keyAuth string, tlds map[string]string) (*challenge, error) { - domain = dns01.UnFqdn(domain) - parts := strings.Split(domain, ".") - - // Find the longest matching TLD. - longest := -1 - for i := len(parts); i > 0; i-- { - t := strings.Join(parts[i-1:], ".") - if _, found := tlds[t]; found { - longest = i - 1 - } - } - if longest < 1 { - return nil, fmt.Errorf("invalid domain name %q", domain) - } - - tld := strings.Join(parts[longest:], ".") - sld := parts[longest-1] - - var host string - if longest >= 1 { - host = strings.Join(parts[:longest-1], ".") - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - - return &challenge{ - domain: domain, - key: "_acme-challenge." + host, - keyFqdn: fqdn, - keyValue: value, - tld: tld, - sld: sld, - host: host, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.toml b/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.toml deleted file mode 100644 index bb4fa8b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Namecheap" -Description = '''''' -URL = "https://www.namecheap.com" -Code = "namecheap" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - NAMECHEAP_API_USER = "API user" - NAMECHEAP_API_KEY = "API key" - [Configuration.Additional] - NAMECHEAP_POLLING_INTERVAL = "Time between DNS propagation check" - NAMECHEAP_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - NAMECHEAP_TTL = "The TTL of the TXT record used for the DNS challenge" - NAMECHEAP_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.namecheap.com/support/api/methods.aspx" diff --git a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap_test.go b/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap_test.go deleted file mode 100644 index 67a49d8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap_test.go +++ /dev/null @@ -1,390 +0,0 @@ -package namecheap - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - envTestUser = "foo" - envTestKey = "bar" - envTestClientIP = "10.0.0.1" -) - -var tldsMock = map[string]string{ - "com.au": "com.au", - "com": "com", - "co.uk": "co.uk", - "uk": "uk", - "edu": "edu", - "co.com": "co.com", - "za.com": "za.com", -} - -func TestDNSProvider_getHosts(t *testing.T) { - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - mock := httptest.NewServer(mockServer(&test, t)) - defer mock.Close() - - provider := mockDNSProvider(mock.URL) - - ch, err := newChallenge(test.domain, "", tldsMock) - require.NoError(t, err) - - hosts, err := provider.getHosts(ch.sld, ch.tld) - if test.errString != "" { - assert.EqualError(t, err, test.errString) - } else { - assert.NoError(t, err) - } - - next1: - for _, h := range hosts { - for _, th := range test.hosts { - if h == th { - continue next1 - } - } - t.Errorf("getHosts case %s unexpected record [%s:%s:%s]", test.name, h.Type, h.Name, h.Address) - } - - next2: - for _, th := range test.hosts { - for _, h := range hosts { - if h == th { - continue next2 - } - } - t.Errorf("getHosts case %s missing record [%s:%s:%s]", test.name, th.Type, th.Name, th.Address) - } - }) - } -} - -func TestDNSProvider_setHosts(t *testing.T) { - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - mock := httptest.NewServer(mockServer(&test, t)) - defer mock.Close() - - prov := mockDNSProvider(mock.URL) - - ch, err := newChallenge(test.domain, "", tldsMock) - require.NoError(t, err) - - hosts, err := prov.getHosts(ch.sld, ch.tld) - if test.errString != "" { - assert.EqualError(t, err, test.errString) - } else { - require.NoError(t, err) - } - if err != nil { - return - } - - err = prov.setHosts(ch.sld, ch.tld, hosts) - require.NoError(t, err) - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - mock := httptest.NewServer(mockServer(&test, t)) - defer mock.Close() - - prov := mockDNSProvider(mock.URL) - err := prov.Present(test.domain, "", "dummyKey") - if test.errString != "" { - assert.EqualError(t, err, "namecheap: "+test.errString) - } else { - assert.NoError(t, err) - } - }) - } -} - -func TestDNSProvider_CleanUp(t *testing.T) { - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - mock := httptest.NewServer(mockServer(&test, t)) - defer mock.Close() - - prov := mockDNSProvider(mock.URL) - err := prov.CleanUp(test.domain, "", "dummyKey") - if test.errString != "" { - assert.EqualError(t, err, "namecheap: "+test.errString) - } else { - assert.NoError(t, err) - } - }) - } -} - -func TestDomainSplit(t *testing.T) { - tests := []struct { - domain string - valid bool - tld string - sld string - host string - }{ - {domain: "a.b.c.test.co.uk", valid: true, tld: "co.uk", sld: "test", host: "a.b.c"}, - {domain: "test.co.uk", valid: true, tld: "co.uk", sld: "test"}, - {domain: "test.com", valid: true, tld: "com", sld: "test"}, - {domain: "test.co.com", valid: true, tld: "co.com", sld: "test"}, - {domain: "www.test.com.au", valid: true, tld: "com.au", sld: "test", host: "www"}, - {domain: "www.za.com", valid: true, tld: "za.com", sld: "www"}, - {}, - {domain: "a"}, - {domain: "com"}, - {domain: "co.com"}, - {domain: "co.uk"}, - {domain: "test.au"}, - {domain: "za.com"}, - {domain: "www.za"}, - {domain: "www.test.au"}, - {domain: "www.test.unk"}, - } - - for _, test := range tests { - test := test - t.Run(test.domain, func(t *testing.T) { - valid := true - ch, err := newChallenge(test.domain, "", tldsMock) - if err != nil { - valid = false - } - - if test.valid && !valid { - t.Errorf("Expected '%s' to split", test.domain) - } else if !test.valid && valid { - t.Errorf("Expected '%s' to produce error", test.domain) - } - - if test.valid && valid { - assertEq(t, "domain", ch.domain, test.domain) - assertEq(t, "tld", ch.tld, test.tld) - assertEq(t, "sld", ch.sld, test.sld) - assertEq(t, "host", ch.host, test.host) - } - }) - } -} - -func assertEq(t *testing.T, variable, got, want string) { - if got != want { - t.Errorf("Expected %s to be '%s' but got '%s'", variable, want, got) - } -} - -func assertHdr(tc *testCase, t *testing.T, values *url.Values) { - ch, _ := newChallenge(tc.domain, "", tldsMock) - - assertEq(t, "ApiUser", values.Get("ApiUser"), envTestUser) - assertEq(t, "ApiKey", values.Get("ApiKey"), envTestKey) - assertEq(t, "UserName", values.Get("UserName"), envTestUser) - assertEq(t, "ClientIp", values.Get("ClientIp"), envTestClientIP) - assertEq(t, "SLD", values.Get("SLD"), ch.sld) - assertEq(t, "TLD", values.Get("TLD"), ch.tld) -} - -func mockServer(tc *testCase, t *testing.T) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case http.MethodGet: - values := r.URL.Query() - cmd := values.Get("Command") - switch cmd { - case "namecheap.domains.dns.getHosts": - assertHdr(tc, t, &values) - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, tc.getHostsResponse) - case "namecheap.domains.getTldList": - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, responseGetTlds) - default: - t.Errorf("Unexpected GET command: %s", cmd) - } - - case http.MethodPost: - err := r.ParseForm() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - values := r.Form - cmd := values.Get("Command") - switch cmd { - case "namecheap.domains.dns.setHosts": - assertHdr(tc, t, &values) - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, tc.setHostsResponse) - default: - t.Errorf("Unexpected POST command: %s", cmd) - } - - default: - t.Errorf("Unexpected http method: %s", r.Method) - } - }) -} - -func mockDNSProvider(url string) *DNSProvider { - config := NewDefaultConfig() - config.BaseURL = url - config.APIUser = envTestUser - config.APIKey = envTestKey - config.ClientIP = envTestClientIP - config.HTTPClient = &http.Client{Timeout: 60 * time.Second} - - provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } - return provider -} - -type testCase struct { - name string - domain string - hosts []Record - errString string - getHostsResponse string - setHostsResponse string -} - -var testCases = []testCase{ - { - name: "Test:Success:1", - domain: "test.example.com", - hosts: []Record{ - {Type: "A", Name: "home", Address: "10.0.0.1", MXPref: "10", TTL: "1799"}, - {Type: "A", Name: "www", Address: "10.0.0.2", MXPref: "10", TTL: "1200"}, - {Type: "AAAA", Name: "a", Address: "::0", MXPref: "10", TTL: "1799"}, - {Type: "CNAME", Name: "*", Address: "example.com.", MXPref: "10", TTL: "1799"}, - {Type: "MXE", Name: "example.com", Address: "10.0.0.5", MXPref: "10", TTL: "1800"}, - {Type: "URL", Name: "xyz", Address: "https://google.com", MXPref: "10", TTL: "1799"}, - }, - getHostsResponse: responseGetHostsSuccess1, - setHostsResponse: responseSetHostsSuccess1, - }, - { - name: "Test:Success:2", - domain: "example.com", - hosts: []Record{ - {Type: "A", Name: "@", Address: "10.0.0.2", MXPref: "10", TTL: "1200"}, - {Type: "A", Name: "www", Address: "10.0.0.3", MXPref: "10", TTL: "60"}, - }, - getHostsResponse: responseGetHostsSuccess2, - setHostsResponse: responseSetHostsSuccess2, - }, - { - name: "Test:Error:BadApiKey:1", - domain: "test.example.com", - errString: "API Key is invalid or API access has not been enabled [1011102]", - getHostsResponse: responseGetHostsErrorBadAPIKey1, - }, -} - -const responseGetHostsSuccess1 = ` - - - - namecheap.domains.dns.getHosts - - - - - - - - - - - PHX01SBAPI01 - --5:00 - 3.338 -` - -const responseSetHostsSuccess1 = ` - - - - namecheap.domains.dns.setHosts - - - - - - PHX01SBAPI01 - --5:00 - 2.347 -` - -const responseGetHostsSuccess2 = ` - - - - namecheap.domains.dns.getHosts - - - - - - - PHX01SBAPI01 - --5:00 - 3.338 -` - -const responseSetHostsSuccess2 = ` - - - - namecheap.domains.dns.setHosts - - - - - - PHX01SBAPI01 - --5:00 - 2.347 -` - -const responseGetHostsErrorBadAPIKey1 = ` - - - API Key is invalid or API access has not been enabled - - - - PHX01SBAPI01 - --5:00 - 0 -` - -const responseGetTlds = ` - - - - namecheap.domains.getTldList - - - Most recognized top level domain - - - PHX01SBAPI01 - --5:00 - 0.004 -` diff --git a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.go b/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.go deleted file mode 100644 index 6cacbd8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.go +++ /dev/null @@ -1,170 +0,0 @@ -// Package namedotcom implements a DNS provider for solving the DNS-01 challenge using Name.com's DNS service. -package namedotcom - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/namedotcom/go/namecom" -) - -// according to https://www.name.com/api-docs/DNS#CreateRecord -const minTTL = 300 - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Username string - APIToken string - Server string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NAMECOM_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("NAMECOM_PROPAGATION_TIMEOUT", 15*time.Minute), - PollingInterval: env.GetOrDefaultSecond("NAMECOM_POLLING_INTERVAL", 20*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NAMECOM_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - client *namecom.NameCom - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for namedotcom. -// Credentials must be passed in the environment variables: -// NAMECOM_USERNAME and NAMECOM_API_TOKEN -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NAMECOM_USERNAME", "NAMECOM_API_TOKEN") - if err != nil { - return nil, fmt.Errorf("namedotcom: %v", err) - } - - config := NewDefaultConfig() - config.Username = values["NAMECOM_USERNAME"] - config.APIToken = values["NAMECOM_API_TOKEN"] - config.Server = env.GetOrFile("NAMECOM_SERVER") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for namedotcom. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("namedotcom: the configuration of the DNS provider is nil") - } - - if config.Username == "" { - return nil, fmt.Errorf("namedotcom: username is required") - } - - if config.APIToken == "" { - return nil, fmt.Errorf("namedotcom: API token is required") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("namedotcom: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client := namecom.New(config.Username, config.APIToken) - client.Client = config.HTTPClient - - if config.Server != "" { - client.Server = config.Server - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - request := &namecom.Record{ - DomainName: domain, - Host: d.extractRecordName(fqdn, domain), - Type: "TXT", - TTL: uint32(d.config.TTL), - Answer: value, - } - - _, err := d.client.CreateRecord(request) - if err != nil { - return fmt.Errorf("namedotcom: API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.getRecords(domain) - if err != nil { - return fmt.Errorf("namedotcom: %v", err) - } - - for _, rec := range records { - if rec.Fqdn == fqdn && rec.Type == "TXT" { - request := &namecom.DeleteRecordRequest{ - DomainName: domain, - ID: rec.ID, - } - _, err := d.client.DeleteRecord(request) - if err != nil { - return fmt.Errorf("namedotcom: %v", err) - } - } - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getRecords(domain string) ([]*namecom.Record, error) { - request := &namecom.ListRecordsRequest{ - DomainName: domain, - Page: 1, - } - - var records []*namecom.Record - for request.Page > 0 { - response, err := d.client.ListRecords(request) - if err != nil { - return nil, err - } - - records = append(records, response.Records...) - request.Page = response.NextPage - } - - return records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.toml b/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.toml deleted file mode 100644 index cd1beaa..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.toml +++ /dev/null @@ -1,22 +0,0 @@ -Name = "Name.com" -Description = '''''' -URL = "https://www.name.com" -Code = "namedotcom" -Since = "v0.5.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - NAMECOM_USERNAME = "Username" - NAMECOM_API_TOKEN = "API token" - [Configuration.Additional] - NAMECOM_POLLING_INTERVAL = "Time between DNS propagation check" - NAMECOM_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - NAMECOM_TTL = "The TTL of the TXT record used for the DNS challenge" - NAMECOM_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.name.com/api-docs/DNS" - GoClient = "https://github.com/namedotcom/go" - diff --git a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom_test.go b/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom_test.go deleted file mode 100644 index eb43e29..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package namedotcom - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "NAMECOM_USERNAME", - "NAMECOM_API_TOKEN"). - WithDomain("NAMEDOTCOM_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "NAMECOM_USERNAME": "A", - "NAMECOM_API_TOKEN": "B", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "NAMECOM_USERNAME": "", - "NAMECOM_API_TOKEN": "", - }, - expected: "namedotcom: some credentials information are missing: NAMECOM_USERNAME,NAMECOM_API_TOKEN", - }, - { - desc: "missing username", - envVars: map[string]string{ - "NAMECOM_USERNAME": "", - "NAMECOM_API_TOKEN": "B", - }, - expected: "namedotcom: some credentials information are missing: NAMECOM_USERNAME", - }, - { - desc: "missing api token", - envVars: map[string]string{ - "NAMECOM_USERNAME": "A", - "NAMECOM_API_TOKEN": "", - }, - expected: "namedotcom: some credentials information are missing: NAMECOM_API_TOKEN", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiToken string - username string - expected string - }{ - { - desc: "success", - apiToken: "A", - username: "B", - }, - { - desc: "missing credentials", - expected: "namedotcom: username is required", - }, - { - desc: "missing API token", - apiToken: "", - username: "B", - expected: "namedotcom: API token is required", - }, - { - desc: "missing username", - apiToken: "A", - username: "", - expected: "namedotcom: username is required", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Username = test.username - config.APIToken = test.apiToken - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client.go deleted file mode 100644 index 733bfd0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client.go +++ /dev/null @@ -1,327 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "time" -) - -// defaultBaseURL for reaching the jSON-based API-Endpoint of netcup -const defaultBaseURL = "https://ccp.netcup.net/run/webservice/servers/endpoint.php?JSON" - -// success response status -const success = "success" - -// Request wrapper as specified in netcup wiki -// needed for every request to netcup API around *Msg -// https://www.netcup-wiki.de/wiki/CCP_API#Anmerkungen_zu_JSON-Requests -type Request struct { - Action string `json:"action"` - Param interface{} `json:"param"` -} - -// LoginRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#login -type LoginRequest struct { - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APIPassword string `json:"apipassword"` - ClientRequestID string `json:"clientrequestid,omitempty"` -} - -// LogoutRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#logout -type LogoutRequest struct { - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APISessionID string `json:"apisessionid"` - ClientRequestID string `json:"clientrequestid,omitempty"` -} - -// UpdateDNSRecordsRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#updateDnsRecords -type UpdateDNSRecordsRequest struct { - DomainName string `json:"domainname"` - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APISessionID string `json:"apisessionid"` - ClientRequestID string `json:"clientrequestid,omitempty"` - DNSRecordSet DNSRecordSet `json:"dnsrecordset"` -} - -// DNSRecordSet as specified in netcup WSDL -// needed in UpdateDNSRecordsRequest -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#Dnsrecordset -type DNSRecordSet struct { - DNSRecords []DNSRecord `json:"dnsrecords"` -} - -// InfoDNSRecordsRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#infoDnsRecords -type InfoDNSRecordsRequest struct { - DomainName string `json:"domainname"` - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APISessionID string `json:"apisessionid"` - ClientRequestID string `json:"clientrequestid,omitempty"` -} - -// DNSRecord as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#Dnsrecord -type DNSRecord struct { - ID int `json:"id,string,omitempty"` - Hostname string `json:"hostname"` - RecordType string `json:"type"` - Priority string `json:"priority,omitempty"` - Destination string `json:"destination"` - DeleteRecord bool `json:"deleterecord,omitempty"` - State string `json:"state,omitempty"` - TTL int `json:"ttl,omitempty"` -} - -// ResponseMsg as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#Responsemessage -type ResponseMsg struct { - ServerRequestID string `json:"serverrequestid"` - ClientRequestID string `json:"clientrequestid,omitempty"` - Action string `json:"action"` - Status string `json:"status"` - StatusCode int `json:"statuscode"` - ShortMessage string `json:"shortmessage"` - LongMessage string `json:"longmessage"` - ResponseData json.RawMessage `json:"responsedata,omitempty"` -} - -func (r *ResponseMsg) Error() string { - return fmt.Sprintf("an error occurred during the action %s: [Status=%s, StatusCode=%d, ShortMessage=%s, LongMessage=%s]", - r.Action, r.Status, r.StatusCode, r.ShortMessage, r.LongMessage) -} - -// LoginResponse response to login action. -type LoginResponse struct { - APISessionID string `json:"apisessionid"` -} - -// InfoDNSRecordsResponse response to infoDnsRecords action. -type InfoDNSRecordsResponse struct { - APISessionID string `json:"apisessionid"` - DNSRecords []DNSRecord `json:"dnsrecords,omitempty"` -} - -// Client netcup DNS client -type Client struct { - customerNumber string - apiKey string - apiPassword string - HTTPClient *http.Client - BaseURL string -} - -// NewClient creates a netcup DNS client -func NewClient(customerNumber string, apiKey string, apiPassword string) (*Client, error) { - if customerNumber == "" || apiKey == "" || apiPassword == "" { - return nil, fmt.Errorf("credentials missing") - } - - return &Client{ - customerNumber: customerNumber, - apiKey: apiKey, - apiPassword: apiPassword, - BaseURL: defaultBaseURL, - HTTPClient: &http.Client{ - Timeout: 10 * time.Second, - }, - }, nil -} - -// Login performs the login as specified by the netcup WSDL -// returns sessionID needed to perform remaining actions -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) Login() (string, error) { - payload := &Request{ - Action: "login", - Param: &LoginRequest{ - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APIPassword: c.apiPassword, - ClientRequestID: "", - }, - } - - var responseData LoginResponse - err := c.doRequest(payload, &responseData) - if err != nil { - return "", fmt.Errorf("loging error: %v", err) - } - - return responseData.APISessionID, nil -} - -// Logout performs the logout with the supplied sessionID as specified by the netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) Logout(sessionID string) error { - payload := &Request{ - Action: "logout", - Param: &LogoutRequest{ - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APISessionID: sessionID, - ClientRequestID: "", - }, - } - - err := c.doRequest(payload, nil) - if err != nil { - return fmt.Errorf("logout error: %v", err) - } - - return nil -} - -// UpdateDNSRecord performs an update of the DNSRecords as specified by the netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) UpdateDNSRecord(sessionID, domainName string, records []DNSRecord) error { - payload := &Request{ - Action: "updateDnsRecords", - Param: UpdateDNSRecordsRequest{ - DomainName: domainName, - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APISessionID: sessionID, - ClientRequestID: "", - DNSRecordSet: DNSRecordSet{DNSRecords: records}, - }, - } - - err := c.doRequest(payload, nil) - if err != nil { - return fmt.Errorf("error when sending the request: %v", err) - } - - return nil -} - -// GetDNSRecords retrieves all dns records of an DNS-Zone as specified by the netcup WSDL -// returns an array of DNSRecords -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) GetDNSRecords(hostname, apiSessionID string) ([]DNSRecord, error) { - payload := &Request{ - Action: "infoDnsRecords", - Param: InfoDNSRecordsRequest{ - DomainName: hostname, - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APISessionID: apiSessionID, - ClientRequestID: "", - }, - } - - var responseData InfoDNSRecordsResponse - err := c.doRequest(payload, &responseData) - if err != nil { - return nil, fmt.Errorf("error when sending the request: %v", err) - } - - return responseData.DNSRecords, nil - -} - -// doRequest marshals given body to JSON, send the request to netcup API -// and returns body of response -func (c *Client) doRequest(payload interface{}, responseData interface{}) error { - body, err := json.Marshal(payload) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, c.BaseURL, bytes.NewReader(body)) - if err != nil { - return err - } - - req.Close = true - req.Header.Set("content-type", "application/json") - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return err - } - - if err = checkResponse(resp); err != nil { - return err - } - - respMsg, err := decodeResponseMsg(resp) - if err != nil { - return err - } - - if respMsg.Status != success { - return respMsg - } - - if responseData != nil { - err = json.Unmarshal(respMsg.ResponseData, responseData) - if err != nil { - return fmt.Errorf("%v: unmarshaling %T error: %v: %s", - respMsg, responseData, err, string(respMsg.ResponseData)) - } - } - - return nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode > 299 { - if resp.Body == nil { - return fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) - } - - defer resp.Body.Close() - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) - } - - return fmt.Errorf("status code=%d: %s", resp.StatusCode, string(raw)) - } - - return nil -} - -func decodeResponseMsg(resp *http.Response) (*ResponseMsg, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) - } - - defer resp.Body.Close() - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) - } - - var respMsg ResponseMsg - err = json.Unmarshal(raw, &respMsg) - if err != nil { - return nil, fmt.Errorf("unmarshaling %T error [status code=%d]: %v: %s", respMsg, resp.StatusCode, err, string(raw)) - } - - return &respMsg, nil -} - -// GetDNSRecordIdx searches a given array of DNSRecords for a given DNSRecord -// equivalence is determined by Destination and RecortType attributes -// returns index of given DNSRecord in given array of DNSRecords -func GetDNSRecordIdx(records []DNSRecord, record DNSRecord) (int, error) { - for index, element := range records { - if record.Destination == element.Destination && record.RecordType == element.RecordType { - return index, nil - } - } - return -1, fmt.Errorf("no DNS Record found") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client_test.go deleted file mode 100644 index 4182c9e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client_test.go +++ /dev/null @@ -1,611 +0,0 @@ -package internal - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strconv" - "strings" - "testing" - - "github.com/go-acme/lego/platform/tester" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "NETCUP_CUSTOMER_NUMBER", - "NETCUP_API_KEY", - "NETCUP_API_PASSWORD"). - WithDomain("NETCUP_DOMAIN") - -func setupClientTest() (*Client, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) - - client, err := NewClient("a", "b", "c") - if err != nil { - panic(err) - } - client.BaseURL = server.URL - - return client, handler, server.Close -} - -func TestGetDNSRecordIdx(t *testing.T) { - records := []DNSRecord{ - { - ID: 12345, - Hostname: "asdf", - RecordType: "TXT", - Priority: "0", - Destination: "randomtext", - DeleteRecord: false, - State: "yes", - }, - { - ID: 23456, - Hostname: "@", - RecordType: "A", - Priority: "0", - Destination: "127.0.0.1", - DeleteRecord: false, - State: "yes", - }, - { - ID: 34567, - Hostname: "dfgh", - RecordType: "CNAME", - Priority: "0", - Destination: "example.com", - DeleteRecord: false, - State: "yes", - }, - { - ID: 45678, - Hostname: "fghj", - RecordType: "MX", - Priority: "10", - Destination: "mail.example.com", - DeleteRecord: false, - State: "yes", - }, - } - - testCases := []struct { - desc string - record DNSRecord - expectError bool - }{ - { - desc: "simple", - record: DNSRecord{ - ID: 12345, - Hostname: "asdf", - RecordType: "TXT", - Priority: "0", - Destination: "randomtext", - DeleteRecord: false, - State: "yes", - }, - }, - { - desc: "wrong Destination", - record: DNSRecord{ - ID: 12345, - Hostname: "asdf", - RecordType: "TXT", - Priority: "0", - Destination: "wrong", - DeleteRecord: false, - State: "yes", - }, - expectError: true, - }, - { - desc: "record type CNAME", - record: DNSRecord{ - ID: 12345, - Hostname: "asdf", - RecordType: "CNAME", - Priority: "0", - Destination: "randomtext", - DeleteRecord: false, - State: "yes", - }, - expectError: true, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - idx, err := GetDNSRecordIdx(records, test.record) - if test.expectError { - assert.Error(t, err) - assert.Equal(t, -1, idx) - } else { - assert.NoError(t, err) - assert.Equal(t, records[idx], test.record) - } - }) - } -} - -func TestClient_Login(t *testing.T) { - client, mux, tearDown := setupClientTest() - defer tearDown() - - mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { - raw, err := ioutil.ReadAll(req.Body) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - - if string(raw) != `{"action":"login","param":{"customernumber":"a","apikey":"b","apipassword":"c"}}` { - http.Error(rw, fmt.Sprintf("invalid request body: %s", string(raw)), http.StatusBadRequest) - } - - response := ` - { - "serverrequestid": "srv-request-id", - "clientrequestid": "", - "action": "login", - "status": "success", - "statuscode": 2000, - "shortmessage": "Login successful", - "longmessage": "Session has been created successful.", - "responsedata": { - "apisessionid": "api-session-id" - } - } - ` - _, err = rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }) - - sessionID, err := client.Login() - require.NoError(t, err) - - assert.Equal(t, "api-session-id", sessionID) -} - -func TestClient_Login_errors(t *testing.T) { - testCases := []struct { - desc string - handler func(rw http.ResponseWriter, req *http.Request) - }{ - { - desc: "HTTP error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - http.Error(rw, "error message", http.StatusInternalServerError) - }, - }, - { - desc: "API error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - response := ` - { - "serverrequestid":"YxTr4EzdbJ101T211zR4yzUEMVE", - "clientrequestid":"", - "action":"login", - "status":"error", - "statuscode":4013, - "shortmessage":"Validation Error.", - "longmessage":"Message is empty.", - "responsedata":"" - }` - _, err := rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }, - }, - { - desc: "responsedata marshaling error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - response := ` - { - "serverrequestid": "srv-request-id", - "clientrequestid": "", - "action": "login", - "status": "success", - "statuscode": 2000, - "shortmessage": "Login successful", - "longmessage": "Session has been created successful.", - "responsedata": "" - }` - _, err := rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - client, mux, tearDown := setupClientTest() - defer tearDown() - - mux.HandleFunc("/", test.handler) - - sessionID, err := client.Login() - assert.Error(t, err) - assert.Equal(t, "", sessionID) - }) - } -} - -func TestClient_Logout(t *testing.T) { - client, mux, tearDown := setupClientTest() - defer tearDown() - - mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { - raw, err := ioutil.ReadAll(req.Body) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - - if string(raw) != `{"action":"logout","param":{"customernumber":"a","apikey":"b","apisessionid":"session-id"}}` { - http.Error(rw, fmt.Sprintf("invalid request body: %s", string(raw)), http.StatusBadRequest) - } - - response := ` - { - "serverrequestid": "request-id", - "clientrequestid": "", - "action": "logout", - "status": "success", - "statuscode": 2000, - "shortmessage": "Logout successful", - "longmessage": "Session has been terminated successful.", - "responsedata": "" - }` - _, err = rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }) - - err := client.Logout("session-id") - require.NoError(t, err) -} - -func TestClient_Logout_errors(t *testing.T) { - testCases := []struct { - desc string - handler func(rw http.ResponseWriter, req *http.Request) - }{ - { - desc: "HTTP error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - http.Error(rw, "error message", http.StatusInternalServerError) - }, - }, - { - desc: "API error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - response := ` - { - "serverrequestid":"YxTr4EzdbJ101T211zR4yzUEMVE", - "clientrequestid":"", - "action":"logout", - "status":"error", - "statuscode":4013, - "shortmessage":"Validation Error.", - "longmessage":"Message is empty.", - "responsedata":"" - }` - _, err := rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - client, mux, tearDown := setupClientTest() - defer tearDown() - - mux.HandleFunc("/", test.handler) - - err := client.Logout("session-id") - require.Error(t, err) - }) - } -} - -func TestClient_GetDNSRecords(t *testing.T) { - client, mux, tearDown := setupClientTest() - defer tearDown() - - mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { - raw, err := ioutil.ReadAll(req.Body) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - - if string(raw) != `{"action":"infoDnsRecords","param":{"domainname":"example.com","customernumber":"a","apikey":"b","apisessionid":"api-session-id"}}` { - http.Error(rw, fmt.Sprintf("invalid request body: %s", string(raw)), http.StatusBadRequest) - } - - response := ` - { - "serverrequestid":"srv-request-id", - "clientrequestid":"", - "action":"infoDnsRecords", - "status":"success", - "statuscode":2000, - "shortmessage":"Login successful", - "longmessage":"Session has been created successful.", - "responsedata":{ - "apisessionid":"api-session-id", - "dnsrecords":[ - { - "id":"1", - "hostname":"example.com", - "type":"TXT", - "priority":"1", - "destination":"bGVnbzE=", - "state":"yes", - "ttl":300 - }, - { - "id":"2", - "hostname":"example2.com", - "type":"TXT", - "priority":"1", - "destination":"bGVnbw==", - "state":"yes", - "ttl":300 - } - ] - } - }` - _, err = rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }) - - expected := []DNSRecord{{ - ID: 1, - Hostname: "example.com", - RecordType: "TXT", - Priority: "1", - Destination: "bGVnbzE=", - DeleteRecord: false, - State: "yes", - TTL: 300, - }, { - ID: 2, - Hostname: "example2.com", - RecordType: "TXT", - Priority: "1", - Destination: "bGVnbw==", - DeleteRecord: false, - State: "yes", - TTL: 300, - }} - - records, err := client.GetDNSRecords("example.com", "api-session-id") - require.NoError(t, err) - - assert.Equal(t, expected, records) -} - -func TestClient_GetDNSRecords_errors(t *testing.T) { - testCases := []struct { - desc string - handler func(rw http.ResponseWriter, req *http.Request) - }{ - { - desc: "HTTP error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - http.Error(rw, "error message", http.StatusInternalServerError) - }, - }, - { - desc: "API error", - handler: func(rw http.ResponseWriter, _ *http.Request) { - response := ` - { - "serverrequestid":"YxTr4EzdbJ101T211zR4yzUEMVE", - "clientrequestid":"", - "action":"infoDnsRecords", - "status":"error", - "statuscode":4013, - "shortmessage":"Validation Error.", - "longmessage":"Message is empty.", - "responsedata":"" - }` - _, err := rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }, - }, - { - desc: "responsedata marshaling error", - handler: func(rw http.ResponseWriter, req *http.Request) { - raw, err := ioutil.ReadAll(req.Body) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - - if string(raw) != `{"action":"infoDnsRecords","param":{"domainname":"example.com","customernumber":"a","apikey":"b","apisessionid":"api-session-id"}}` { - http.Error(rw, fmt.Sprintf("invalid request body: %s", string(raw)), http.StatusBadRequest) - } - - response := ` - { - "serverrequestid":"srv-request-id", - "clientrequestid":"", - "action":"infoDnsRecords", - "status":"success", - "statuscode":2000, - "shortmessage":"Login successful", - "longmessage":"Session has been created successful.", - "responsedata":"" - }` - _, err = rw.Write([]byte(response)) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - client, mux, tearDown := setupClientTest() - defer tearDown() - - mux.HandleFunc("/", test.handler) - - records, err := client.GetDNSRecords("example.com", "api-session-id") - require.Error(t, err) - assert.Empty(t, records) - }) - } -} - -func TestLiveClientAuth(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - // Setup - envTest.RestoreEnv() - - client, err := NewClient( - envTest.GetValue("NETCUP_CUSTOMER_NUMBER"), - envTest.GetValue("NETCUP_API_KEY"), - envTest.GetValue("NETCUP_API_PASSWORD")) - require.NoError(t, err) - - for i := 1; i < 4; i++ { - i := i - t.Run("Test_"+strconv.Itoa(i), func(t *testing.T) { - t.Parallel() - - sessionID, err := client.Login() - require.NoError(t, err) - - err = client.Logout(sessionID) - require.NoError(t, err) - }) - } - -} - -func TestLiveClientGetDnsRecords(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - // Setup - envTest.RestoreEnv() - - client, err := NewClient( - envTest.GetValue("NETCUP_CUSTOMER_NUMBER"), - envTest.GetValue("NETCUP_API_KEY"), - envTest.GetValue("NETCUP_API_PASSWORD")) - require.NoError(t, err) - - sessionID, err := client.Login() - require.NoError(t, err) - - fqdn, _ := dns01.GetRecord(envTest.GetDomain(), "123d==") - - zone, err := dns01.FindZoneByFqdn(fqdn) - require.NoError(t, err, "error finding DNSZone") - - zone = dns01.UnFqdn(zone) - - // TestMethod - _, err = client.GetDNSRecords(zone, sessionID) - require.NoError(t, err) - - // Tear down - err = client.Logout(sessionID) - require.NoError(t, err) -} - -func TestLiveClientUpdateDnsRecord(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - // Setup - envTest.RestoreEnv() - - client, err := NewClient( - envTest.GetValue("NETCUP_CUSTOMER_NUMBER"), - envTest.GetValue("NETCUP_API_KEY"), - envTest.GetValue("NETCUP_API_PASSWORD")) - require.NoError(t, err) - - sessionID, err := client.Login() - require.NoError(t, err) - - fqdn, _ := dns01.GetRecord(envTest.GetDomain(), "123d==") - - zone, err := dns01.FindZoneByFqdn(fqdn) - require.NoError(t, err, fmt.Errorf("error finding DNSZone, %v", err)) - - hostname := strings.Replace(fqdn, "."+zone, "", 1) - - record := DNSRecord{ - Hostname: hostname, - RecordType: "TXT", - Destination: "asdf5678", - DeleteRecord: false, - TTL: 120, - } - - // test - zone = dns01.UnFqdn(zone) - - err = client.UpdateDNSRecord(sessionID, zone, []DNSRecord{record}) - require.NoError(t, err) - - records, err := client.GetDNSRecords(zone, sessionID) - require.NoError(t, err) - - recordIdx, err := GetDNSRecordIdx(records, record) - require.NoError(t, err) - - assert.Equal(t, record.Hostname, records[recordIdx].Hostname) - assert.Equal(t, record.RecordType, records[recordIdx].RecordType) - assert.Equal(t, record.Destination, records[recordIdx].Destination) - assert.Equal(t, record.DeleteRecord, records[recordIdx].DeleteRecord) - - records[recordIdx].DeleteRecord = true - - // Tear down - err = client.UpdateDNSRecord(sessionID, envTest.GetDomain(), []DNSRecord{records[recordIdx]}) - require.NoError(t, err, "Did not remove record! Please do so yourself.") - - err = client.Logout(sessionID) - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.go b/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.go deleted file mode 100644 index 003dcbb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.go +++ /dev/null @@ -1,182 +0,0 @@ -// Package netcup implements a DNS Provider for solving the DNS-01 challenge using the netcup DNS API. -package netcup - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/providers/dns/netcup/internal" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Key string - Password string - Customer string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NETCUP_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NETCUP_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("NETCUP_POLLING_INTERVAL", 5*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NETCUP_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - client *internal.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for netcup. -// Credentials must be passed in the environment variables: -// NETCUP_CUSTOMER_NUMBER, NETCUP_API_KEY, NETCUP_API_PASSWORD -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NETCUP_CUSTOMER_NUMBER", "NETCUP_API_KEY", "NETCUP_API_PASSWORD") - if err != nil { - return nil, fmt.Errorf("netcup: %v", err) - } - - config := NewDefaultConfig() - config.Customer = values["NETCUP_CUSTOMER_NUMBER"] - config.Key = values["NETCUP_API_KEY"] - config.Password = values["NETCUP_API_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for netcup. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("netcup: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.Customer, config.Key, config.Password) - if err != nil { - return nil, fmt.Errorf("netcup: %v", err) - } - - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domainName, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domainName, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("netcup: failed to find DNSZone, %v", err) - } - - sessionID, err := d.client.Login() - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - defer func() { - err = d.client.Logout(sessionID) - if err != nil { - log.Print("netcup: %v", err) - } - }() - - hostname := strings.Replace(fqdn, "."+zone, "", 1) - record := internal.DNSRecord{ - Hostname: hostname, - RecordType: "TXT", - Destination: value, - TTL: d.config.TTL, - } - - zone = dns01.UnFqdn(zone) - - records, err := d.client.GetDNSRecords(zone, sessionID) - if err != nil { - // skip no existing records - log.Infof("no existing records, error ignored: %v", err) - } - - records = append(records, record) - - err = d.client.UpdateDNSRecord(sessionID, zone, records) - if err != nil { - return fmt.Errorf("netcup: failed to add TXT-Record: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domainName, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domainName, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("netcup: failed to find DNSZone, %v", err) - } - - sessionID, err := d.client.Login() - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - defer func() { - err = d.client.Logout(sessionID) - if err != nil { - log.Print("netcup: %v", err) - } - }() - - hostname := strings.Replace(fqdn, "."+zone, "", 1) - - zone = dns01.UnFqdn(zone) - - records, err := d.client.GetDNSRecords(zone, sessionID) - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - record := internal.DNSRecord{ - Hostname: hostname, - RecordType: "TXT", - Destination: value, - } - - idx, err := internal.GetDNSRecordIdx(records, record) - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - records[idx].DeleteRecord = true - - err = d.client.UpdateDNSRecord(sessionID, zone, []internal.DNSRecord{records[idx]}) - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.toml b/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.toml deleted file mode 100644 index 992e868..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Netcup" -Description = '''''' -URL = "https://www.netcup.eu/" -Code = "netcup" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - NETCUP_CUSTOMER_NUMBER = "Customer number" - NETCUP_API_KEY = "API key" - NETCUP_API_PASSWORD = "API password" - [Configuration.Additional] - NETCUP_POLLING_INTERVAL = "Time between DNS propagation check" - NETCUP_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - NETCUP_TTL = "The TTL of the TXT record used for the DNS challenge" - NETCUP_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.netcup-wiki.de/wiki/DNS_API" diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup_test.go b/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup_test.go deleted file mode 100644 index f172423..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package netcup - -import ( - "fmt" - "testing" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "NETCUP_CUSTOMER_NUMBER", - "NETCUP_API_KEY", - "NETCUP_API_PASSWORD"). - WithDomain("NETCUP_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "NETCUP_CUSTOMER_NUMBER": "A", - "NETCUP_API_KEY": "B", - "NETCUP_API_PASSWORD": "C", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "NETCUP_CUSTOMER_NUMBER": "", - "NETCUP_API_KEY": "", - "NETCUP_API_PASSWORD": "", - }, - expected: "netcup: some credentials information are missing: NETCUP_CUSTOMER_NUMBER,NETCUP_API_KEY,NETCUP_API_PASSWORD", - }, - { - desc: "missing customer number", - envVars: map[string]string{ - "NETCUP_CUSTOMER_NUMBER": "", - "NETCUP_API_KEY": "B", - "NETCUP_API_PASSWORD": "C", - }, - expected: "netcup: some credentials information are missing: NETCUP_CUSTOMER_NUMBER", - }, - { - desc: "missing API key", - envVars: map[string]string{ - "NETCUP_CUSTOMER_NUMBER": "A", - "NETCUP_API_KEY": "", - "NETCUP_API_PASSWORD": "C", - }, - expected: "netcup: some credentials information are missing: NETCUP_API_KEY", - }, - { - desc: "missing api password", - envVars: map[string]string{ - "NETCUP_CUSTOMER_NUMBER": "A", - "NETCUP_API_KEY": "B", - "NETCUP_API_PASSWORD": "", - }, - expected: "netcup: some credentials information are missing: NETCUP_API_PASSWORD", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - customer string - key string - password string - expected string - }{ - { - desc: "success", - customer: "A", - key: "B", - password: "C", - }, - { - desc: "missing credentials", - expected: "netcup: credentials missing", - }, - { - desc: "missing customer", - customer: "", - key: "B", - password: "C", - expected: "netcup: credentials missing", - }, - { - desc: "missing key", - customer: "A", - key: "", - password: "C", - expected: "netcup: credentials missing", - }, - { - desc: "missing password", - customer: "A", - key: "B", - password: "", - expected: "netcup: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Customer = test.customer - config.Key = test.key - config.Password = test.password - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresentAndCleanup(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - p, err := NewDNSProvider() - require.NoError(t, err) - - fqdn, _ := dns01.GetRecord(envTest.GetDomain(), "123d==") - - zone, err := dns01.FindZoneByFqdn(fqdn) - require.NoError(t, err, "error finding DNSZone") - - zone = dns01.UnFqdn(zone) - - testCases := []string{ - zone, - "sub." + zone, - "*." + zone, - "*.sub." + zone, - } - - for _, test := range testCases { - t.Run(fmt.Sprintf("domain(%s)", test), func(t *testing.T) { - err = p.Present(test, "987d", "123d==") - require.NoError(t, err) - - err = p.CleanUp(test, "987d", "123d==") - require.NoError(t, err, "Did not clean up! Please remove record yourself.") - }) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client.go deleted file mode 100644 index a2eb8a7..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client.go +++ /dev/null @@ -1,234 +0,0 @@ -package internal - -import ( - "bytes" - "crypto/hmac" - "crypto/sha1" - "encoding/base64" - "encoding/xml" - "errors" - "fmt" - "net/http" - "time" -) - -const ( - defaultBaseURL = "https://dns.api.nifcloud.com" - apiVersion = "2012-12-12N2013-12-16" - // XMLNs XML NS of Route53 - XMLNs = "https://route53.amazonaws.com/doc/2012-12-12/" -) - -// ChangeResourceRecordSetsRequest is a complex type that contains change information for the resource record set. -type ChangeResourceRecordSetsRequest struct { - XMLNs string `xml:"xmlns,attr"` - ChangeBatch ChangeBatch `xml:"ChangeBatch"` -} - -// ChangeResourceRecordSetsResponse is a complex type containing the response for the request. -type ChangeResourceRecordSetsResponse struct { - ChangeInfo ChangeInfo `xml:"ChangeInfo"` -} - -// GetChangeResponse is a complex type that contains the ChangeInfo element. -type GetChangeResponse struct { - ChangeInfo ChangeInfo `xml:"ChangeInfo"` -} - -// ErrorResponse is the information for any errors. -type ErrorResponse struct { - Error struct { - Type string `xml:"Type"` - Message string `xml:"Message"` - Code string `xml:"Code"` - } `xml:"Error"` - RequestID string `xml:"RequestId"` -} - -// ChangeBatch is the information for a change request. -type ChangeBatch struct { - Changes Changes `xml:"Changes"` - Comment string `xml:"Comment"` -} - -// Changes is array of Change. -type Changes struct { - Change []Change `xml:"Change"` -} - -// Change is the information for each resource record set that you want to change. -type Change struct { - Action string `xml:"Action"` - ResourceRecordSet ResourceRecordSet `xml:"ResourceRecordSet"` -} - -// ResourceRecordSet is the information about the resource record set to create or delete. -type ResourceRecordSet struct { - Name string `xml:"Name"` - Type string `xml:"Type"` - TTL int `xml:"TTL"` - ResourceRecords ResourceRecords `xml:"ResourceRecords"` -} - -// ResourceRecords is array of ResourceRecord. -type ResourceRecords struct { - ResourceRecord []ResourceRecord `xml:"ResourceRecord"` -} - -// ResourceRecord is the information specific to the resource record. -type ResourceRecord struct { - Value string `xml:"Value"` -} - -// ChangeInfo is A complex type that describes change information about changes made to your hosted zone. -type ChangeInfo struct { - ID string `xml:"Id"` - Status string `xml:"Status"` - SubmittedAt string `xml:"SubmittedAt"` -} - -// NewClient Creates a new client of NIFCLOUD DNS -func NewClient(accessKey string, secretKey string) (*Client, error) { - if len(accessKey) == 0 || len(secretKey) == 0 { - return nil, errors.New("credentials missing") - } - - return &Client{ - accessKey: accessKey, - secretKey: secretKey, - BaseURL: defaultBaseURL, - HTTPClient: &http.Client{}, - }, nil -} - -// Client client of NIFCLOUD DNS -type Client struct { - accessKey string - secretKey string - BaseURL string - HTTPClient *http.Client -} - -// ChangeResourceRecordSets Call ChangeResourceRecordSets API and return response. -func (c *Client) ChangeResourceRecordSets(hostedZoneID string, input ChangeResourceRecordSetsRequest) (*ChangeResourceRecordSetsResponse, error) { - requestURL := fmt.Sprintf("%s/%s/hostedzone/%s/rrset", c.BaseURL, apiVersion, hostedZoneID) - - body := &bytes.Buffer{} - body.Write([]byte(xml.Header)) - err := xml.NewEncoder(body).Encode(input) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(http.MethodPost, requestURL, body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "text/xml; charset=utf-8") - - err = c.sign(req) - if err != nil { - return nil, fmt.Errorf("an error occurred during the creation of the signature: %v", err) - } - - res, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - if res.Body == nil { - return nil, errors.New("the response body is nil") - } - - defer res.Body.Close() - - if res.StatusCode != http.StatusOK { - errResp := &ErrorResponse{} - err = xml.NewDecoder(res.Body).Decode(errResp) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the error body to XML: %v", err) - } - - return nil, fmt.Errorf("an error occurred: %s", errResp.Error.Message) - } - - output := &ChangeResourceRecordSetsResponse{} - err = xml.NewDecoder(res.Body).Decode(output) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the response body to XML: %v", err) - } - - return output, err -} - -// GetChange Call GetChange API and return response. -func (c *Client) GetChange(statusID string) (*GetChangeResponse, error) { - requestURL := fmt.Sprintf("%s/%s/change/%s", c.BaseURL, apiVersion, statusID) - - req, err := http.NewRequest(http.MethodGet, requestURL, nil) - if err != nil { - return nil, err - } - - err = c.sign(req) - if err != nil { - return nil, fmt.Errorf("an error occurred during the creation of the signature: %v", err) - } - - res, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - if res.Body == nil { - return nil, errors.New("the response body is nil") - } - - defer res.Body.Close() - - if res.StatusCode != http.StatusOK { - errResp := &ErrorResponse{} - err = xml.NewDecoder(res.Body).Decode(errResp) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the error body to XML: %v", err) - } - - return nil, fmt.Errorf("an error occurred: %s", errResp.Error.Message) - } - - output := &GetChangeResponse{} - err = xml.NewDecoder(res.Body).Decode(output) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the response body to XML: %v", err) - } - - return output, nil -} - -func (c *Client) sign(req *http.Request) error { - if req.Header.Get("Date") == "" { - location, err := time.LoadLocation("GMT") - if err != nil { - return err - } - - req.Header.Set("Date", time.Now().In(location).Format(time.RFC1123)) - } - - if req.URL.Path == "" { - req.URL.Path += "/" - } - - mac := hmac.New(sha1.New, []byte(c.secretKey)) - _, err := mac.Write([]byte(req.Header.Get("Date"))) - if err != nil { - return err - } - - hashed := mac.Sum(nil) - signature := base64.StdEncoding.EncodeToString(hashed) - - auth := fmt.Sprintf("NIFTY3-HTTPS NiftyAccessKeyId=%s,Algorithm=HmacSHA1,Signature=%s", c.accessKey, signature) - req.Header.Set("X-Nifty-Authorization", auth) - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client_test.go deleted file mode 100644 index b9cec1b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client_test.go +++ /dev/null @@ -1,179 +0,0 @@ -package internal - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func runTestServer(responseBody string, statusCode int) *httptest.Server { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(statusCode) - fmt.Fprintln(w, responseBody) - })) - return server -} - -func TestChangeResourceRecordSets(t *testing.T) { - responseBody := ` - - - xxxxx - INSYNC - 2015-08-05T00:00:00.000Z - - -` - server := runTestServer(responseBody, http.StatusOK) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL - - res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) - require.NoError(t, err) - assert.Equal(t, "xxxxx", res.ChangeInfo.ID) - assert.Equal(t, "INSYNC", res.ChangeInfo.Status) - assert.Equal(t, "2015-08-05T00:00:00.000Z", res.ChangeInfo.SubmittedAt) -} - -func TestChangeResourceRecordSetsErrors(t *testing.T) { - testCases := []struct { - desc string - responseBody string - statusCode int - expected string - }{ - { - desc: "API error", - responseBody: ` - - - Sender - AuthFailed - The request signature we calculated does not match the signature you provided. - - -`, - statusCode: http.StatusUnauthorized, - expected: "an error occurred: The request signature we calculated does not match the signature you provided.", - }, - { - desc: "response body error", - responseBody: "foo", - statusCode: http.StatusOK, - expected: "an error occurred while unmarshaling the response body to XML: EOF", - }, - { - desc: "error message error", - responseBody: "foo", - statusCode: http.StatusInternalServerError, - expected: "an error occurred while unmarshaling the error body to XML: EOF", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - - server := runTestServer(test.responseBody, test.statusCode) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL - - res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) - assert.Nil(t, res) - assert.EqualError(t, err, test.expected) - }) - } -} - -func TestGetChange(t *testing.T) { - responseBody := ` - - - xxxxx - INSYNC - 2015-08-05T00:00:00.000Z - - -` - - server := runTestServer(responseBody, http.StatusOK) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL - - res, err := client.GetChange("12345") - require.NoError(t, err) - assert.Equal(t, "xxxxx", res.ChangeInfo.ID) - assert.Equal(t, "INSYNC", res.ChangeInfo.Status) - assert.Equal(t, "2015-08-05T00:00:00.000Z", res.ChangeInfo.SubmittedAt) -} - -func TestGetChangeErrors(t *testing.T) { - testCases := []struct { - desc string - responseBody string - statusCode int - expected string - }{ - { - desc: "API error", - responseBody: ` - - - Sender - AuthFailed - The request signature we calculated does not match the signature you provided. - - -`, - statusCode: http.StatusUnauthorized, - expected: "an error occurred: The request signature we calculated does not match the signature you provided.", - }, - { - desc: "response body error", - responseBody: "foo", - statusCode: http.StatusOK, - expected: "an error occurred while unmarshaling the response body to XML: EOF", - }, - { - desc: "error message error", - responseBody: "foo", - statusCode: http.StatusInternalServerError, - expected: "an error occurred while unmarshaling the error body to XML: EOF", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - - server := runTestServer(test.responseBody, test.statusCode) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL - - res, err := client.GetChange("12345") - assert.Nil(t, res) - assert.EqualError(t, err, test.expected) - }) - } - -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.go b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.go deleted file mode 100644 index ed1d7ec..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.go +++ /dev/null @@ -1,156 +0,0 @@ -// Package nifcloud implements a DNS provider for solving the DNS-01 challenge using NIFCLOUD DNS. -package nifcloud - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/providers/dns/nifcloud/internal" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/platform/wait" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - AccessKey string - SecretKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NIFCLOUD_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NIFCLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("NIFCLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NIFCLOUD_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - client *internal.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for the NIFCLOUD DNS service. -// Credentials must be passed in the environment variables: -// NIFCLOUD_ACCESS_KEY_ID and NIFCLOUD_SECRET_ACCESS_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NIFCLOUD_ACCESS_KEY_ID", "NIFCLOUD_SECRET_ACCESS_KEY") - if err != nil { - return nil, fmt.Errorf("nifcloud: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = env.GetOrFile("NIFCLOUD_DNS_ENDPOINT") - config.AccessKey = values["NIFCLOUD_ACCESS_KEY_ID"] - config.SecretKey = values["NIFCLOUD_SECRET_ACCESS_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for NIFCLOUD. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("nifcloud: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.AccessKey, config.SecretKey) - if err != nil { - return nil, fmt.Errorf("nifcloud: %v", err) - } - - if config.HTTPClient != nil { - client.HTTPClient = config.HTTPClient - } - - if len(config.BaseURL) > 0 { - client.BaseURL = config.BaseURL - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("CREATE", fqdn, value, domain, d.config.TTL) - if err != nil { - return fmt.Errorf("nifcloud: %v", err) - } - return err -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("DELETE", fqdn, value, domain, d.config.TTL) - if err != nil { - return fmt.Errorf("nifcloud: %v", err) - } - return err -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) changeRecord(action, fqdn, value, domain string, ttl int) error { - name := dns01.UnFqdn(fqdn) - - reqParams := internal.ChangeResourceRecordSetsRequest{ - XMLNs: internal.XMLNs, - ChangeBatch: internal.ChangeBatch{ - Comment: "Managed by Lego", - Changes: internal.Changes{ - Change: []internal.Change{ - { - Action: action, - ResourceRecordSet: internal.ResourceRecordSet{ - Name: name, - Type: "TXT", - TTL: ttl, - ResourceRecords: internal.ResourceRecords{ - ResourceRecord: []internal.ResourceRecord{ - { - Value: value, - }, - }, - }, - }, - }, - }, - }, - }, - } - - resp, err := d.client.ChangeResourceRecordSets(domain, reqParams) - if err != nil { - return fmt.Errorf("failed to change NIFCLOUD record set: %v", err) - } - - statusID := resp.ChangeInfo.ID - - return wait.For("nifcloud", 120*time.Second, 4*time.Second, func() (bool, error) { - resp, err := d.client.GetChange(statusID) - if err != nil { - return false, fmt.Errorf("failed to query NIFCLOUD DNS change status: %v", err) - } - return resp.ChangeInfo.Status == "INSYNC", nil - }) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.toml b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.toml deleted file mode 100644 index 9394cc8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "NIFCloud" -Description = '''''' -URL = "https://www.nifcloud.com/" -Code = "nifcloud" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - NIFCLOUD_ACCESS_KEY_ID = "Access key" - NIFCLOUD_SECRET_ACCESS_KEY = "Secret access key" - [Configuration.Additional] - NIFCLOUD_POLLING_INTERVAL = "Time between DNS propagation check" - NIFCLOUD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - NIFCLOUD_TTL = "The TTL of the TXT record used for the DNS challenge" - NIFCLOUD_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://mbaas.nifcloud.com/doc/current/rest/common/format.html" diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud_test.go b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud_test.go deleted file mode 100644 index e4ee7ed..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package nifcloud - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "NIFCLOUD_ACCESS_KEY_ID", - "NIFCLOUD_SECRET_ACCESS_KEY"). - WithDomain("NIFCLOUD_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "NIFCLOUD_ACCESS_KEY_ID": "123", - "NIFCLOUD_SECRET_ACCESS_KEY": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "NIFCLOUD_ACCESS_KEY_ID": "", - "NIFCLOUD_SECRET_ACCESS_KEY": "", - }, - expected: "nifcloud: some credentials information are missing: NIFCLOUD_ACCESS_KEY_ID,NIFCLOUD_SECRET_ACCESS_KEY", - }, - { - desc: "missing access key", - envVars: map[string]string{ - "NIFCLOUD_ACCESS_KEY_ID": "", - "NIFCLOUD_SECRET_ACCESS_KEY": "456", - }, - expected: "nifcloud: some credentials information are missing: NIFCLOUD_ACCESS_KEY_ID", - }, - { - desc: "missing secret key", - envVars: map[string]string{ - "NIFCLOUD_ACCESS_KEY_ID": "123", - "NIFCLOUD_SECRET_ACCESS_KEY": "", - }, - expected: "nifcloud: some credentials information are missing: NIFCLOUD_SECRET_ACCESS_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - accessKey string - secretKey string - expected string - }{ - { - desc: "success", - accessKey: "123", - secretKey: "456", - }, - { - desc: "missing credentials", - expected: "nifcloud: credentials missing", - }, - { - desc: "missing api key", - secretKey: "456", - expected: "nifcloud: credentials missing", - }, - { - desc: "missing secret key", - accessKey: "123", - expected: "nifcloud: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.AccessKey = test.accessKey - config.SecretKey = test.secretKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.go b/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.go deleted file mode 100644 index 9ecc438..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.go +++ /dev/null @@ -1,162 +0,0 @@ -// Package ns1 implements a DNS provider for solving the DNS-01 challenge using NS1 DNS. -package ns1 - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "gopkg.in/ns1/ns1-go.v2/rest" - "gopkg.in/ns1/ns1-go.v2/rest/model/dns" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NS1_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NS1_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("NS1_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NS1_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - client *rest.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for NS1. -// Credentials must be passed in the environment variables: NS1_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NS1_API_KEY") - if err != nil { - return nil, fmt.Errorf("ns1: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["NS1_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for NS1. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("ns1: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("ns1: credentials missing") - } - - client := rest.NewClient(config.HTTPClient, rest.SetAPIKey(config.APIKey)) - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("ns1: %v", err) - } - - record, _, err := d.client.Records.Get(zone.Zone, dns01.UnFqdn(fqdn), "TXT") - - // Create a new record - if err == rest.ErrRecordMissing || record == nil { - log.Infof("Create a new record for [zone: %s, fqdn: %s, domain: %s]", zone.Zone, fqdn) - - record = dns.NewRecord(zone.Zone, dns01.UnFqdn(fqdn), "TXT") - record.TTL = d.config.TTL - record.Answers = []*dns.Answer{{Rdata: []string{value}}} - - _, err = d.client.Records.Create(record) - if err != nil { - return fmt.Errorf("ns1: failed to create record [zone: %q, fqdn: %q]: %v", zone.Zone, fqdn, err) - } - - return nil - } - - if err != nil { - return fmt.Errorf("ns1: failed to get the existing record: %v", err) - } - - // Update the existing records - record.Answers = append(record.Answers, &dns.Answer{Rdata: []string{value}}) - - log.Infof("Update an existing record for [zone: %s, fqdn: %s, domain: %s]", zone.Zone, fqdn, domain) - - _, err = d.client.Records.Update(record) - if err != nil { - return fmt.Errorf("ns1: failed to update record [zone: %q, fqdn: %q]: %v", zone.Zone, fqdn, err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("ns1: %v", err) - } - - name := dns01.UnFqdn(fqdn) - _, err = d.client.Records.Delete(zone.Zone, name, "TXT") - if err != nil { - return fmt.Errorf("ns1: failed to delete record [zone: %q, domain: %q]: %v", zone.Zone, name, err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(fqdn string) (*dns.Zone, error) { - authZone, err := getAuthZone(fqdn) - if err != nil { - return nil, fmt.Errorf("failed to extract auth zone from fqdn %q: %v", fqdn, err) - } - - zone, _, err := d.client.Zones.Get(authZone) - if err != nil { - return nil, fmt.Errorf("failed to get zone [authZone: %q, fqdn: %q]: %v", authZone, fqdn, err) - } - - return zone, nil -} - -func getAuthZone(fqdn string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - return strings.TrimSuffix(authZone, "."), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.toml b/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.toml deleted file mode 100644 index 94200cf..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "NS1" -Description = '''''' -URL = "https://ns1.com" -Code = "ns1" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - NS1_API_KEY = "API key" - [Configuration.Additional] - NS1_POLLING_INTERVAL = "Time between DNS propagation check" - NS1_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - NS1_TTL = "The TTL of the TXT record used for the DNS challenge" - NS1_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://ns1.com/api" - GoClient = "https://github.com/ns1/ns1-go" diff --git a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1_test.go b/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1_test.go deleted file mode 100644 index d7a21b9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package ns1 - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("NS1_API_KEY"). - WithDomain("NS1_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "NS1_API_KEY": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "NS1_API_KEY": "", - }, - expected: "ns1: some credentials information are missing: NS1_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "ns1: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func Test_getAuthZone(t *testing.T) { - type expected struct { - AuthZone string - Error string - } - - testCases := []struct { - desc string - fqdn string - expected expected - }{ - { - desc: "valid fqdn", - fqdn: "_acme-challenge.myhost.sub.example.com.", - expected: expected{ - AuthZone: "example.com", - }, - }, - { - desc: "invalid fqdn", - fqdn: "_acme-challenge.myhost.sub.example.com", - expected: expected{ - Error: "could not find the start of authority for _acme-challenge.myhost.sub.example.com: dns: domain must be fully qualified", - }, - }, - { - desc: "invalid authority", - fqdn: "_acme-challenge.myhost.sub.domain.tld.", - expected: expected{ - Error: "could not find the start of authority for _acme-challenge.myhost.sub.domain.tld.: NXDOMAIN", - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - authZone, err := getAuthZone(test.fqdn) - - if len(test.expected.Error) > 0 { - assert.EqualError(t, err, test.expected.Error) - } else { - require.NoError(t, err) - assert.Equal(t, test.expected.AuthZone, authZone) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/configprovider.go b/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/configprovider.go deleted file mode 100644 index afde368..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/configprovider.go +++ /dev/null @@ -1,101 +0,0 @@ -package oraclecloud - -import ( - "crypto/rsa" - "encoding/base64" - "fmt" - "io/ioutil" - "os" - - "github.com/go-acme/lego/platform/config/env" - "github.com/oracle/oci-go-sdk/common" -) - -const ( - ociPrivkey = "OCI_PRIVKEY" - ociPrivkeyPass = "OCI_PRIVKEY_PASS" - ociTenancyOCID = "OCI_TENANCY_OCID" - ociUserOCID = "OCI_USER_OCID" - ociPubkeyFingerprint = "OCI_PUBKEY_FINGERPRINT" - ociRegion = "OCI_REGION" -) - -type configProvider struct { - values map[string]string - privateKeyPassphrase string -} - -func newConfigProvider(values map[string]string) *configProvider { - return &configProvider{ - values: values, - privateKeyPassphrase: env.GetOrFile(ociPrivkeyPass), - } -} - -func (p *configProvider) PrivateRSAKey() (*rsa.PrivateKey, error) { - privateKey, err := getPrivateKey(ociPrivkey) - if err != nil { - return nil, err - } - - return common.PrivateKeyFromBytes(privateKey, common.String(p.privateKeyPassphrase)) -} - -func (p *configProvider) KeyID() (string, error) { - tenancy, err := p.TenancyOCID() - if err != nil { - return "", err - } - - user, err := p.UserOCID() - if err != nil { - return "", err - } - - fingerprint, err := p.KeyFingerprint() - if err != nil { - return "", err - } - - return fmt.Sprintf("%s/%s/%s", tenancy, user, fingerprint), nil -} - -func (p *configProvider) TenancyOCID() (value string, err error) { - return p.values[ociTenancyOCID], nil -} - -func (p *configProvider) UserOCID() (string, error) { - return p.values[ociUserOCID], nil -} - -func (p *configProvider) KeyFingerprint() (string, error) { - return p.values[ociPubkeyFingerprint], nil -} - -func (p *configProvider) Region() (string, error) { - return p.values[ociRegion], nil -} - -func getPrivateKey(envVar string) ([]byte, error) { - envVarValue := os.Getenv(envVar) - if envVarValue != "" { - bytes, err := base64.StdEncoding.DecodeString(envVarValue) - if err != nil { - return nil, fmt.Errorf("failed to read base64 value %s (defined by env var %s): %s", envVarValue, envVar, err) - } - return bytes, nil - } - - fileVar := envVar + "_FILE" - fileVarValue := os.Getenv(fileVar) - if fileVarValue == "" { - return nil, fmt.Errorf("no value provided for: %s or %s", envVar, fileVar) - } - - fileContents, err := ioutil.ReadFile(fileVarValue) - if err != nil { - return nil, fmt.Errorf("failed to read the file %s (defined by env var %s): %s", fileVarValue, fileVar, err) - } - - return fileContents, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.go b/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.go deleted file mode 100644 index 9218cb8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.go +++ /dev/null @@ -1,175 +0,0 @@ -package oraclecloud - -import ( - "context" - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/oracle/oci-go-sdk/common" - "github.com/oracle/oci-go-sdk/dns" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - CompartmentID string - OCIConfigProvider common.ConfigurationProvider - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("OCI_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("OCI_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("OCI_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("OCI_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - client *dns.DnsClient - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for OracleCloud. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(ociPrivkey, ociTenancyOCID, ociUserOCID, ociPubkeyFingerprint, ociRegion, "OCI_COMPARTMENT_OCID") - if err != nil { - return nil, fmt.Errorf("oraclecloud: %v", err) - } - - config := NewDefaultConfig() - config.CompartmentID = values["OCI_COMPARTMENT_OCID"] - config.OCIConfigProvider = newConfigProvider(values) - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for OracleCloud. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("oraclecloud: the configuration of the DNS provider is nil") - } - - if config.CompartmentID == "" { - return nil, errors.New("oraclecloud: CompartmentID is missing") - } - - if config.OCIConfigProvider == nil { - return nil, errors.New("oraclecloud: OCIConfigProvider is missing") - } - - client, err := dns.NewDnsClientWithConfigurationProvider(config.OCIConfigProvider) - if err != nil { - return nil, fmt.Errorf("oraclecloud: %v", err) - } - - if config.HTTPClient != nil { - client.HTTPClient = config.HTTPClient - } - - return &DNSProvider{client: &client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // generate request to dns.PatchDomainRecordsRequest - recordOperation := dns.RecordOperation{ - Domain: common.String(dns01.UnFqdn(fqdn)), - Rdata: common.String(value), - Rtype: common.String("TXT"), - Ttl: common.Int(d.config.TTL), - IsProtected: common.Bool(false), - } - - request := dns.PatchDomainRecordsRequest{ - CompartmentId: common.String(d.config.CompartmentID), - ZoneNameOrId: common.String(domain), - Domain: common.String(dns01.UnFqdn(fqdn)), - PatchDomainRecordsDetails: dns.PatchDomainRecordsDetails{ - Items: []dns.RecordOperation{recordOperation}, - }, - } - - _, err := d.client.PatchDomainRecords(context.Background(), request) - if err != nil { - return fmt.Errorf("oraclecloud: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // search to TXT record's hash to delete - getRequest := dns.GetDomainRecordsRequest{ - ZoneNameOrId: common.String(domain), - Domain: common.String(dns01.UnFqdn(fqdn)), - CompartmentId: common.String(d.config.CompartmentID), - Rtype: common.String("TXT"), - } - - ctx := context.Background() - - domainRecords, err := d.client.GetDomainRecords(ctx, getRequest) - if err != nil { - return fmt.Errorf("oraclecloud: %v", err) - } - - if *domainRecords.OpcTotalItems == 0 { - return fmt.Errorf("oraclecloud: no record to CleanUp") - } - - var deleteHash *string - for _, record := range domainRecords.RecordCollection.Items { - if record.Rdata != nil && *record.Rdata == `"`+value+`"` { - deleteHash = record.RecordHash - break - } - } - - if deleteHash == nil { - return fmt.Errorf("oraclecloud: no record to CleanUp") - } - - recordOperation := dns.RecordOperation{ - RecordHash: deleteHash, - Operation: dns.RecordOperationOperationRemove, - } - - patchRequest := dns.PatchDomainRecordsRequest{ - ZoneNameOrId: common.String(domain), - Domain: common.String(dns01.UnFqdn(fqdn)), - PatchDomainRecordsDetails: dns.PatchDomainRecordsDetails{ - Items: []dns.RecordOperation{recordOperation}, - }, - CompartmentId: common.String(d.config.CompartmentID), - } - - _, err = d.client.PatchDomainRecords(ctx, patchRequest) - if err != nil { - return fmt.Errorf("oraclecloud: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.toml b/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.toml deleted file mode 100644 index b97ca85..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.toml +++ /dev/null @@ -1,35 +0,0 @@ -Name = "Oracle Cloud" -Description = '''''' -URL = "https://cloud.oracle.com/home" -Code = "oraclecloud" -Since = "v2.3.0" - -Example = ''' -OCI_PRIVKEY_FILE="~/.oci/oci_api_key.pem" \ -OCI_PRIVKEY_PASS="secret" \ -OCI_TENANCY_OCID="ocid1.tenancy.oc1..secret" \ -OCI_USER_OCID="ocid1.user.oc1..secret" \ -OCI_PUBKEY_FINGERPRINT="00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00" \ -OCI_REGION="us-phoenix-1" \ -OCI_COMPARTMENT_OCID="ocid1.tenancy.oc1..secret" \ -lego --dns oraclecloud --domains my.domain.com --email my@email.com run -''' - -[Configuration] - [Configuration.Credentials] - OCI_PRIVKEY_FILE = "Private key file" - OCI_PRIVKEY_PASS = "Private key password" - OCI_TENANCY_OCID = "Tenanct OCID" - OCI_USER_OCID = "User OCID" - OCI_PUBKEY_FINGERPRINT = "Public key fingerprint" - OCI_REGION = "Region" - OCI_COMPARTMENT_OCID = "Compartment OCID" - [Configuration.Additional] - OCI_POLLING_INTERVAL = "Time between DNS propagation check" - OCI_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - OCI_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://docs.cloud.oracle.com/iaas/Content/DNS/Concepts/dnszonemanagement.htm" - GoClient = "https://github.com/oracle/oci-go-sdk" - diff --git a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud_test.go b/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud_test.go deleted file mode 100644 index 0a83ade..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud_test.go +++ /dev/null @@ -1,317 +0,0 @@ -package oraclecloud - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/oracle/oci-go-sdk/common" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - ociPrivkey, - ociPrivkey+"_FILE", - ociPrivkeyPass, - ociTenancyOCID, - ociUserOCID, - ociPubkeyFingerprint, - ociRegion, - "OCI_COMPARTMENT_OCID"). - WithDomain("ORACLECLOUD_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret1"), - ociPrivkeyPass: "secret1", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - }, - { - desc: "success file", - envVars: map[string]string{ - ociPrivkey + "_FILE": mustGeneratePrivateKeyFile("secret1"), - ociPrivkeyPass: "secret1", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{}, - expected: "oraclecloud: some credentials information are missing: OCI_PRIVKEY,OCI_TENANCY_OCID,OCI_USER_OCID,OCI_PUBKEY_FINGERPRINT,OCI_REGION,OCI_COMPARTMENT_OCID", - }, - { - desc: "missing CompartmentID", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "secret", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "", - }, - expected: "oraclecloud: some credentials information are missing: OCI_COMPARTMENT_OCID", - }, - { - desc: "missing OCI_PRIVKEY", - envVars: map[string]string{ - ociPrivkey: "", - ociPrivkeyPass: "secret", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: some credentials information are missing: OCI_PRIVKEY", - }, - { - desc: "missing OCI_PRIVKEY_PASS", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: can not create client, bad configuration: x509: decryption password incorrect", - }, - { - desc: "missing OCI_TENANCY_OCID", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "secret", - ociTenancyOCID: "", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: some credentials information are missing: OCI_TENANCY_OCID", - }, - { - desc: "missing OCI_USER_OCID", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "secret", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: some credentials information are missing: OCI_USER_OCID", - }, - { - desc: "missing OCI_PUBKEY_FINGERPRINT", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "secret", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "", - ociRegion: "us-phoenix-1", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: some credentials information are missing: OCI_PUBKEY_FINGERPRINT", - }, - { - desc: "missing OCI_REGION", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "secret", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: some credentials information are missing: OCI_REGION", - }, - { - desc: "missing OCI_REGION", - envVars: map[string]string{ - ociPrivkey: mustGeneratePrivateKey("secret"), - ociPrivkeyPass: "secret", - ociTenancyOCID: "ocid1.tenancy.oc1..secret", - ociUserOCID: "ocid1.user.oc1..secret", - ociPubkeyFingerprint: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00", - ociRegion: "", - "OCI_COMPARTMENT_OCID": "123", - }, - expected: "oraclecloud: some credentials information are missing: OCI_REGION", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer func() { - privKeyFile := os.Getenv(ociPrivkey + "_FILE") - if privKeyFile != "" { - _ = os.Remove(privKeyFile) - } - envTest.RestoreEnv() - }() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - compartmentID string - configurationProvider common.ConfigurationProvider - expected string - }{ - { - desc: "invalid configuration", - configurationProvider: &configProvider{}, - compartmentID: "123", - expected: "oraclecloud: can not create client, bad configuration: x509: decryption password incorrect", - }, - { - desc: "OCIConfigProvider is missing", - compartmentID: "123", - expected: "oraclecloud: OCIConfigProvider is missing", - }, - { - desc: "missing CompartmentID", - expected: "oraclecloud: CompartmentID is missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.CompartmentID = test.compartmentID - config.OCIConfigProvider = test.configurationProvider - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func mustGeneratePrivateKey(pwd string) string { - block, err := generatePrivateKey(pwd) - if err != nil { - panic(err) - } - - return base64.StdEncoding.EncodeToString(pem.EncodeToMemory(block)) -} - -func mustGeneratePrivateKeyFile(pwd string) string { - block, err := generatePrivateKey(pwd) - if err != nil { - panic(err) - } - - file, err := ioutil.TempFile("", "lego_oci_*.pem") - if err != nil { - panic(err) - } - - err = pem.Encode(file, block) - if err != nil { - panic(err) - } - - return file.Name() -} - -func generatePrivateKey(pwd string) (*pem.Block, error) { - key, err := rsa.GenerateKey(rand.Reader, 512) - if err != nil { - return nil, err - } - - block := &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: x509.MarshalPKCS1PrivateKey(key), - } - - if pwd != "" { - block, err = x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, []byte(pwd), x509.PEMCipherAES256) - if err != nil { - return nil, err - } - } - - return block, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/client.go b/vendor/github.com/go-acme/lego/providers/dns/otc/client.go deleted file mode 100644 index 1cd71f5..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/client.go +++ /dev/null @@ -1,263 +0,0 @@ -package otc - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" -) - -type recordset struct { - Name string `json:"name"` - Description string `json:"description"` - Type string `json:"type"` - TTL int `json:"ttl"` - Records []string `json:"records"` -} - -type nameResponse struct { - Name string `json:"name"` -} - -type userResponse struct { - Name string `json:"name"` - Password string `json:"password"` - Domain nameResponse `json:"domain"` -} - -type passwordResponse struct { - User userResponse `json:"user"` -} - -type identityResponse struct { - Methods []string `json:"methods"` - Password passwordResponse `json:"password"` -} - -type scopeResponse struct { - Project nameResponse `json:"project"` -} - -type authResponse struct { - Identity identityResponse `json:"identity"` - Scope scopeResponse `json:"scope"` -} - -type loginResponse struct { - Auth authResponse `json:"auth"` -} - -type endpointResponse struct { - Token token `json:"token"` -} - -type token struct { - Catalog []catalog `json:"catalog"` -} - -type catalog struct { - Type string `json:"type"` - Endpoints []endpoint `json:"endpoints"` -} - -type endpoint struct { - URL string `json:"url"` -} - -type zoneItem struct { - ID string `json:"id"` -} - -type zonesResponse struct { - Zones []zoneItem `json:"zones"` -} - -type recordSet struct { - ID string `json:"id"` -} - -type recordSetsResponse struct { - RecordSets []recordSet `json:"recordsets"` -} - -// Starts a new OTC API Session. Authenticates using userName, password -// and receives a token to be used in for subsequent requests. -func (d *DNSProvider) login() error { - return d.loginRequest() -} - -func (d *DNSProvider) loginRequest() error { - userResp := userResponse{ - Name: d.config.UserName, - Password: d.config.Password, - Domain: nameResponse{ - Name: d.config.DomainName, - }, - } - - loginResp := loginResponse{ - Auth: authResponse{ - Identity: identityResponse{ - Methods: []string{"password"}, - Password: passwordResponse{ - User: userResp, - }, - }, - Scope: scopeResponse{ - Project: nameResponse{ - Name: d.config.ProjectName, - }, - }, - }, - } - - body, err := json.Marshal(loginResp) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, d.config.IdentityEndpoint, bytes.NewReader(body)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - - client := &http.Client{Timeout: d.config.HTTPClient.Timeout} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return fmt.Errorf("OTC API request failed with HTTP status code %d", resp.StatusCode) - } - - d.token = resp.Header.Get("X-Subject-Token") - - if d.token == "" { - return fmt.Errorf("unable to get auth token") - } - - var endpointResp endpointResponse - - err = json.NewDecoder(resp.Body).Decode(&endpointResp) - if err != nil { - return err - } - - var endpoints []endpoint - for _, v := range endpointResp.Token.Catalog { - if v.Type == "dns" { - endpoints = append(endpoints, v.Endpoints...) - } - } - - if len(endpoints) > 0 { - d.baseURL = fmt.Sprintf("%s/v2", endpoints[0].URL) - } else { - return fmt.Errorf("unable to get dns endpoint") - } - - return nil -} - -func (d *DNSProvider) getZoneID(zone string) (string, error) { - resource := fmt.Sprintf("zones?name=%s", zone) - resp, err := d.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return "", err - } - - var zonesRes zonesResponse - err = json.NewDecoder(resp).Decode(&zonesRes) - if err != nil { - return "", err - } - - if len(zonesRes.Zones) < 1 { - return "", fmt.Errorf("zone %s not found", zone) - } - - if len(zonesRes.Zones) > 1 { - return "", fmt.Errorf("to many zones found") - } - - if zonesRes.Zones[0].ID == "" { - return "", fmt.Errorf("id not found") - } - - return zonesRes.Zones[0].ID, nil -} - -func (d *DNSProvider) getRecordSetID(zoneID string, fqdn string) (string, error) { - resource := fmt.Sprintf("zones/%s/recordsets?type=TXT&name=%s", zoneID, fqdn) - resp, err := d.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return "", err - } - - var recordSetsRes recordSetsResponse - err = json.NewDecoder(resp).Decode(&recordSetsRes) - if err != nil { - return "", err - } - - if len(recordSetsRes.RecordSets) < 1 { - return "", fmt.Errorf("record not found") - } - - if len(recordSetsRes.RecordSets) > 1 { - return "", fmt.Errorf("to many records found") - } - - if recordSetsRes.RecordSets[0].ID == "" { - return "", fmt.Errorf("id not found") - } - - return recordSetsRes.RecordSets[0].ID, nil -} - -func (d *DNSProvider) deleteRecordSet(zoneID, recordID string) error { - resource := fmt.Sprintf("zones/%s/recordsets/%s", zoneID, recordID) - - _, err := d.sendRequest(http.MethodDelete, resource, nil) - return err -} - -func (d *DNSProvider) sendRequest(method, resource string, payload interface{}) (io.Reader, error) { - url := fmt.Sprintf("%s/%s", d.baseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - if len(d.token) > 0 { - req.Header.Set("X-Auth-Token", d.token) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("OTC API request %s failed with HTTP status code %d", url, resp.StatusCode) - } - - body1, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return bytes.NewReader(body1), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/mock_test.go b/vendor/github.com/go-acme/lego/providers/dns/otc/mock_test.go deleted file mode 100644 index 31778c0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/mock_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package otc - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -const fakeOTCToken = "62244bc21da68d03ebac94e6636ff01f" - -// DNSServerMock mock -type DNSServerMock struct { - t *testing.T - server *httptest.Server - Mux *http.ServeMux -} - -// NewDNSServerMock create a new DNSServerMock -func NewDNSServerMock(t *testing.T) *DNSServerMock { - mux := http.NewServeMux() - - return &DNSServerMock{ - t: t, - server: httptest.NewServer(mux), - Mux: mux, - } -} - -func (m *DNSServerMock) GetServerURL() string { - return m.server.URL -} - -// ShutdownServer creates the mock server -func (m *DNSServerMock) ShutdownServer() { - m.server.Close() -} - -// HandleAuthSuccessfully Handle auth successfully -func (m *DNSServerMock) HandleAuthSuccessfully() { - m.Mux.HandleFunc("/v3/auth/token", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("X-Subject-Token", fakeOTCToken) - - fmt.Fprintf(w, `{ - "token": { - "catalog": [ - { - "type": "dns", - "id": "56cd81db1f8445d98652479afe07c5ba", - "name": "", - "endpoints": [ - { - "url": "%s", - "region": "eu-de", - "region_id": "eu-de", - "interface": "public", - "id": "0047a06690484d86afe04877074efddf" - } - ] - } - ] - }}`, m.server.URL) - }) -} - -// HandleListZonesSuccessfully Handle list zones successfully -func (m *DNSServerMock) HandleListZonesSuccessfully() { - m.Mux.HandleFunc("/v2/zones", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(m.t, r.Method, http.MethodGet) - assert.Equal(m.t, r.URL.Path, "/v2/zones") - assert.Equal(m.t, r.URL.RawQuery, "name=example.com.") - assert.Equal(m.t, r.Header.Get("Content-Type"), "application/json") - - fmt.Fprintf(w, `{ - "zones":[{ - "id":"123123" - }]} - `) - - }) -} - -// HandleListZonesEmpty Handle list zones empty -func (m *DNSServerMock) HandleListZonesEmpty() { - m.Mux.HandleFunc("/v2/zones", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(m.t, r.Method, http.MethodGet) - assert.Equal(m.t, r.URL.Path, "/v2/zones") - assert.Equal(m.t, r.URL.RawQuery, "name=example.com.") - assert.Equal(m.t, r.Header.Get("Content-Type"), "application/json") - - fmt.Fprintf(w, `{ - "zones":[ - ]} - `) - }) -} - -// HandleDeleteRecordsetsSuccessfully Handle delete recordsets successfully -func (m *DNSServerMock) HandleDeleteRecordsetsSuccessfully() { - m.Mux.HandleFunc("/v2/zones/123123/recordsets/321321", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(m.t, r.Method, http.MethodDelete) - assert.Equal(m.t, r.URL.Path, "/v2/zones/123123/recordsets/321321") - assert.Equal(m.t, r.Header.Get("Content-Type"), "application/json") - - fmt.Fprintf(w, `{ - "zones":[{ - "id":"123123" - }]} - `) - }) -} - -// HandleListRecordsetsEmpty Handle list recordsets empty -func (m *DNSServerMock) HandleListRecordsetsEmpty() { - m.Mux.HandleFunc("/v2/zones/123123/recordsets", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(m.t, r.URL.Path, "/v2/zones/123123/recordsets") - assert.Equal(m.t, r.URL.RawQuery, "type=TXT&name=_acme-challenge.example.com.") - - fmt.Fprintf(w, `{ - "recordsets":[ - ]} - `) - }) -} - -// HandleListRecordsetsSuccessfully Handle list recordsets successfully -func (m *DNSServerMock) HandleListRecordsetsSuccessfully() { - m.Mux.HandleFunc("/v2/zones/123123/recordsets", func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodGet { - assert.Equal(m.t, r.URL.Path, "/v2/zones/123123/recordsets") - assert.Equal(m.t, r.URL.RawQuery, "type=TXT&name=_acme-challenge.example.com.") - assert.Equal(m.t, r.Header.Get("Content-Type"), "application/json") - - fmt.Fprintf(w, `{ - "recordsets":[{ - "id":"321321" - }]} - `) - return - } - - if r.Method == http.MethodPost { - assert.Equal(m.t, r.Header.Get("Content-Type"), "application/json") - - body, err := ioutil.ReadAll(r.Body) - assert.Nil(m.t, err) - exceptedString := "{\"name\":\"_acme-challenge.example.com.\",\"description\":\"Added TXT record for ACME dns-01 challenge using lego client\",\"type\":\"TXT\",\"ttl\":300,\"records\":[\"\\\"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI\\\"\"]}" - assert.Equal(m.t, string(body), exceptedString) - fmt.Fprintf(w, `{ - "recordsets":[{ - "id":"321321" - }]} - `) - return - } - - http.Error(w, fmt.Sprintf("Expected method to be 'GET' or 'POST' but got '%s'", r.Method), http.StatusBadRequest) - }) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/otc.go b/vendor/github.com/go-acme/lego/providers/dns/otc/otc.go deleted file mode 100644 index 94eb6c2..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/otc.go +++ /dev/null @@ -1,179 +0,0 @@ -// Package otc implements a DNS provider for solving the DNS-01 challenge using Open Telekom Cloud Managed DNS. -package otc - -import ( - "errors" - "fmt" - "net" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultIdentityEndpoint = "https://iam.eu-de.otc.t-systems.com:443/v3/auth/tokens" - -// minTTL 300 is otc minimum value for ttl -const minTTL = 300 - -// Config is used to configure the creation of the DNSProvider -type Config struct { - IdentityEndpoint string - DomainName string - ProjectName string - UserName string - Password string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - IdentityEndpoint: env.GetOrDefaultString("OTC_IDENTITY_ENDPOINT", defaultIdentityEndpoint), - PropagationTimeout: env.GetOrDefaultSecond("OTC_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("OTC_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("OTC_TTL", minTTL), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("OTC_HTTP_TIMEOUT", 10*time.Second), - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - - // Workaround for keep alive bug in otc api - DisableKeepAlives: true, - }, - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// OTC's Managed DNS API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - baseURL string - token string -} - -// NewDNSProvider returns a DNSProvider instance configured for OTC DNS. -// Credentials must be passed in the environment variables: OTC_USER_NAME, -// OTC_DOMAIN_NAME, OTC_PASSWORD OTC_PROJECT_NAME and OTC_IDENTITY_ENDPOINT. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("OTC_DOMAIN_NAME", "OTC_USER_NAME", "OTC_PASSWORD", "OTC_PROJECT_NAME") - if err != nil { - return nil, fmt.Errorf("otc: %v", err) - } - - config := NewDefaultConfig() - config.DomainName = values["OTC_DOMAIN_NAME"] - config.UserName = values["OTC_USER_NAME"] - config.Password = values["OTC_PASSWORD"] - config.ProjectName = values["OTC_PROJECT_NAME"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for OTC DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("otc: the configuration of the DNS provider is nil") - } - - if config.DomainName == "" || config.UserName == "" || config.Password == "" || config.ProjectName == "" { - return nil, fmt.Errorf("otc: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("otc: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - if config.IdentityEndpoint == "" { - config.IdentityEndpoint = defaultIdentityEndpoint - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("otc: unable to get zone: %s", err) - } - - resource := fmt.Sprintf("zones/%s/recordsets", zoneID) - - r1 := &recordset{ - Name: fqdn, - Description: "Added TXT record for ACME dns-01 challenge using lego client", - Type: "TXT", - TTL: d.config.TTL, - Records: []string{fmt.Sprintf("\"%s\"", value)}, - } - - _, err = d.sendRequest(http.MethodPost, resource, r1) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - recordID, err := d.getRecordSetID(zoneID, fqdn) - if err != nil { - return fmt.Errorf("otc: unable go get record %s for zone %s: %s", fqdn, domain, err) - } - - err = d.deleteRecordSet(zoneID, recordID) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/otc.toml b/vendor/github.com/go-acme/lego/providers/dns/otc/otc.toml deleted file mode 100644 index d60aa3f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/otc.toml +++ /dev/null @@ -1,24 +0,0 @@ -Name = "Open Telekom Cloud" -Description = '''''' -URL = "https://cloud.telekom.de/en" -Code = "otc" -Since = "v0.4.1" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - OTC_USER_NAME = "User name" - OTC_PASSWORD = "Password" - OTC_PROJECT_NAME = "Project name" - OTC_DOMAIN_NAME = "Domain name" - OTC_IDENTITY_ENDPOINT = "Identity endpoint URL" - [Configuration.Additional] - OTC_POLLING_INTERVAL = "Time between DNS propagation check" - OTC_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - OTC_TTL = "The TTL of the TXT record used for the DNS challenge" - OTC_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://docs.otc.t-systems.com/en-us/dns/index.html" - diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/otc_test.go b/vendor/github.com/go-acme/lego/providers/dns/otc/otc_test.go deleted file mode 100644 index 9883faa..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/otc_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package otc - -import ( - "fmt" - "os" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/suite" -) - -type OTCSuite struct { - suite.Suite - Mock *DNSServerMock - envTest *tester.EnvTest -} - -func (s *OTCSuite) SetupTest() { - s.Mock = NewDNSServerMock(s.T()) - s.Mock.HandleAuthSuccessfully() - s.envTest = tester.NewEnvTest( - "OTC_DOMAIN_NAME", - "OTC_USER_NAME", - "OTC_PASSWORD", - "OTC_PROJECT_NAME", - "OTC_IDENTITY_ENDPOINT", - ) -} - -func (s *OTCSuite) TearDownTest() { - s.envTest.RestoreEnv() - s.Mock.ShutdownServer() -} - -func TestTestSuite(t *testing.T) { - suite.Run(t, new(OTCSuite)) -} - -func (s *OTCSuite) createDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - config.UserName = "UserName" - config.Password = "Password" - config.DomainName = "DomainName" - config.ProjectName = "ProjectName" - config.IdentityEndpoint = fmt.Sprintf("%s/v3/auth/token", s.Mock.GetServerURL()) - - return NewDNSProviderConfig(config) -} - -func (s *OTCSuite) TestLogin() { - provider, err := s.createDNSProvider() - s.Require().NoError(err) - - err = provider.loginRequest() - s.Require().NoError(err) - - s.Equal(provider.baseURL, fmt.Sprintf("%s/v2", s.Mock.GetServerURL())) - s.Equal(fakeOTCToken, provider.token) -} - -func (s *OTCSuite) TestLoginEnv() { - s.envTest.ClearEnv() - - s.envTest.Apply(map[string]string{ - "OTC_DOMAIN_NAME": "unittest1", - "OTC_USER_NAME": "unittest2", - "OTC_PASSWORD": "unittest3", - "OTC_PROJECT_NAME": "unittest4", - "OTC_IDENTITY_ENDPOINT": "unittest5", - }) - - provider, err := NewDNSProvider() - s.Require().NoError(err) - - s.Equal(provider.config.DomainName, "unittest1") - s.Equal(provider.config.UserName, "unittest2") - s.Equal(provider.config.Password, "unittest3") - s.Equal(provider.config.ProjectName, "unittest4") - s.Equal(provider.config.IdentityEndpoint, "unittest5") - - os.Setenv("OTC_IDENTITY_ENDPOINT", "") - - provider, err = NewDNSProvider() - s.Require().NoError(err) - - s.Equal(provider.config.IdentityEndpoint, "https://iam.eu-de.otc.t-systems.com:443/v3/auth/tokens") -} - -func (s *OTCSuite) TestLoginEnvEmpty() { - s.envTest.ClearEnv() - - _, err := NewDNSProvider() - s.EqualError(err, "otc: some credentials information are missing: OTC_DOMAIN_NAME,OTC_USER_NAME,OTC_PASSWORD,OTC_PROJECT_NAME") -} - -func (s *OTCSuite) TestDNSProvider_Present() { - s.Mock.HandleListZonesSuccessfully() - s.Mock.HandleListRecordsetsSuccessfully() - - provider, err := s.createDNSProvider() - s.Require().NoError(err) - - err = provider.Present("example.com", "", "foobar") - s.Require().NoError(err) -} - -func (s *OTCSuite) TestDNSProvider_Present_EmptyZone() { - s.Mock.HandleListZonesEmpty() - s.Mock.HandleListRecordsetsSuccessfully() - - provider, err := s.createDNSProvider() - s.Require().NoError(err) - - err = provider.Present("example.com", "", "foobar") - s.NotNil(err) -} - -func (s *OTCSuite) TestDNSProvider_CleanUp() { - s.Mock.HandleListZonesSuccessfully() - s.Mock.HandleListRecordsetsSuccessfully() - s.Mock.HandleDeleteRecordsetsSuccessfully() - - provider, err := s.createDNSProvider() - s.Require().NoError(err) - - err = provider.CleanUp("example.com", "", "foobar") - s.Require().NoError(err) -} - -func (s *OTCSuite) TestDNSProvider_CleanUp_EmptyRecordset() { - s.Mock.HandleListZonesSuccessfully() - s.Mock.HandleListRecordsetsEmpty() - - provider, err := s.createDNSProvider() - s.Require().NoError(err) - - err = provider.CleanUp("example.com", "", "foobar") - s.Require().Error(err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.go b/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.go deleted file mode 100644 index dae9e1e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.go +++ /dev/null @@ -1,203 +0,0 @@ -// Package ovh implements a DNS provider for solving the DNS-01 challenge using OVH DNS. -package ovh - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/ovh/go-ovh/ovh" -) - -// OVH API reference: https://eu.api.ovh.com/ -// Create a Token: https://eu.api.ovh.com/createToken/ - -// Record a DNS record -type Record struct { - ID int `json:"id,omitempty"` - FieldType string `json:"fieldType,omitempty"` - SubDomain string `json:"subDomain,omitempty"` - Target string `json:"target,omitempty"` - TTL int `json:"ttl,omitempty"` - Zone string `json:"zone,omitempty"` -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIEndpoint string - ApplicationKey string - ApplicationSecret string - ConsumerKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("OVH_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("OVH_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("OVH_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("OVH_HTTP_TIMEOUT", ovh.DefaultTimeout), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -// that uses OVH's REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - client *ovh.Client - recordIDs map[string]int - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for OVH -// Credentials must be passed in the environment variable: -// OVH_ENDPOINT : it must be ovh-eu or ovh-ca -// OVH_APPLICATION_KEY -// OVH_APPLICATION_SECRET -// OVH_CONSUMER_KEY -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("OVH_ENDPOINT", "OVH_APPLICATION_KEY", "OVH_APPLICATION_SECRET", "OVH_CONSUMER_KEY") - if err != nil { - return nil, fmt.Errorf("ovh: %v", err) - } - - config := NewDefaultConfig() - config.APIEndpoint = values["OVH_ENDPOINT"] - config.ApplicationKey = values["OVH_APPLICATION_KEY"] - config.ApplicationSecret = values["OVH_APPLICATION_SECRET"] - config.ConsumerKey = values["OVH_CONSUMER_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for OVH. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("ovh: the configuration of the DNS provider is nil") - } - - if config.APIEndpoint == "" || config.ApplicationKey == "" || config.ApplicationSecret == "" || config.ConsumerKey == "" { - return nil, fmt.Errorf("ovh: credentials missing") - } - - client, err := ovh.NewClient( - config.APIEndpoint, - config.ApplicationKey, - config.ApplicationSecret, - config.ConsumerKey, - ) - if err != nil { - return nil, fmt.Errorf("ovh: %v", err) - } - - client.Client = config.HTTPClient - - return &DNSProvider{ - config: config, - client: client, - recordIDs: make(map[string]int), - }, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // Parse domain name - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("ovh: could not determine zone for domain: '%s'. %s", domain, err) - } - - authZone = dns01.UnFqdn(authZone) - subDomain := d.extractRecordName(fqdn, authZone) - - reqURL := fmt.Sprintf("/domain/zone/%s/record", authZone) - reqData := Record{FieldType: "TXT", SubDomain: subDomain, Target: value, TTL: d.config.TTL} - - // Create TXT record - var respData Record - err = d.client.Post(reqURL, reqData, &respData) - if err != nil { - return fmt.Errorf("ovh: error when call api to add record (%s): %v", reqURL, err) - } - - // Apply the change - reqURL = fmt.Sprintf("/domain/zone/%s/refresh", authZone) - err = d.client.Post(reqURL, nil, nil) - if err != nil { - return fmt.Errorf("ovh: error when call api to refresh zone (%s): %v", reqURL, err) - } - - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = respData.ID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // get the record's unique ID from when we created it - d.recordIDsMu.Lock() - recordID, ok := d.recordIDs[fqdn] - d.recordIDsMu.Unlock() - if !ok { - return fmt.Errorf("ovh: unknown record ID for '%s'", fqdn) - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("ovh: could not determine zone for domain: '%s'. %s", domain, err) - } - - authZone = dns01.UnFqdn(authZone) - - reqURL := fmt.Sprintf("/domain/zone/%s/record/%d", authZone, recordID) - - err = d.client.Delete(reqURL, nil) - if err != nil { - return fmt.Errorf("ovh: error when call OVH api to delete challenge record (%s): %v", reqURL, err) - } - - // Apply the change - reqURL = fmt.Sprintf("/domain/zone/%s/refresh", authZone) - err = d.client.Post(reqURL, nil, nil) - if err != nil { - return fmt.Errorf("ovh: error when call api to refresh zone (%s): %v", reqURL, err) - } - - // Delete record ID from map - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.toml b/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.toml deleted file mode 100644 index 46ba81b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.toml +++ /dev/null @@ -1,23 +0,0 @@ -Name = "OVH" -Description = '''''' -URL = "https://www.ovh.com/" -Code = "ovh" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - OVH_ENDPOINT = "Endpoint URL (ovh-eu or ovh-ca)" - OVH_APPLICATION_KEY = "Application key" - OVH_APPLICATION_SECRET = "Application secret" - OVH_CONSUMER_KEY = "Consumer key" - [Configuration.Additional] - OVH_POLLING_INTERVAL = "Time between DNS propagation check" - OVH_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - OVH_TTL = "The TTL of the TXT record used for the DNS challenge" - OVH_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://eu.api.ovh.com/" - GoClient = "https://github.com/ovh/go-ovh" diff --git a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh_test.go b/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh_test.go deleted file mode 100644 index fea9100..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package ovh - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "OVH_ENDPOINT", - "OVH_APPLICATION_KEY", - "OVH_APPLICATION_SECRET", - "OVH_CONSUMER_KEY"). - WithDomain("OVH_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "OVH_ENDPOINT": "ovh-eu", - "OVH_APPLICATION_KEY": "B", - "OVH_APPLICATION_SECRET": "C", - "OVH_CONSUMER_KEY": "D", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "OVH_ENDPOINT": "", - "OVH_APPLICATION_KEY": "", - "OVH_APPLICATION_SECRET": "", - "OVH_CONSUMER_KEY": "", - }, - expected: "ovh: some credentials information are missing: OVH_ENDPOINT,OVH_APPLICATION_KEY,OVH_APPLICATION_SECRET,OVH_CONSUMER_KEY", - }, - { - desc: "missing endpoint", - envVars: map[string]string{ - "OVH_ENDPOINT": "", - "OVH_APPLICATION_KEY": "B", - "OVH_APPLICATION_SECRET": "C", - "OVH_CONSUMER_KEY": "D", - }, - expected: "ovh: some credentials information are missing: OVH_ENDPOINT", - }, - { - desc: "missing invalid endpoint", - envVars: map[string]string{ - "OVH_ENDPOINT": "foobar", - "OVH_APPLICATION_KEY": "B", - "OVH_APPLICATION_SECRET": "C", - "OVH_CONSUMER_KEY": "D", - }, - expected: "ovh: unknown endpoint 'foobar', consider checking 'Endpoints' list of using an URL", - }, - { - desc: "missing application key", - envVars: map[string]string{ - "OVH_ENDPOINT": "ovh-eu", - "OVH_APPLICATION_KEY": "", - "OVH_APPLICATION_SECRET": "C", - "OVH_CONSUMER_KEY": "D", - }, - expected: "ovh: some credentials information are missing: OVH_APPLICATION_KEY", - }, - { - desc: "missing application secret", - envVars: map[string]string{ - "OVH_ENDPOINT": "ovh-eu", - "OVH_APPLICATION_KEY": "B", - "OVH_APPLICATION_SECRET": "", - "OVH_CONSUMER_KEY": "D", - }, - expected: "ovh: some credentials information are missing: OVH_APPLICATION_SECRET", - }, - { - desc: "missing consumer key", - envVars: map[string]string{ - "OVH_ENDPOINT": "ovh-eu", - "OVH_APPLICATION_KEY": "B", - "OVH_APPLICATION_SECRET": "C", - "OVH_CONSUMER_KEY": "", - }, - expected: "ovh: some credentials information are missing: OVH_CONSUMER_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - require.NotNil(t, p.recordIDs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiEndpoint string - applicationKey string - applicationSecret string - consumerKey string - expected string - }{ - { - desc: "success", - apiEndpoint: "ovh-eu", - applicationKey: "B", - applicationSecret: "C", - consumerKey: "D", - }, - { - desc: "missing credentials", - expected: "ovh: credentials missing", - }, - { - desc: "missing api endpoint", - apiEndpoint: "", - applicationKey: "B", - applicationSecret: "C", - consumerKey: "D", - expected: "ovh: credentials missing", - }, - { - desc: "missing invalid api endpoint", - apiEndpoint: "foobar", - applicationKey: "B", - applicationSecret: "C", - consumerKey: "D", - expected: "ovh: unknown endpoint 'foobar', consider checking 'Endpoints' list of using an URL", - }, - { - desc: "missing application key", - apiEndpoint: "ovh-eu", - applicationKey: "", - applicationSecret: "C", - consumerKey: "D", - expected: "ovh: credentials missing", - }, - { - desc: "missing application secret", - apiEndpoint: "ovh-eu", - applicationKey: "B", - applicationSecret: "", - consumerKey: "D", - expected: "ovh: credentials missing", - }, - { - desc: "missing consumer key", - apiEndpoint: "ovh-eu", - applicationKey: "B", - applicationSecret: "C", - consumerKey: "", - expected: "ovh: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIEndpoint = test.apiEndpoint - config.ApplicationKey = test.applicationKey - config.ApplicationSecret = test.applicationSecret - config.ConsumerKey = test.consumerKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - require.NotNil(t, p.recordIDs) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/pdns/client.go b/vendor/github.com/go-acme/lego/providers/dns/pdns/client.go deleted file mode 100644 index c66181e..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/pdns/client.go +++ /dev/null @@ -1,220 +0,0 @@ -package pdns - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" -) - -type Record struct { - Content string `json:"content"` - Disabled bool `json:"disabled"` - - // pre-v1 API - Name string `json:"name"` - Type string `json:"type"` - TTL int `json:"ttl,omitempty"` -} - -type hostedZone struct { - ID string `json:"id"` - Name string `json:"name"` - URL string `json:"url"` - RRSets []rrSet `json:"rrsets"` - - // pre-v1 API - Records []Record `json:"records"` -} - -type rrSet struct { - Name string `json:"name"` - Type string `json:"type"` - Kind string `json:"kind"` - ChangeType string `json:"changetype"` - Records []Record `json:"records"` - TTL int `json:"ttl,omitempty"` -} - -type rrSets struct { - RRSets []rrSet `json:"rrsets"` -} - -type apiError struct { - ShortMsg string `json:"error"` -} - -func (a apiError) Error() string { - return a.ShortMsg -} - -type apiVersion struct { - URL string `json:"url"` - Version int `json:"version"` -} - -func (d *DNSProvider) getHostedZone(fqdn string) (*hostedZone, error) { - var zone hostedZone - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - u := "/servers/localhost/zones" - result, err := d.sendRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - var zones []hostedZone - err = json.Unmarshal(result, &zones) - if err != nil { - return nil, err - } - - u = "" - for _, zone := range zones { - if dns01.UnFqdn(zone.Name) == dns01.UnFqdn(authZone) { - u = zone.URL - break - } - } - - result, err = d.sendRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - err = json.Unmarshal(result, &zone) - if err != nil { - return nil, err - } - - // convert pre-v1 API result - if len(zone.Records) > 0 { - zone.RRSets = []rrSet{} - for _, record := range zone.Records { - set := rrSet{ - Name: record.Name, - Type: record.Type, - Records: []Record{record}, - } - zone.RRSets = append(zone.RRSets, set) - } - } - - return &zone, nil -} - -func (d *DNSProvider) findTxtRecord(fqdn string) (*rrSet, error) { - zone, err := d.getHostedZone(fqdn) - if err != nil { - return nil, err - } - - _, err = d.sendRequest(http.MethodGet, zone.URL, nil) - if err != nil { - return nil, err - } - - for _, set := range zone.RRSets { - if (set.Name == dns01.UnFqdn(fqdn) || set.Name == fqdn) && set.Type == "TXT" { - return &set, nil - } - } - - return nil, nil -} - -func (d *DNSProvider) getAPIVersion() (int, error) { - result, err := d.sendRequest(http.MethodGet, "/api", nil) - if err != nil { - return 0, err - } - - var versions []apiVersion - err = json.Unmarshal(result, &versions) - if err != nil { - return 0, err - } - - latestVersion := 0 - for _, v := range versions { - if v.Version > latestVersion { - latestVersion = v.Version - } - } - - return latestVersion, err -} - -func (d *DNSProvider) sendRequest(method, uri string, body io.Reader) (json.RawMessage, error) { - req, err := d.makeRequest(method, uri, body) - if err != nil { - return nil, err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error talking to PDNS API -> %v", err) - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusUnprocessableEntity && (resp.StatusCode < 200 || resp.StatusCode >= 300) { - return nil, fmt.Errorf("unexpected HTTP status code %d when fetching '%s'", resp.StatusCode, req.URL) - } - - var msg json.RawMessage - err = json.NewDecoder(resp.Body).Decode(&msg) - if err != nil { - if err == io.EOF { - // empty body - return nil, nil - } - // other error - return nil, err - } - - // check for PowerDNS error message - if len(msg) > 0 && msg[0] == '{' { - var errInfo apiError - err = json.Unmarshal(msg, &errInfo) - if err != nil { - return nil, err - } - if errInfo.ShortMsg != "" { - return nil, fmt.Errorf("error talking to PDNS API -> %v", errInfo) - } - } - return msg, nil -} - -func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (*http.Request, error) { - var path = "" - if d.config.Host.Path != "/" { - path = d.config.Host.Path - } - - if !strings.HasPrefix(uri, "/") { - uri = "/" + uri - } - - if d.apiVersion > 0 && !strings.HasPrefix(uri, "/api/v") { - uri = "/api/v" + strconv.Itoa(d.apiVersion) + uri - } - - u := d.config.Host.Scheme + "://" + d.config.Host.Host + path + uri - req, err := http.NewRequest(method, u, body) - if err != nil { - return nil, err - } - - req.Header.Set("X-API-Key", d.config.APIKey) - - return req, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.go b/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.go deleted file mode 100644 index 87adedb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.go +++ /dev/null @@ -1,198 +0,0 @@ -// Package pdns implements a DNS provider for solving the DNS-01 challenge using PowerDNS nameserver. -package pdns - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - Host *url.URL - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("PDNS_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("PDNS_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("PDNS_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("PDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - apiVersion int - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for pdns. -// Credentials must be passed in the environment variable: -// PDNS_API_URL and PDNS_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("PDNS_API_KEY", "PDNS_API_URL") - if err != nil { - return nil, fmt.Errorf("pdns: %v", err) - } - - hostURL, err := url.Parse(values["PDNS_API_URL"]) - if err != nil { - return nil, fmt.Errorf("pdns: %v", err) - } - - config := NewDefaultConfig() - config.Host = hostURL - config.APIKey = values["PDNS_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for pdns. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("pdns: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("pdns: API key missing") - } - - if config.Host == nil || config.Host.Host == "" { - return nil, fmt.Errorf("pdns: API URL missing") - } - - d := &DNSProvider{config: config} - - apiVersion, err := d.getAPIVersion() - if err != nil { - log.Warnf("pdns: failed to get API version %v", err) - } - d.apiVersion = apiVersion - - return d, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - name := fqdn - - // pre-v1 API wants non-fqdn - if d.apiVersion == 0 { - name = dns01.UnFqdn(fqdn) - } - - rec := Record{ - Content: "\"" + value + "\"", - Disabled: false, - - // pre-v1 API - Type: "TXT", - Name: name, - TTL: d.config.TTL, - } - - // Look for existing records. - existingRrSet, err := d.findTxtRecord(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - // merge the existing and new records - var records []Record - if existingRrSet != nil { - records = existingRrSet.Records - } - records = append(records, rec) - - rrsets := rrSets{ - RRSets: []rrSet{ - { - Name: name, - ChangeType: "REPLACE", - Type: "TXT", - Kind: "Master", - TTL: d.config.TTL, - Records: records, - }, - }, - } - - body, err := json.Marshal(rrsets) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - _, err = d.sendRequest(http.MethodPatch, zone.URL, bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - set, err := d.findTxtRecord(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - if set == nil { - return fmt.Errorf("pdns: no existing record found for %s", fqdn) - } - - rrsets := rrSets{ - RRSets: []rrSet{ - { - Name: set.Name, - Type: set.Type, - ChangeType: "DELETE", - }, - }, - } - body, err := json.Marshal(rrsets) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - _, err = d.sendRequest(http.MethodPatch, zone.URL, bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.toml b/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.toml deleted file mode 100644 index f6b8370..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.toml +++ /dev/null @@ -1,30 +0,0 @@ -Name = "PowerDNS" -Description = '''''' -URL = "https://www.powerdns.com/" -Code = "pdns" -Since = "v0.4.0" - -Example = '''''' - -Additional = ''' -## Information - -Tested and confirmed to work with PowerDNS authoritative server 3.4.8 and 4.0.1. Refer to [PowerDNS documentation](https://doc.powerdns.com/md/httpapi/README/) instructions on how to enable the built-in API interface. - -PowerDNS Notes: -- PowerDNS API does not currently support SSL, therefore you should take care to ensure that traffic between lego and the PowerDNS API is over a trusted network, VPN etc. -- In order to have the SOA serial automatically increment each time the `_acme-challenge` record is added/modified via the API, set `SOA-EDIT-API` to `INCEPTION-INCREMENT` for the zone in the `domainmetadata` table -''' - -[Configuration] - [Configuration.Credentials] - PDNS_API_KEY = "API key" - PDNS_API_URL = "API url" - [Configuration.Additional] - PDNS_POLLING_INTERVAL = "Time between DNS propagation check" - PDNS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - PDNS_TTL = "The TTL of the TXT record used for the DNS challenge" - PDNS_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://doc.powerdns.com/md/httpapi/README/" diff --git a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns_test.go b/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns_test.go deleted file mode 100644 index c87c101..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns_test.go +++ /dev/null @@ -1,143 +0,0 @@ -package pdns - -import ( - "net/url" - "testing" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "PDNS_API_URL", - "PDNS_API_KEY"). - WithDomain("PDNS_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "PDNS_API_KEY": "123", - "PDNS_API_URL": "http://example.com", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "PDNS_API_KEY": "", - "PDNS_API_URL": "", - }, - expected: "pdns: some credentials information are missing: PDNS_API_KEY,PDNS_API_URL", - }, - { - desc: "missing api key", - envVars: map[string]string{ - "PDNS_API_KEY": "", - "PDNS_API_URL": "http://example.com", - }, - expected: "pdns: some credentials information are missing: PDNS_API_KEY", - }, - { - desc: "missing API URL", - envVars: map[string]string{ - "PDNS_API_KEY": "123", - "PDNS_API_URL": "", - }, - expected: "pdns: some credentials information are missing: PDNS_API_URL", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - host *url.URL - expected string - }{ - { - desc: "success", - apiKey: "123", - host: func() *url.URL { - u, _ := url.Parse("http://example.com") - return u - }(), - }, - { - desc: "missing credentials", - expected: "pdns: API key missing", - }, - { - desc: "missing API key", - apiKey: "", - host: func() *url.URL { - u, _ := url.Parse("http://example.com") - return u - }(), - expected: "pdns: API key missing", - }, - { - desc: "missing host", - apiKey: "123", - expected: "pdns: API URL missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.Host = test.host - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresentAndCleanup(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/client.go b/vendor/github.com/go-acme/lego/providers/dns/rackspace/client.go deleted file mode 100644 index ce9b2de..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/client.go +++ /dev/null @@ -1,205 +0,0 @@ -package rackspace - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - - "github.com/go-acme/lego/challenge/dns01" -) - -// APIKeyCredentials API credential -type APIKeyCredentials struct { - Username string `json:"username"` - APIKey string `json:"apiKey"` -} - -// Auth auth credentials -type Auth struct { - APIKeyCredentials `json:"RAX-KSKEY:apiKeyCredentials"` -} - -// AuthData Auth data -type AuthData struct { - Auth `json:"auth"` -} - -// Identity Identity -type Identity struct { - Access Access `json:"access"` -} - -// Access Access -type Access struct { - ServiceCatalog []ServiceCatalog `json:"serviceCatalog"` - Token Token `json:"token"` -} - -// Token Token -type Token struct { - ID string `json:"id"` -} - -// ServiceCatalog ServiceCatalog -type ServiceCatalog struct { - Endpoints []Endpoint `json:"endpoints"` - Name string `json:"name"` -} - -// Endpoint Endpoint -type Endpoint struct { - PublicURL string `json:"publicURL"` - TenantID string `json:"tenantId"` -} - -// ZoneSearchResponse represents the response when querying Rackspace DNS zones -type ZoneSearchResponse struct { - TotalEntries int `json:"totalEntries"` - HostedZones []HostedZone `json:"domains"` -} - -// HostedZone HostedZone -type HostedZone struct { - ID int `json:"id"` - Name string `json:"name"` -} - -// Records is the list of records sent/received from the DNS API -type Records struct { - Record []Record `json:"records"` -} - -// Record represents a Rackspace DNS record -type Record struct { - Name string `json:"name"` - Type string `json:"type"` - Data string `json:"data"` - TTL int `json:"ttl,omitempty"` - ID string `json:"id,omitempty"` -} - -// getHostedZoneID performs a lookup to get the DNS zone which needs -// modifying for a given FQDN -func (d *DNSProvider) getHostedZoneID(fqdn string) (int, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return 0, err - } - - result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains?name=%s", dns01.UnFqdn(authZone)), nil) - if err != nil { - return 0, err - } - - var zoneSearchResponse ZoneSearchResponse - err = json.Unmarshal(result, &zoneSearchResponse) - if err != nil { - return 0, err - } - - // If nothing was returned, or for whatever reason more than 1 was returned (the search uses exact match, so should not occur) - if zoneSearchResponse.TotalEntries != 1 { - return 0, fmt.Errorf("found %d zones for %s in Rackspace for domain %s", zoneSearchResponse.TotalEntries, authZone, fqdn) - } - - return zoneSearchResponse.HostedZones[0].ID, nil -} - -// findTxtRecord searches a DNS zone for a TXT record with a specific name -func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) { - result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains/%d/records?type=TXT&name=%s", zoneID, dns01.UnFqdn(fqdn)), nil) - if err != nil { - return nil, err - } - - var records Records - err = json.Unmarshal(result, &records) - if err != nil { - return nil, err - } - - switch len(records.Record) { - case 1: - case 0: - return nil, fmt.Errorf("no TXT record found for %s", fqdn) - default: - return nil, fmt.Errorf("more than 1 TXT record found for %s", fqdn) - } - - return &records.Record[0], nil -} - -// makeRequest is a wrapper function used for making DNS API requests -func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) { - url := d.cloudDNSEndpoint + uri - - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - req.Header.Set("X-Auth-Token", d.token) - req.Header.Set("Content-Type", "application/json") - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error querying DNS API: %v", err) - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted { - return nil, fmt.Errorf("request failed for %s %s. Response code: %d", method, url, resp.StatusCode) - } - - var r json.RawMessage - err = json.NewDecoder(resp.Body).Decode(&r) - if err != nil { - return nil, fmt.Errorf("JSON decode failed for %s %s. Response code: %d", method, url, resp.StatusCode) - } - - return r, nil -} - -func login(config *Config) (*Identity, error) { - authData := AuthData{ - Auth: Auth{ - APIKeyCredentials: APIKeyCredentials{ - Username: config.APIUser, - APIKey: config.APIKey, - }, - }, - } - - body, err := json.Marshal(authData) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(http.MethodPost, config.BaseURL, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - - resp, err := config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error querying Identity API: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("authentication failed: response code: %d", resp.StatusCode) - } - - var identity Identity - err = json.NewDecoder(resp.Body).Decode(&identity) - if err != nil { - return nil, err - } - - return &identity, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.go b/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.go deleted file mode 100644 index 91b5a56..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.go +++ /dev/null @@ -1,159 +0,0 @@ -// Package rackspace implements a DNS provider for solving the DNS-01 challenge using rackspace DNS. -package rackspace - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// defaultBaseURL represents the Identity API endpoint to call -const defaultBaseURL = "https://identity.api.rackspacecloud.com/v2.0/tokens" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIUser string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - TTL: env.GetOrDefaultInt("RACKSPACE_TTL", 300), - PropagationTimeout: env.GetOrDefaultSecond("RACKSPACE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("RACKSPACE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("RACKSPACE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -// used to store the reusable token and DNS API endpoint -type DNSProvider struct { - config *Config - token string - cloudDNSEndpoint string -} - -// NewDNSProvider returns a DNSProvider instance configured for Rackspace. -// Credentials must be passed in the environment variables: -// RACKSPACE_USER and RACKSPACE_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("RACKSPACE_USER", "RACKSPACE_API_KEY") - if err != nil { - return nil, fmt.Errorf("rackspace: %v", err) - } - - config := NewDefaultConfig() - config.APIUser = values["RACKSPACE_USER"] - config.APIKey = values["RACKSPACE_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Rackspace. -// It authenticates against the API, also grabbing the DNS Endpoint. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("rackspace: the configuration of the DNS provider is nil") - } - - if config.APIUser == "" || config.APIKey == "" { - return nil, fmt.Errorf("rackspace: credentials missing") - } - - identity, err := login(config) - if err != nil { - return nil, fmt.Errorf("rackspace: %v", err) - } - - // Iterate through the Service Catalog to get the DNS Endpoint - var dnsEndpoint string - for _, service := range identity.Access.ServiceCatalog { - if service.Name == "cloudDNS" { - dnsEndpoint = service.Endpoints[0].PublicURL - break - } - } - - if dnsEndpoint == "" { - return nil, fmt.Errorf("rackspace: failed to populate DNS endpoint, check Rackspace API for changes") - } - - return &DNSProvider{ - config: config, - token: identity.Access.Token.ID, - cloudDNSEndpoint: dnsEndpoint, - }, nil - -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - rec := Records{ - Record: []Record{{ - Name: dns01.UnFqdn(fqdn), - Type: "TXT", - Data: value, - TTL: d.config.TTL, - }}, - } - - body, err := json.Marshal(rec) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - _, err = d.makeRequest(http.MethodPost, fmt.Sprintf("/domains/%d/records", zoneID), bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - record, err := d.findTxtRecord(fqdn, zoneID) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - _, err = d.makeRequest(http.MethodDelete, fmt.Sprintf("/domains/%d/records?id=%s", zoneID, record.ID), nil) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.toml b/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.toml deleted file mode 100644 index 5688ddb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Rackspace" -Description = '''''' -URL = "https://www.rackspace.com/" -Code = "rackspace" -Since = "v0.4.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - RACKSPACE_USER = "API user" - RACKSPACE_API_KEY = "API key" - [Configuration.Additional] - RACKSPACE_POLLING_INTERVAL = "Time between DNS propagation check" - RACKSPACE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - RACKSPACE_TTL = "The TTL of the TXT record used for the DNS challenge" - RACKSPACE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://developer.rackspace.com/docs/cloud-dns/v1/" diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace_mock_test.go b/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace_mock_test.go deleted file mode 100644 index 0874543..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace_mock_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package rackspace - -const recordDeleteMock = ` -{ - "status": "RUNNING", - "verb": "DELETE", - "jobId": "00000000-0000-0000-0000-0000000000", - "callbackUrl": "https://dns.api.rackspacecloud.com/v1.0/123456/status/00000000-0000-0000-0000-0000000000", - "requestUrl": "https://dns.api.rackspacecloud.com/v1.0/123456/domains/112233/recordsid=TXT-654321" -} -` - -const recordDetailsMock = ` -{ - "records": [ - { - "name": "_acme-challenge.example.com", - "id": "TXT-654321", - "type": "TXT", - "data": "pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM", - "ttl": 300, - "updated": "1970-01-01T00:00:00.000+0000", - "created": "1970-01-01T00:00:00.000+0000" - } - ] -} -` - -const zoneDetailsMock = ` -{ - "domains": [ - { - "name": "example.com", - "id": 112233, - "emailAddress": "hostmaster@example.com", - "updated": "1970-01-01T00:00:00.000+0000", - "created": "1970-01-01T00:00:00.000+0000" - } - ], - "totalEntries": 1 -} -` - -const identityResponseMock = ` -{ - "access": { - "token": { - "id": "testToken", - "expires": "1970-01-01T00:00:00.000Z", - "tenant": { - "id": "123456", - "name": "123456" - }, - "RAX-AUTH:authenticatedBy": [ - "APIKEY" - ] - }, - "serviceCatalog": [ - { - "type": "rax:dns", - "endpoints": [ - { - "publicURL": "https://dns.api.rackspacecloud.com/v1.0/123456", - "tenantId": "123456" - } - ], - "name": "cloudDNS" - } - ], - "user": { - "id": "fakeUseID", - "name": "testUser" - } - } -} -` - -const recordResponseMock = ` -{ - "request": "{\"records\":[{\"name\":\"_acme-challenge.example.com\",\"type\":\"TXT\",\"data\":\"pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM\",\"ttl\":300}]}", - "status": "RUNNING", - "verb": "POST", - "jobId": "00000000-0000-0000-0000-0000000000", - "callbackUrl": "https://dns.api.rackspacecloud.com/v1.0/123456/status/00000000-0000-0000-0000-0000000000", - "requestUrl": "https://dns.api.rackspacecloud.com/v1.0/123456/domains/112233/records" -} -` diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace_test.go b/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace_test.go deleted file mode 100644 index 2d969f1..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package rackspace - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "RACKSPACE_USER", - "RACKSPACE_API_KEY"). - WithDomain("RACKSPACE_DOMAIN") - -func TestNewDNSProviderConfig(t *testing.T) { - config, tearDown := setupTest() - defer tearDown() - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - assert.NotNil(t, provider.config) - - assert.Equal(t, provider.token, "testToken", "The token should match") -} - -func TestNewDNSProviderConfig_MissingCredErr(t *testing.T) { - _, err := NewDNSProviderConfig(NewDefaultConfig()) - assert.EqualError(t, err, "rackspace: credentials missing") -} - -func TestDNSProvider_Present(t *testing.T) { - config, tearDown := setupTest() - defer tearDown() - - provider, err := NewDNSProviderConfig(config) - - if assert.NoError(t, err) { - err = provider.Present("example.com", "token", "keyAuth") - require.NoError(t, err) - } -} - -func TestDNSProvider_CleanUp(t *testing.T) { - config, tearDown := setupTest() - defer tearDown() - - provider, err := NewDNSProviderConfig(config) - - if assert.NoError(t, err) { - err = provider.CleanUp("example.com", "token", "keyAuth") - require.NoError(t, err) - } -} - -func TestLiveNewDNSProvider_ValidEnv(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - assert.Contains(t, provider.cloudDNSEndpoint, "https://dns.api.rackspacecloud.com/v1.0/", "The endpoint URL should contain the base") -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "112233445566==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(15 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "112233445566==") - require.NoError(t, err) -} - -func setupTest() (*Config, func()) { - apiURL, tearDown := startTestServers() - - config := NewDefaultConfig() - config.APIUser = "testUser" - config.APIKey = "testKey" - config.BaseURL = apiURL - - return config, tearDown -} - -func startTestServers() (string, func()) { - dnsAPI := httptest.NewServer(dnsHandler()) - identityAPI := httptest.NewServer(identityHandler(dnsAPI.URL + "/123456")) - - return identityAPI.URL + "/", func() { - identityAPI.Close() - dnsAPI.Close() - } -} - -func identityHandler(dnsEndpoint string) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - - if string(reqBody) != `{"auth":{"RAX-KSKEY:apiKeyCredentials":{"username":"testUser","apiKey":"testKey"}}}` { - w.WriteHeader(http.StatusBadRequest) - return - } - - resp := strings.Replace(identityResponseMock, "https://dns.api.rackspacecloud.com/v1.0/123456", dnsEndpoint, 1) - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, resp) - }) -} - -func dnsHandler() *http.ServeMux { - mux := http.NewServeMux() - - // Used by `getHostedZoneID()` finding `zoneID` "?name=example.com" - mux.HandleFunc("/123456/domains", func(w http.ResponseWriter, r *http.Request) { - if r.URL.Query().Get("name") == "example.com" { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, zoneDetailsMock) - return - } - w.WriteHeader(http.StatusBadRequest) - }) - - mux.HandleFunc("/123456/domains/112233/records", func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - // Used by `Present()` creating the TXT record - case http.MethodPost: - reqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - if string(reqBody) != `{"records":[{"name":"_acme-challenge.example.com","type":"TXT","data":"pW9ZKG0xz_PCriK-nCMOjADy9eJcgGWIzkkj2fN4uZM","ttl":300}]}` { - w.WriteHeader(http.StatusBadRequest) - return - } - - w.WriteHeader(http.StatusAccepted) - fmt.Fprint(w, recordResponseMock) - // Used by `findTxtRecord()` finding `record.ID` "?type=TXT&name=_acme-challenge.example.com" - case http.MethodGet: - if r.URL.Query().Get("type") == "TXT" && r.URL.Query().Get("name") == "_acme-challenge.example.com" { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, recordDetailsMock) - return - } - w.WriteHeader(http.StatusBadRequest) - return - // Used by `CleanUp()` deleting the TXT record "?id=445566" - case http.MethodDelete: - if r.URL.Query().Get("id") == "TXT-654321" { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, recordDeleteMock) - return - } - w.WriteHeader(http.StatusBadRequest) - } - }) - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - fmt.Printf("Not Found for Request: (%+v)\n\n", r) - }) - - return mux -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.go b/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.go deleted file mode 100644 index 75e3d55..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.go +++ /dev/null @@ -1,183 +0,0 @@ -// Package rfc2136 implements a DNS provider for solving the DNS-01 challenge using the rfc2136 dynamic update. -package rfc2136 - -import ( - "errors" - "fmt" - "net" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/miekg/dns" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Nameserver string - TSIGAlgorithm string - TSIGKey string - TSIGSecret string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - SequenceInterval time.Duration - DNSTimeout time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TSIGAlgorithm: env.GetOrDefaultString("RFC2136_TSIG_ALGORITHM", dns.HmacMD5), - TTL: env.GetOrDefaultInt("RFC2136_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("RFC2136_PROPAGATION_TIMEOUT", env.GetOrDefaultSecond("RFC2136_TIMEOUT", 60*time.Second)), - PollingInterval: env.GetOrDefaultSecond("RFC2136_POLLING_INTERVAL", 2*time.Second), - SequenceInterval: env.GetOrDefaultSecond("RFC2136_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - DNSTimeout: env.GetOrDefaultSecond("RFC2136_DNS_TIMEOUT", 10*time.Second), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that -// uses dynamic DNS updates (RFC 2136) to create TXT records on a nameserver. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for rfc2136 -// dynamic update. Configured with environment variables: -// RFC2136_NAMESERVER: Network address in the form "host" or "host:port". -// RFC2136_TSIG_ALGORITHM: Defaults to hmac-md5.sig-alg.reg.int. (HMAC-MD5). -// See https://github.com/miekg/dns/blob/master/tsig.go for supported values. -// RFC2136_TSIG_KEY: Name of the secret key as defined in DNS server configuration. -// RFC2136_TSIG_SECRET: Secret key payload. -// RFC2136_PROPAGATION_TIMEOUT: DNS propagation timeout in time.ParseDuration format. (60s) -// To disable TSIG authentication, leave the RFC2136_TSIG* variables unset. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("RFC2136_NAMESERVER") - if err != nil { - return nil, fmt.Errorf("rfc2136: %v", err) - } - - config := NewDefaultConfig() - config.Nameserver = values["RFC2136_NAMESERVER"] - config.TSIGKey = env.GetOrFile("RFC2136_TSIG_KEY") - config.TSIGSecret = env.GetOrFile("RFC2136_TSIG_SECRET") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for rfc2136. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("rfc2136: the configuration of the DNS provider is nil") - } - - if config.Nameserver == "" { - return nil, fmt.Errorf("rfc2136: nameserver missing") - } - - if config.TSIGAlgorithm == "" { - config.TSIGAlgorithm = dns.HmacMD5 - } - - // Append the default DNS port if none is specified. - if _, _, err := net.SplitHostPort(config.Nameserver); err != nil { - if strings.Contains(err.Error(), "missing port") { - config.Nameserver = net.JoinHostPort(config.Nameserver, "53") - } else { - return nil, fmt.Errorf("rfc2136: %v", err) - } - } - - if len(config.TSIGKey) == 0 && len(config.TSIGSecret) > 0 || - len(config.TSIGKey) > 0 && len(config.TSIGSecret) == 0 { - config.TSIGKey = "" - config.TSIGSecret = "" - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("INSERT", fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("rfc2136: failed to insert: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("REMOVE", fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("rfc2136: failed to remove: %v", err) - } - return nil -} - -func (d *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { - // Find the zone for the given fqdn - zone, err := dns01.FindZoneByFqdnCustom(fqdn, []string{d.config.Nameserver}) - if err != nil { - return err - } - - // Create RR - rr := new(dns.TXT) - rr.Hdr = dns.RR_Header{Name: fqdn, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: uint32(ttl)} - rr.Txt = []string{value} - rrs := []dns.RR{rr} - - // Create dynamic update packet - m := new(dns.Msg) - m.SetUpdate(zone) - switch action { - case "INSERT": - // Always remove old challenge left over from who knows what. - m.RemoveRRset(rrs) - m.Insert(rrs) - case "REMOVE": - m.Remove(rrs) - default: - return fmt.Errorf("unexpected action: %s", action) - } - - // Setup client - c := &dns.Client{Timeout: d.config.DNSTimeout} - c.SingleInflight = true - - // TSIG authentication / msg signing - if len(d.config.TSIGKey) > 0 && len(d.config.TSIGSecret) > 0 { - m.SetTsig(dns.Fqdn(d.config.TSIGKey), d.config.TSIGAlgorithm, 300, time.Now().Unix()) - c.TsigSecret = map[string]string{dns.Fqdn(d.config.TSIGKey): d.config.TSIGSecret} - } - - // Send the query - reply, _, err := c.Exchange(m, d.config.Nameserver) - if err != nil { - return fmt.Errorf("DNS update failed: %v", err) - } - if reply != nil && reply.Rcode != dns.RcodeSuccess { - return fmt.Errorf("DNS update failed: server replied: %s", dns.RcodeToString[reply.Rcode]) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.toml b/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.toml deleted file mode 100644 index 6e213c8..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.toml +++ /dev/null @@ -1,23 +0,0 @@ -Name = "RFC2136" -Description = '''''' -URL = "https://tools.ietf.org/html/rfc2136" -Code = "rfc2136" -Since = "v0.3.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - RFC2136_TSIG_KEY = "Name of the secret key as defined in DNS server configuration. To disable TSIG authentication, leave the `RFC2136_TSIG*` variables unset." - RFC2136_TSIG_SECRET = "Secret key payload. To disable TSIG authentication, leave the` RFC2136_TSIG*` variables unset." - RFC2136_TSIG_ALGORITHM = "TSIG algorythm. See [miekg/dns#tsig.go](https://github.com/miekg/dns/blob/master/tsig.go) for supported values. To disable TSIG authentication, leave the `RFC2136_TSIG*` variables unset." - RFC2136_NAMESERVER = 'Network address in the form "host" or "host:port"' - [Configuration.Additional] - RFC2136_POLLING_INTERVAL = "Time between DNS propagation check" - RFC2136_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - RFC2136_TTL = "The TTL of the TXT record used for the DNS challenge" - RFC2136_DNS_TIMEOUT = "API request timeout" - RFC2136_SEQUENCE_INTERVAL = "Interval between iteration" - -[Links] - API = "https://tools.ietf.org/html/rfc2136" diff --git a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136_test.go b/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136_test.go deleted file mode 100644 index e4174e4..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136_test.go +++ /dev/null @@ -1,251 +0,0 @@ -package rfc2136 - -import ( - "bytes" - "fmt" - "net" - "strings" - "sync" - "testing" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/miekg/dns" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - envTestDomain = "123456789.www.example.com" - envTestKeyAuth = "123d==" - envTestValue = "Now36o-3BmlB623-0c1qCIUmgWVVmDJb88KGl24pqpo" - envTestFqdn = "_acme-challenge.123456789.www.example.com." - envTestZone = "example.com." - envTestTTL = 120 - envTestTsigKey = "example.com." - envTestTsigSecret = "IwBTJx9wrDp4Y1RyC3H0gA==" -) - -func TestCanaryLocalTestServer(t *testing.T) { - dns01.ClearFqdnCache() - dns.HandleFunc("example.com.", serverHandlerHello) - defer dns.HandleRemove("example.com.") - - server, addr, err := runLocalDNSTestServer(false) - require.NoError(t, err, "Failed to start test server") - defer func() { _ = server.Shutdown() }() - - c := new(dns.Client) - m := new(dns.Msg) - - m.SetQuestion("example.com.", dns.TypeTXT) - - r, _, err := c.Exchange(m, addr) - require.NoError(t, err, "Failed to communicate with test server") - assert.Len(t, r.Extra, 1, "Failed to communicate with test server") - - txt := r.Extra[0].(*dns.TXT).Txt[0] - assert.Equal(t, "Hello world", txt) -} - -func TestServerSuccess(t *testing.T) { - dns01.ClearFqdnCache() - dns.HandleFunc(envTestZone, serverHandlerReturnSuccess) - defer dns.HandleRemove(envTestZone) - - server, addr, err := runLocalDNSTestServer(false) - require.NoError(t, err, "Failed to start test server") - defer func() { _ = server.Shutdown() }() - - config := NewDefaultConfig() - config.Nameserver = addr - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = provider.Present(envTestDomain, "", envTestKeyAuth) - require.NoError(t, err) -} - -func TestServerError(t *testing.T) { - dns01.ClearFqdnCache() - dns.HandleFunc(envTestZone, serverHandlerReturnErr) - defer dns.HandleRemove(envTestZone) - - server, addr, err := runLocalDNSTestServer(false) - require.NoError(t, err, "Failed to start test server") - defer func() { _ = server.Shutdown() }() - - config := NewDefaultConfig() - config.Nameserver = addr - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = provider.Present(envTestDomain, "", envTestKeyAuth) - require.Error(t, err) - if !strings.Contains(err.Error(), "NOTZONE") { - t.Errorf("Expected Present() to return an error with the 'NOTZONE' rcode string but it did not: %v", err) - } -} - -func TestTsigClient(t *testing.T) { - dns01.ClearFqdnCache() - dns.HandleFunc(envTestZone, serverHandlerReturnSuccess) - defer dns.HandleRemove(envTestZone) - - server, addr, err := runLocalDNSTestServer(true) - require.NoError(t, err, "Failed to start test server") - defer func() { _ = server.Shutdown() }() - - config := NewDefaultConfig() - config.Nameserver = addr - config.TSIGKey = envTestTsigKey - config.TSIGSecret = envTestTsigSecret - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = provider.Present(envTestDomain, "", envTestKeyAuth) - require.NoError(t, err) -} - -func TestValidUpdatePacket(t *testing.T) { - var reqChan = make(chan *dns.Msg, 10) - - dns01.ClearFqdnCache() - dns.HandleFunc(envTestZone, serverHandlerPassBackRequest(reqChan)) - defer dns.HandleRemove(envTestZone) - - server, addr, err := runLocalDNSTestServer(false) - require.NoError(t, err, "Failed to start test server") - defer func() { _ = server.Shutdown() }() - - txtRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN TXT %s", envTestFqdn, envTestTTL, envTestValue)) - rrs := []dns.RR{txtRR} - m := new(dns.Msg) - m.SetUpdate(envTestZone) - m.RemoveRRset(rrs) - m.Insert(rrs) - expectStr := m.String() - - expect, err := m.Pack() - require.NoError(t, err, "error packing") - - config := NewDefaultConfig() - config.Nameserver = addr - - provider, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = provider.Present(envTestDomain, "", "1234d==") - require.NoError(t, err) - - rcvMsg := <-reqChan - rcvMsg.Id = m.Id - - actual, err := rcvMsg.Pack() - require.NoError(t, err, "error packing") - - if !bytes.Equal(actual, expect) { - tmp := new(dns.Msg) - if err := tmp.Unpack(actual); err != nil { - t.Fatalf("Error unpacking actual msg: %v", err) - } - t.Errorf("Expected msg:\n%s", expectStr) - t.Errorf("Actual msg:\n%v", tmp) - } -} - -func runLocalDNSTestServer(tsig bool) (*dns.Server, string, error) { - pc, err := net.ListenPacket("udp", "127.0.0.1:0") - if err != nil { - return nil, "", err - } - - server := &dns.Server{ - PacketConn: pc, - ReadTimeout: time.Hour, - WriteTimeout: time.Hour, - MsgAcceptFunc: func(dh dns.Header) dns.MsgAcceptAction { - // bypass defaultMsgAcceptFunc to allow dynamic update (https://github.com/miekg/dns/pull/830) - return dns.MsgAccept - }} - - if tsig { - server.TsigSecret = map[string]string{envTestTsigKey: envTestTsigSecret} - } - - waitLock := sync.Mutex{} - waitLock.Lock() - server.NotifyStartedFunc = waitLock.Unlock - - go func() { - _ = server.ActivateAndServe() - pc.Close() - }() - - waitLock.Lock() - return server, pc.LocalAddr().String(), nil -} - -func serverHandlerHello(w dns.ResponseWriter, req *dns.Msg) { - m := new(dns.Msg) - m.SetReply(req) - m.Extra = make([]dns.RR, 1) - m.Extra[0] = &dns.TXT{ - Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0}, - Txt: []string{"Hello world"}, - } - _ = w.WriteMsg(m) -} - -func serverHandlerReturnSuccess(w dns.ResponseWriter, req *dns.Msg) { - m := new(dns.Msg) - m.SetReply(req) - if req.Opcode == dns.OpcodeQuery && req.Question[0].Qtype == dns.TypeSOA && req.Question[0].Qclass == dns.ClassINET { - // Return SOA to appease findZoneByFqdn() - soaRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN SOA ns1.%s admin.%s 2016022801 28800 7200 2419200 1200", envTestZone, envTestTTL, envTestZone, envTestZone)) - m.Answer = []dns.RR{soaRR} - } - - if t := req.IsTsig(); t != nil { - if w.TsigStatus() == nil { - // Validated - m.SetTsig(envTestZone, dns.HmacMD5, 300, time.Now().Unix()) - } - } - - _ = w.WriteMsg(m) -} - -func serverHandlerReturnErr(w dns.ResponseWriter, req *dns.Msg) { - m := new(dns.Msg) - m.SetRcode(req, dns.RcodeNotZone) - _ = w.WriteMsg(m) -} - -func serverHandlerPassBackRequest(reqChan chan *dns.Msg) func(w dns.ResponseWriter, req *dns.Msg) { - return func(w dns.ResponseWriter, req *dns.Msg) { - m := new(dns.Msg) - m.SetReply(req) - if req.Opcode == dns.OpcodeQuery && req.Question[0].Qtype == dns.TypeSOA && req.Question[0].Qclass == dns.ClassINET { - // Return SOA to appease findZoneByFqdn() - soaRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN SOA ns1.%s admin.%s 2016022801 28800 7200 2419200 1200", envTestZone, envTestTTL, envTestZone, envTestZone)) - m.Answer = []dns.RR{soaRR} - } - - if t := req.IsTsig(); t != nil { - if w.TsigStatus() == nil { - // Validated - m.SetTsig(envTestZone, dns.HmacMD5, 300, time.Now().Unix()) - } - } - - _ = w.WriteMsg(m) - if req.Opcode != dns.OpcodeQuery || req.Question[0].Qtype != dns.TypeSOA || req.Question[0].Qclass != dns.ClassINET { - // Only talk back when it is not the SOA RR. - reqChan <- req - } - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/fixtures_test.go b/vendor/github.com/go-acme/lego/providers/dns/route53/fixtures_test.go deleted file mode 100644 index 444a880..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/fixtures_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package route53 - -const ChangeResourceRecordSetsResponse = ` - - - /change/123456 - PENDING - 2016-02-10T01:36:41.958Z - -` - -const ListHostedZonesByNameResponse = ` - - - - /hostedzone/ABCDEFG - example.com. - D2224C5B-684A-DB4A-BB9A-E09E3BAFEA7A - - Test comment - false - - 10 - - - true - example2.com - ZLT12321321124 - 1 -` - -const GetChangeResponse = ` - - - 123456 - INSYNC - 2016-02-10T01:36:41.958Z - -` diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/mock_test.go b/vendor/github.com/go-acme/lego/providers/dns/route53/mock_test.go deleted file mode 100644 index 79b0bba..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/mock_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package route53 - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -// MockResponse represents a predefined response used by a mock server -type MockResponse struct { - StatusCode int - Body string -} - -// MockResponseMap maps request paths to responses -type MockResponseMap map[string]MockResponse - -func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - path := r.URL.Path - resp, ok := responses[path] - if !ok { - resp, ok = responses[r.RequestURI] - if !ok { - msg := fmt.Sprintf("Requested path not found in response map: %s", path) - require.FailNow(t, msg) - } - } - - w.Header().Set("Content-Type", "application/xml") - w.WriteHeader(resp.StatusCode) - _, err := w.Write([]byte(resp.Body)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - })) - - time.Sleep(100 * time.Millisecond) - return ts -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/route53.go b/vendor/github.com/go-acme/lego/providers/dns/route53/route53.go deleted file mode 100644 index 6d06de7..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/route53.go +++ /dev/null @@ -1,279 +0,0 @@ -// Package route53 implements a DNS provider for solving the DNS-01 challenge using AWS Route 53 DNS. -package route53 - -import ( - "errors" - "fmt" - "math/rand" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/route53" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/platform/wait" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - MaxRetries int - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HostedZoneID string -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - MaxRetries: env.GetOrDefaultInt("AWS_MAX_RETRIES", 5), - TTL: env.GetOrDefaultInt("AWS_TTL", 10), - PropagationTimeout: env.GetOrDefaultSecond("AWS_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("AWS_POLLING_INTERVAL", 4*time.Second), - HostedZoneID: env.GetOrFile("AWS_HOSTED_ZONE_ID"), - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - client *route53.Route53 - config *Config -} - -// customRetryer implements the client.Retryer interface by composing the DefaultRetryer. -// It controls the logic for retrying recoverable request errors (e.g. when rate limits are exceeded). -type customRetryer struct { - client.DefaultRetryer -} - -// RetryRules overwrites the DefaultRetryer's method. -// It uses a basic exponential backoff algorithm: -// that returns an initial delay of ~400ms with an upper limit of ~30 seconds, -// which should prevent causing a high number of consecutive throttling errors. -// For reference: Route 53 enforces an account-wide(!) 5req/s query limit. -func (d customRetryer) RetryRules(r *request.Request) time.Duration { - retryCount := r.RetryCount - if retryCount > 7 { - retryCount = 7 - } - - delay := (1 << uint(retryCount)) * (rand.Intn(50) + 200) - return time.Duration(delay) * time.Millisecond -} - -// NewDNSProvider returns a DNSProvider instance configured for the AWS Route 53 service. -// -// AWS Credentials are automatically detected in the following locations and prioritized in the following order: -// 1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, -// AWS_REGION, [AWS_SESSION_TOKEN] -// 2. Shared credentials file (defaults to ~/.aws/credentials) -// 3. Amazon EC2 IAM role -// -// If AWS_HOSTED_ZONE_ID is not set, Lego tries to determine the correct public hosted zone via the FQDN. -// -// See also: https://github.com/aws/aws-sdk-go/wiki/configuring-sdk -func NewDNSProvider() (*DNSProvider, error) { - return NewDNSProviderConfig(NewDefaultConfig()) -} - -// NewDNSProviderConfig takes a given config ans returns a custom configured DNSProvider instance -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("route53: the configuration of the Route53 DNS provider is nil") - } - - retry := customRetryer{} - retry.NumMaxRetries = config.MaxRetries - sessionCfg := request.WithRetryer(aws.NewConfig(), retry) - - sess, err := session.NewSessionWithOptions(session.Options{Config: *sessionCfg}) - if err != nil { - return nil, err - } - - cl := route53.New(sess) - return &DNSProvider{client: cl, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - hostedZoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("route53: failed to determine hosted zone ID: %v", err) - } - - records, err := d.getExistingRecordSets(hostedZoneID, fqdn) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - - realValue := `"` + value + `"` - - var found bool - for _, record := range records { - if aws.StringValue(record.Value) == realValue { - found = true - } - } - - if !found { - records = append(records, &route53.ResourceRecord{Value: aws.String(realValue)}) - } - - recordSet := &route53.ResourceRecordSet{ - Name: aws.String(fqdn), - Type: aws.String("TXT"), - TTL: aws.Int64(int64(d.config.TTL)), - ResourceRecords: records, - } - - err = d.changeRecord(route53.ChangeActionUpsert, hostedZoneID, recordSet) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - hostedZoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("failed to determine Route 53 hosted zone ID: %v", err) - } - - records, err := d.getExistingRecordSets(hostedZoneID, fqdn) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - - if len(records) == 0 { - return nil - } - - recordSet := &route53.ResourceRecordSet{ - Name: aws.String(fqdn), - Type: aws.String("TXT"), - TTL: aws.Int64(int64(d.config.TTL)), - ResourceRecords: records, - } - - err = d.changeRecord(route53.ChangeActionDelete, hostedZoneID, recordSet) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - return nil -} - -func (d *DNSProvider) changeRecord(action, hostedZoneID string, recordSet *route53.ResourceRecordSet) error { - recordSetInput := &route53.ChangeResourceRecordSetsInput{ - HostedZoneId: aws.String(hostedZoneID), - ChangeBatch: &route53.ChangeBatch{ - Comment: aws.String("Managed by Lego"), - Changes: []*route53.Change{{ - Action: aws.String(action), - ResourceRecordSet: recordSet, - }}, - }, - } - - resp, err := d.client.ChangeResourceRecordSets(recordSetInput) - if err != nil { - return fmt.Errorf("failed to change record set: %v", err) - } - - changeID := resp.ChangeInfo.Id - - return wait.For("route53", d.config.PropagationTimeout, d.config.PollingInterval, func() (bool, error) { - reqParams := &route53.GetChangeInput{Id: changeID} - - resp, err := d.client.GetChange(reqParams) - if err != nil { - return false, fmt.Errorf("failed to query change status: %v", err) - } - - if aws.StringValue(resp.ChangeInfo.Status) == route53.ChangeStatusInsync { - return true, nil - } - return false, fmt.Errorf("unable to retrieve change: ID=%s", aws.StringValue(changeID)) - }) -} - -func (d *DNSProvider) getExistingRecordSets(hostedZoneID string, fqdn string) ([]*route53.ResourceRecord, error) { - listInput := &route53.ListResourceRecordSetsInput{ - HostedZoneId: aws.String(hostedZoneID), - StartRecordName: aws.String(fqdn), - StartRecordType: aws.String("TXT"), - } - - recordSetsOutput, err := d.client.ListResourceRecordSets(listInput) - if err != nil { - return nil, err - } - - if recordSetsOutput == nil { - return nil, nil - } - - var records []*route53.ResourceRecord - - for _, recordSet := range recordSetsOutput.ResourceRecordSets { - if aws.StringValue(recordSet.Name) == fqdn { - records = append(records, recordSet.ResourceRecords...) - } - } - - return records, nil -} - -func (d *DNSProvider) getHostedZoneID(fqdn string) (string, error) { - if d.config.HostedZoneID != "" { - return d.config.HostedZoneID, nil - } - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - // .DNSName should not have a trailing dot - reqParams := &route53.ListHostedZonesByNameInput{ - DNSName: aws.String(dns01.UnFqdn(authZone)), - } - resp, err := d.client.ListHostedZonesByName(reqParams) - if err != nil { - return "", err - } - - var hostedZoneID string - for _, hostedZone := range resp.HostedZones { - // .Name has a trailing dot - if !aws.BoolValue(hostedZone.Config.PrivateZone) && aws.StringValue(hostedZone.Name) == authZone { - hostedZoneID = aws.StringValue(hostedZone.Id) - break - } - } - - if len(hostedZoneID) == 0 { - return "", fmt.Errorf("zone %s not found for domain %s", authZone, fqdn) - } - - if strings.HasPrefix(hostedZoneID, "/hostedzone/") { - hostedZoneID = strings.TrimPrefix(hostedZoneID, "/hostedzone/") - } - - return hostedZoneID, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/route53.toml b/vendor/github.com/go-acme/lego/providers/dns/route53/route53.toml deleted file mode 100644 index b6e8776..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/route53.toml +++ /dev/null @@ -1,69 +0,0 @@ -Name = "Amazon Route 53" -Description = '''''' -URL = "https://aws.amazon.com/route53/" -Code = "route53" -Since = "v0.3.0" - -Example = '''''' - -Additional = ''' -## Description - -AWS Credentials are automatically detected in the following locations and prioritized in the following order: - -1. Environment variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, [`AWS_SESSION_TOKEN`] -2. Shared credentials file (defaults to `~/.aws/credentials`) -3. Amazon EC2 IAM role - -If `AWS_HOSTED_ZONE_ID` is not set, Lego tries to determine the correct public hosted zone via the FQDN. - -See also: [sessions](https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/sessions.html) - -## Policy - -The following AWS IAM policy document describes the permissions required for lego to complete the DNS challenge. - -```json -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "", - "Effect": "Allow", - "Action": [ - "route53:GetChange", - "route53:ChangeResourceRecordSets", - "route53:ListResourceRecordSets" - ], - "Resource": [ - "arn:aws:route53:::hostedzone/*", - "arn:aws:route53:::change/*" - ] - }, - { - "Sid": "", - "Effect": "Allow", - "Action": "route53:ListHostedZonesByName", - "Resource": "*" - } - ] -} -``` - -''' - -[Configuration] - [Configuration.Credentials] - AWS_ACCESS_KEY_ID = "Managed by the AWS client" - AWS_SECRET_ACCESS_KEY = "Managed by the AWS client" - AWS_REGION = "Managed by the AWS client" - AWS_HOSTED_ZONE_ID = "Override the hosted zone ID" - [Configuration.Additional] - AWS_MAX_RETRIES = "The number of maximum returns the service will use to make an individual API request" - AWS_POLLING_INTERVAL = "Time between DNS propagation check" - AWS_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - AWS_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://docs.aws.amazon.com/Route53/latest/APIReference/API_Operations_Amazon_Route_53.html" - GoClient = "https://github.com/aws/aws-sdk-go/aws" diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/route53_integration_test.go b/vendor/github.com/go-acme/lego/providers/dns/route53/route53_integration_test.go deleted file mode 100644 index acc301b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/route53_integration_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package route53 - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/route53" - "github.com/stretchr/testify/require" -) - -func TestLiveTTL(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - - provider, err := NewDNSProvider() - require.NoError(t, err) - - domain := envTest.GetDomain() - - err = provider.Present(domain, "foo", "bar") - require.NoError(t, err) - - // we need a separate R53 client here as the one in the DNS provider is unexported. - fqdn := "_acme-challenge." + domain + "." - sess, err := session.NewSession() - require.NoError(t, err) - svc := route53.New(sess) - - defer func() { - errC := provider.CleanUp(domain, "foo", "bar") - if errC != nil { - t.Log(errC) - } - }() - - zoneID, err := provider.getHostedZoneID(fqdn) - require.NoError(t, err) - - params := &route53.ListResourceRecordSetsInput{ - HostedZoneId: aws.String(zoneID), - } - resp, err := svc.ListResourceRecordSets(params) - require.NoError(t, err) - - for _, v := range resp.ResourceRecordSets { - if aws.StringValue(v.Name) == fqdn && aws.StringValue(v.Type) == "TXT" && aws.Int64Value(v.TTL) == 10 { - return - } - } - - t.Fatalf("Could not find a TXT record for _acme-challenge.%s with a TTL of 10", domain) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/route53_test.go b/vendor/github.com/go-acme/lego/providers/dns/route53/route53_test.go deleted file mode 100644 index 53ab2c2..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/route53_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package route53 - -import ( - "net/http/httptest" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/route53" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "AWS_ACCESS_KEY_ID", - "AWS_SECRET_ACCESS_KEY", - "AWS_REGION", - "AWS_HOSTED_ZONE_ID", - "AWS_MAX_RETRIES", - "AWS_TTL", - "AWS_PROPAGATION_TIMEOUT", - "AWS_POLLING_INTERVAL"). - WithDomain("R53_DOMAIN"). - WithLiveTestRequirements("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION", "R53_DOMAIN") - -func makeTestProvider(ts *httptest.Server) *DNSProvider { - config := &aws.Config{ - Credentials: credentials.NewStaticCredentials("abc", "123", " "), - Endpoint: aws.String(ts.URL), - Region: aws.String("mock-region"), - MaxRetries: aws.Int(1), - } - - sess, err := session.NewSession(config) - if err != nil { - panic(err) - } - client := route53.New(sess) - cfg := NewDefaultConfig() - return &DNSProvider{client: client, config: cfg} -} - -func Test_loadCredentials_FromEnv(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - os.Setenv("AWS_ACCESS_KEY_ID", "123") - os.Setenv("AWS_SECRET_ACCESS_KEY", "456") - os.Setenv("AWS_REGION", "us-east-1") - - config := &aws.Config{ - CredentialsChainVerboseErrors: aws.Bool(true), - } - - sess, err := session.NewSession(config) - require.NoError(t, err) - - value, err := sess.Config.Credentials.Get() - require.NoError(t, err, "Expected credentials to be set from environment") - - expected := credentials.Value{ - AccessKeyID: "123", - SecretAccessKey: "456", - SessionToken: "", - ProviderName: "EnvConfigCredentials", - } - assert.Equal(t, expected, value) -} - -func Test_loadRegion_FromEnv(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - os.Setenv("AWS_REGION", route53.CloudWatchRegionUsEast1) - - sess, err := session.NewSession(aws.NewConfig()) - require.NoError(t, err) - - region := aws.StringValue(sess.Config.Region) - assert.Equal(t, route53.CloudWatchRegionUsEast1, region, "Region") -} - -func Test_getHostedZoneID_FromEnv(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - expectedZoneID := "zoneID" - - os.Setenv("AWS_HOSTED_ZONE_ID", expectedZoneID) - - provider, err := NewDNSProvider() - require.NoError(t, err) - - hostedZoneID, err := provider.getHostedZoneID("whatever") - require.NoError(t, err, "HostedZoneID") - - assert.Equal(t, expectedZoneID, hostedZoneID) -} - -func TestNewDefaultConfig(t *testing.T) { - defer envTest.RestoreEnv() - - testCases := []struct { - desc string - envVars map[string]string - expected *Config - }{ - { - desc: "default configuration", - expected: &Config{ - MaxRetries: 5, - TTL: 10, - PropagationTimeout: 2 * time.Minute, - PollingInterval: 4 * time.Second, - }, - }, - { - desc: "", - envVars: map[string]string{ - "AWS_MAX_RETRIES": "10", - "AWS_TTL": "99", - "AWS_PROPAGATION_TIMEOUT": "60", - "AWS_POLLING_INTERVAL": "60", - "AWS_HOSTED_ZONE_ID": "abc123", - }, - expected: &Config{ - MaxRetries: 10, - TTL: 99, - PropagationTimeout: 60 * time.Second, - PollingInterval: 60 * time.Second, - HostedZoneID: "abc123", - }, - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - envTest.ClearEnv() - for key, value := range test.envVars { - os.Setenv(key, value) - } - - config := NewDefaultConfig() - - assert.Equal(t, test.expected, config) - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - mockResponses := MockResponseMap{ - "/2013-04-01/hostedzonesbyname": {StatusCode: 200, Body: ListHostedZonesByNameResponse}, - "/2013-04-01/hostedzone/ABCDEFG/rrset/": {StatusCode: 200, Body: ChangeResourceRecordSetsResponse}, - "/2013-04-01/change/123456": {StatusCode: 200, Body: GetChangeResponse}, - "/2013-04-01/hostedzone/ABCDEFG/rrset?name=_acme-challenge.example.com.&type=TXT": { - StatusCode: 200, - Body: "", - }, - } - - ts := newMockServer(t, mockResponses) - defer ts.Close() - - defer envTest.RestoreEnv() - envTest.ClearEnv() - provider := makeTestProvider(ts) - - domain := "example.com" - keyAuth := "123456d==" - - err := provider.Present(domain, "", keyAuth) - require.NoError(t, err, "Expected Present to return no error") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client.go b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client.go deleted file mode 100644 index 10b8a1f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client.go +++ /dev/null @@ -1,106 +0,0 @@ -package sakuracloud - -import ( - "fmt" - "net/http" - "strings" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/sacloud/libsacloud/api" - "github.com/sacloud/libsacloud/sacloud" -) - -const sacloudAPILockKey = "lego/dns/sacloud" - -func (d *DNSProvider) addTXTRecord(fqdn, domain, value string, ttl int) error { - sacloud.LockByKey(sacloudAPILockKey) - defer sacloud.UnlockByKey(sacloudAPILockKey) - - zone, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("sakuracloud: %v", err) - } - - name := d.extractRecordName(fqdn, zone.Name) - - zone.AddRecord(zone.CreateNewRecord(name, "TXT", value, ttl)) - _, err = d.client.Update(zone.ID, zone) - if err != nil { - return fmt.Errorf("sakuracloud: API call failed: %v", err) - } - - return nil -} - -func (d *DNSProvider) cleanupTXTRecord(fqdn, domain string) error { - sacloud.LockByKey(sacloudAPILockKey) - defer sacloud.UnlockByKey(sacloudAPILockKey) - - zone, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("sakuracloud: %v", err) - } - - records := d.findTxtRecords(fqdn, zone) - - for _, record := range records { - var updRecords []sacloud.DNSRecordSet - for _, r := range zone.Settings.DNS.ResourceRecordSets { - if !(r.Name == record.Name && r.Type == record.Type && r.RData == record.RData) { - updRecords = append(updRecords, r) - } - } - zone.Settings.DNS.ResourceRecordSets = updRecords - } - - _, err = d.client.Update(zone.ID, zone) - if err != nil { - return fmt.Errorf("sakuracloud: API call failed: %v", err) - } - return nil -} - -func (d *DNSProvider) getHostedZone(domain string) (*sacloud.DNS, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return nil, err - } - - zoneName := dns01.UnFqdn(authZone) - - res, err := d.client.Reset().WithNameLike(zoneName).Find() - if err != nil { - if notFound, ok := err.(api.Error); ok && notFound.ResponseCode() == http.StatusNotFound { - return nil, fmt.Errorf("zone %s not found on SakuraCloud DNS: %v", zoneName, err) - } - return nil, fmt.Errorf("API call failed: %v", err) - } - - for _, zone := range res.CommonServiceDNSItems { - if zone.Name == zoneName { - return &zone, nil - } - } - - return nil, fmt.Errorf("zone %s not found", zoneName) -} - -func (d *DNSProvider) findTxtRecords(fqdn string, zone *sacloud.DNS) []sacloud.DNSRecordSet { - recordName := d.extractRecordName(fqdn, zone.Name) - - var res []sacloud.DNSRecordSet - for _, record := range zone.Settings.DNS.ResourceRecordSets { - if record.Name == recordName && record.Type == "TXT" { - res = append(res, record) - } - } - return res -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client_test.go b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client_test.go deleted file mode 100644 index e8a1c62..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package sakuracloud - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "sync" - "testing" - - "github.com/sacloud/libsacloud/api" - "github.com/sacloud/libsacloud/sacloud" - "github.com/stretchr/testify/require" -) - -type simpleResponse struct { - *sacloud.DNS `json:"CommonServiceItem,omitempty"` -} - -type apiQuery struct { - Filter struct { - Name string `json:"Name"` - ProviderClass string `json:"Provider.Class"` - } `json:"Filter"` -} - -func fakeAPIServer(handler func(rw http.ResponseWriter, req *http.Request)) func() { - mux := http.NewServeMux() - server := httptest.NewServer(mux) - - mux.HandleFunc("/is1a/api/cloud/1.1/commonserviceitem/", handler) - - backup := api.SakuraCloudAPIRoot - api.SakuraCloudAPIRoot = server.URL - return func() { - api.SakuraCloudAPIRoot = backup - } -} - -func TestDNSProvider_addTXTRecord(t *testing.T) { - searchResp := &api.SearchDNSResponse{} - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { - switch req.Method { - case http.MethodGet: - if len(searchResp.CommonServiceDNSItems) == 0 { - q := &apiQuery{} - if err := json.Unmarshal([]byte(req.URL.RawQuery), q); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - fakeZone := sacloud.CreateNewDNS(q.Filter.Name) - fakeZone.ID = 123456789012 - searchResp = &api.SearchDNSResponse{CommonServiceDNSItems: []sacloud.DNS{*fakeZone}} - } - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - case http.MethodPut: // Update - resp := &simpleResponse{} - if err := json.NewDecoder(req.Body).Decode(resp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - var items []sacloud.DNS - for _, v := range searchResp.CommonServiceDNSItems { - if resp.Name == v.Name { - items = append(items, *resp.DNS) - } else { - items = append(items, v) - } - } - searchResp.CommonServiceDNSItems = items - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - default: - http.Error(rw, "OOPS", http.StatusServiceUnavailable) - } - }) - defer tearDown() - - config := NewDefaultConfig() - config.Token = "token1" - config.Secret = "secret1" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = p.addTXTRecord("test.example.com", "example.com", "dummyValue", 10) - require.NoError(t, err) - - updZone, err := p.getHostedZone("example.com") - require.NoError(t, err) - require.NotNil(t, updZone) - - require.Len(t, updZone.Settings.DNS.ResourceRecordSets, 1) -} - -func TestDNSProvider_cleanupTXTRecord(t *testing.T) { - searchResp := &api.SearchDNSResponse{} - - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { - switch req.Method { - case http.MethodGet: - if len(searchResp.CommonServiceDNSItems) == 0 { - q := &apiQuery{} - if err := json.Unmarshal([]byte(req.URL.RawQuery), q); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - fakeZone := sacloud.CreateNewDNS(q.Filter.Name) - fakeZone.ID = 123456789012 - fakeZone.CreateNewRecord("test", "TXT", "dummyValue", 10) - searchResp = &api.SearchDNSResponse{CommonServiceDNSItems: []sacloud.DNS{*fakeZone}} - } - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - case http.MethodPut: // Update - resp := &simpleResponse{} - if err := json.NewDecoder(req.Body).Decode(resp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - var items []sacloud.DNS - for _, v := range searchResp.CommonServiceDNSItems { - if resp.Name == v.Name { - items = append(items, *resp.DNS) - } else { - items = append(items, v) - } - } - searchResp.CommonServiceDNSItems = items - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - default: - http.Error(rw, "OOPS", http.StatusServiceUnavailable) - } - }) - defer tearDown() - - config := NewDefaultConfig() - config.Token = "token2" - config.Secret = "secret2" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = p.cleanupTXTRecord("test.example.com", "example.com") - require.NoError(t, err) - - updZone, err := p.getHostedZone("example.com") - require.NoError(t, err) - require.NotNil(t, updZone) - - require.Len(t, updZone.Settings.DNS.ResourceRecordSets, 0) -} - -func TestDNSProvider_addTXTRecord_concurrent(t *testing.T) { - searchResp := &api.SearchDNSResponse{} - - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { - switch req.Method { - case http.MethodGet: - if len(searchResp.CommonServiceDNSItems) == 0 { - q := &apiQuery{} - if err := json.Unmarshal([]byte(req.URL.RawQuery), q); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - fakeZone := sacloud.CreateNewDNS(q.Filter.Name) - fakeZone.ID = 123456789012 - searchResp = &api.SearchDNSResponse{CommonServiceDNSItems: []sacloud.DNS{*fakeZone}} - } - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - case http.MethodPut: // Update - resp := &simpleResponse{} - if err := json.NewDecoder(req.Body).Decode(resp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - var items []sacloud.DNS - for _, v := range searchResp.CommonServiceDNSItems { - if resp.Name == v.Name { - items = append(items, *resp.DNS) - } else { - items = append(items, v) - } - } - searchResp.CommonServiceDNSItems = items - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - default: - http.Error(rw, "OOPS", http.StatusServiceUnavailable) - } - }) - defer tearDown() - - dummyRecordCount := 10 - - var providers []*DNSProvider - for i := 0; i < dummyRecordCount; i++ { - config := NewDefaultConfig() - config.Token = "token3" - config.Secret = "secret3" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - providers = append(providers, p) - } - - var wg sync.WaitGroup - wg.Add(len(providers)) - - for i, p := range providers { - go func(fqdn string, client *DNSProvider) { - err := client.addTXTRecord(fqdn, "example.com", "dummyValue", 10) - require.NoError(t, err) - wg.Done() - }(fmt.Sprintf("test%d.example.com", i), p) - } - - wg.Wait() - - updZone, err := providers[0].getHostedZone("example.com") - require.NoError(t, err) - require.NotNil(t, updZone) - - require.Len(t, updZone.Settings.DNS.ResourceRecordSets, dummyRecordCount) -} - -func TestDNSProvider_cleanupTXTRecord_concurrent(t *testing.T) { - dummyRecordCount := 10 - - baseFakeZone := sacloud.CreateNewDNS("example.com") - baseFakeZone.ID = 123456789012 - for i := 0; i < dummyRecordCount; i++ { - baseFakeZone.AddRecord(baseFakeZone.CreateNewRecord(fmt.Sprintf("test%d", i), "TXT", "dummyValue", 10)) - } - - searchResp := &api.SearchDNSResponse{CommonServiceDNSItems: []sacloud.DNS{*baseFakeZone}} - - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { - switch req.Method { - case http.MethodGet: - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - case http.MethodPut: // Update - resp := &simpleResponse{} - if err := json.NewDecoder(req.Body).Decode(resp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - - var items []sacloud.DNS - for _, v := range searchResp.CommonServiceDNSItems { - if resp.Name == v.Name { - items = append(items, *resp.DNS) - } else { - items = append(items, v) - } - } - searchResp.CommonServiceDNSItems = items - - if err := json.NewEncoder(rw).Encode(searchResp); err != nil { - http.Error(rw, err.Error(), http.StatusServiceUnavailable) - } - default: - http.Error(rw, "OOPS", http.StatusServiceUnavailable) - } - }) - defer tearDown() - - fakeZone := sacloud.CreateNewDNS("example.com") - fakeZone.ID = 123456789012 - for i := 0; i < dummyRecordCount; i++ { - fakeZone.AddRecord(fakeZone.CreateNewRecord(fmt.Sprintf("test%d", i), "TXT", "dummyValue", 10)) - } - - var providers []*DNSProvider - for i := 0; i < dummyRecordCount; i++ { - config := NewDefaultConfig() - config.Token = "token4" - config.Secret = "secret4" - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - providers = append(providers, p) - } - - var wg sync.WaitGroup - wg.Add(len(providers)) - - for i, p := range providers { - go func(fqdn string, client *DNSProvider) { - err := client.cleanupTXTRecord(fqdn, "example.com") - require.NoError(t, err) - wg.Done() - }(fmt.Sprintf("test%d.example.com", i), p) - } - - wg.Wait() - - updZone, err := providers[0].getHostedZone("example.com") - require.NoError(t, err) - require.NotNil(t, updZone) - - require.Len(t, updZone.Settings.DNS.ResourceRecordSets, 0) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.go b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.go deleted file mode 100644 index 87f55a0..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.go +++ /dev/null @@ -1,101 +0,0 @@ -// Package sakuracloud implements a DNS provider for solving the DNS-01 challenge using SakuraCloud DNS. -package sakuracloud - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/sacloud/libsacloud/api" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - Secret string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("SAKURACLOUD_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("SAKURACLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("SAKURACLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("SAKURACLOUD_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *api.DNSAPI -} - -// NewDNSProvider returns a DNSProvider instance configured for SakuraCloud. -// Credentials must be passed in the environment variables: SAKURACLOUD_ACCESS_TOKEN & SAKURACLOUD_ACCESS_TOKEN_SECRET -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("SAKURACLOUD_ACCESS_TOKEN", "SAKURACLOUD_ACCESS_TOKEN_SECRET") - if err != nil { - return nil, fmt.Errorf("sakuracloud: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["SAKURACLOUD_ACCESS_TOKEN"] - config.Secret = values["SAKURACLOUD_ACCESS_TOKEN_SECRET"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for SakuraCloud. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("sakuracloud: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("sakuracloud: AccessToken is missing") - } - - if config.Secret == "" { - return nil, errors.New("sakuracloud: AccessSecret is missing") - } - - apiClient := api.NewClient(config.Token, config.Secret, "is1a") - if config.HTTPClient == nil { - apiClient.HTTPClient = http.DefaultClient - } else { - apiClient.HTTPClient = config.HTTPClient - } - - return &DNSProvider{ - client: apiClient.GetDNSAPI(), - config: config, - }, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - return d.addTXTRecord(fqdn, domain, value, d.config.TTL) -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - return d.cleanupTXTRecord(fqdn, domain) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.toml b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.toml deleted file mode 100644 index 0dfcb94..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Sakura Cloud" -Description = '''''' -URL = "https://cloud.sakura.ad.jp/" -Code = "sakuracloud" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - SAKURACLOUD_ACCESS_TOKEN = "Access token" - SAKURACLOUD_ACCESS_TOKEN_SECRET = "Access token secret" - [Configuration.Additional] - SAKURACLOUD_POLLING_INTERVAL = "Time between DNS propagation check" - SAKURACLOUD_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - SAKURACLOUD_TTL = "The TTL of the TXT record used for the DNS challenge" - SAKURACLOUD_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://developer.sakura.ad.jp/cloud/api/1.1/" - GoClient = "https://github.com/sacloud/libsacloud" diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud_test.go b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud_test.go deleted file mode 100644 index 3387540..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package sakuracloud - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "SAKURACLOUD_ACCESS_TOKEN", - "SAKURACLOUD_ACCESS_TOKEN_SECRET"). - WithDomain("SAKURACLOUD_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "SAKURACLOUD_ACCESS_TOKEN": "123", - "SAKURACLOUD_ACCESS_TOKEN_SECRET": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "SAKURACLOUD_ACCESS_TOKEN": "", - "SAKURACLOUD_ACCESS_TOKEN_SECRET": "", - }, - expected: "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN,SAKURACLOUD_ACCESS_TOKEN_SECRET", - }, - { - desc: "missing access token", - envVars: map[string]string{ - "SAKURACLOUD_ACCESS_TOKEN": "", - "SAKURACLOUD_ACCESS_TOKEN_SECRET": "456", - }, - expected: "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN", - }, - { - desc: "missing token secret", - envVars: map[string]string{ - "SAKURACLOUD_ACCESS_TOKEN": "123", - "SAKURACLOUD_ACCESS_TOKEN_SECRET": "", - }, - expected: "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN_SECRET", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - token string - secret string - expected string - }{ - { - desc: "success", - token: "123", - secret: "456", - }, - { - desc: "missing credentials", - expected: "sakuracloud: AccessToken is missing", - }, - { - desc: "missing token", - secret: "456", - expected: "sakuracloud: AccessToken is missing", - }, - { - desc: "missing secret", - token: "123", - expected: "sakuracloud: AccessSecret is missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.Token = test.token - config.Secret = test.secret - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/selectel/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/selectel/internal/client.go deleted file mode 100644 index 8457bc4..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/selectel/internal/client.go +++ /dev/null @@ -1,221 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" -) - -// Domain represents domain name. -type Domain struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` -} - -// Record represents DNS record. -type Record struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` // Record type (SOA, NS, A/AAAA, CNAME, SRV, MX, TXT, SPF) - TTL int `json:"ttl,omitempty"` - Email string `json:"email,omitempty"` // Email of domain's admin (only for SOA records) - Content string `json:"content,omitempty"` // Record content (not for SRV) -} - -// APIError API error message -type APIError struct { - Description string `json:"error"` - Code int `json:"code"` - Field string `json:"field"` -} - -func (a *APIError) Error() string { - return fmt.Sprintf("API error: %d - %s - %s", a.Code, a.Description, a.Field) -} - -// ClientOpts represents options to init client. -type ClientOpts struct { - BaseURL string - Token string - UserAgent string - HTTPClient *http.Client -} - -// Client represents DNS client. -type Client struct { - baseURL string - token string - userAgent string - httpClient *http.Client -} - -// NewClient returns a client instance. -func NewClient(opts ClientOpts) *Client { - if opts.HTTPClient == nil { - opts.HTTPClient = &http.Client{} - } - - return &Client{ - token: opts.Token, - baseURL: opts.BaseURL, - httpClient: opts.HTTPClient, - userAgent: opts.UserAgent, - } -} - -// GetDomainByName gets Domain object by its name. If `domainName` level > 2 and there is -// no such domain on the account - it'll recursively search for the first -// which is exists in Selectel Domain API. -func (c *Client) GetDomainByName(domainName string) (*Domain, error) { - uri := fmt.Sprintf("/%s", domainName) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - domain := &Domain{} - resp, err := c.do(req, domain) - if err != nil { - switch { - case resp.StatusCode == http.StatusNotFound && strings.Count(domainName, ".") > 1: - // Look up for the next sub domain - subIndex := strings.Index(domainName, ".") - return c.GetDomainByName(domainName[subIndex+1:]) - default: - return nil, err - } - } - - return domain, nil -} - -// AddRecord adds Record for given domain. -func (c *Client) AddRecord(domainID int, body Record) (*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodPost, uri, body) - if err != nil { - return nil, err - } - - record := &Record{} - _, err = c.do(req, record) - if err != nil { - return nil, err - } - - return record, nil -} - -// ListRecords returns list records for specific domain. -func (c *Client) ListRecords(domainID int) ([]*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - var records []*Record - _, err = c.do(req, &records) - if err != nil { - return nil, err - } - return records, nil -} - -// DeleteRecord deletes specific record. -func (c *Client) DeleteRecord(domainID, recordID int) error { - uri := fmt.Sprintf("/%d/records/%d", domainID, recordID) - req, err := c.newRequest(http.MethodDelete, uri, nil) - if err != nil { - return err - } - - _, err = c.do(req, nil) - return err -} - -func (c *Client) newRequest(method, uri string, body interface{}) (*http.Request, error) { - buf := new(bytes.Buffer) - - if body != nil { - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, fmt.Errorf("failed to encode request body with error: %v", err) - } - } - - req, err := http.NewRequest(method, c.baseURL+uri, buf) - if err != nil { - return nil, fmt.Errorf("failed to create new http request with error: %v", err) - } - - req.Header.Add("X-Token", c.token) - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - - return req, nil -} - -func (c *Client) do(req *http.Request, to interface{}) (*http.Response, error) { - resp, err := c.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("request failed with error: %v", err) - } - - err = checkResponse(resp) - if err != nil { - return resp, err - } - - if to != nil { - if err = unmarshalBody(resp, to); err != nil { - return resp, err - } - } - - return resp, nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode >= http.StatusBadRequest && - resp.StatusCode <= http.StatusNetworkAuthenticationRequired { - - if resp.Body == nil { - return fmt.Errorf("request failed with status code %d and empty body", resp.StatusCode) - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - apiError := APIError{} - err = json.Unmarshal(body, &apiError) - if err != nil { - return fmt.Errorf("request failed with status code %d, response body: %s", resp.StatusCode, string(body)) - } - - return fmt.Errorf("request failed with status code %d: %v", resp.StatusCode, apiError) - } - - return nil -} - -func unmarshalBody(resp *http.Response, to interface{}) error { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - err = json.Unmarshal(body, to) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.go b/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.go deleted file mode 100644 index 83abe25..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.go +++ /dev/null @@ -1,154 +0,0 @@ -// Package selectel implements a DNS provider for solving the DNS-01 challenge using Selectel Domains API. -// Selectel Domain API reference: https://kb.selectel.com/23136054.html -// Token: https://my.selectel.ru/profile/apikeys -package selectel - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/selectel/internal" -) - -const ( - defaultBaseURL = "https://api.selectel.ru/domains/v1" - minTTL = 60 -) - -const ( - envNamespace = "SELECTEL_" - baseURLEnvVar = envNamespace + "BASE_URL" - apiTokenEnvVar = envNamespace + "API_TOKEN" - ttlEnvVar = envNamespace + "TTL" - propagationTimeoutEnvVar = envNamespace + "PROPAGATION_TIMEOUT" - pollingIntervalEnvVar = envNamespace + "POLLING_INTERVAL" - httpTimeoutEnvVar = envNamespace + "HTTP_TIMEOUT" -) - -// Config is used to configure the creation of the DNSProvider. -type Config struct { - BaseURL string - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider. -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: env.GetOrDefaultString(baseURLEnvVar, defaultBaseURL), - TTL: env.GetOrDefaultInt(ttlEnvVar, minTTL), - PropagationTimeout: env.GetOrDefaultSecond(propagationTimeoutEnvVar, 120*time.Second), - PollingInterval: env.GetOrDefaultSecond(pollingIntervalEnvVar, 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond(httpTimeoutEnvVar, 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Selectel Domains API. -// API token must be passed in the environment variable SELECTEL_API_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(apiTokenEnvVar) - if err != nil { - return nil, fmt.Errorf("selectel: %v", err) - } - - config := NewDefaultConfig() - config.Token = values[apiTokenEnvVar] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for selectel. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("selectel: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("selectel: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("selectel: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client := internal.NewClient(internal.ClientOpts{ - BaseURL: config.BaseURL, - Token: config.Token, - HTTPClient: config.HTTPClient, - }) - - return &DNSProvider{config: config, client: client}, nil -} - -// Timeout returns the Timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill DNS-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - txtRecord := internal.Record{ - Type: "TXT", - TTL: d.config.TTL, - Name: fqdn, - Content: value, - } - _, err = d.client.AddRecord(domainObj.ID, txtRecord) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - return nil -} - -// CleanUp removes a TXT record used for DNS-01 challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - recordName := dns01.UnFqdn(fqdn) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - records, err := d.client.ListRecords(domainObj.ID) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - // Delete records with specific FQDN - var lastErr error - for _, record := range records { - if record.Name == recordName { - err = d.client.DeleteRecord(domainObj.ID, record.ID) - if err != nil { - lastErr = fmt.Errorf("selectel: %v", err) - } - } - } - - return lastErr -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.toml b/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.toml deleted file mode 100644 index 2d9ee48..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Selectel" -Description = '''''' -URL = "https://kb.selectel.com/" -Code = "selectel" -Since = "v1.2.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - SELECTEL_API_TOKEN = "API token" - [Configuration.Additional] - SELECTEL_BASE_URL = "API endpoint URL" - SELECTEL_POLLING_INTERVAL = "Time between DNS propagation check" - SELECTEL_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - SELECTEL_TTL = "The TTL of the TXT record used for the DNS challenge" - SELECTEL_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://kb.selectel.com/23136054.html" diff --git a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel_test.go b/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel_test.go deleted file mode 100644 index 09b02df..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package selectel - -import ( - "fmt" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest(apiTokenEnvVar, ttlEnvVar) - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - apiTokenEnvVar: "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - apiTokenEnvVar: "", - }, - expected: fmt.Sprintf("selectel: some credentials information are missing: %s", apiTokenEnvVar), - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - token string - ttl int - expected string - }{ - { - desc: "success", - token: "123", - ttl: 60, - }, - { - desc: "missing api key", - token: "", - ttl: 60, - expected: "selectel: credentials missing", - }, - { - desc: "bad TTL value", - token: "123", - ttl: 59, - expected: fmt.Sprintf("selectel: invalid TTL, TTL (59) must be greater than %d", minTTL), - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.TTL = test.ttl - config.Token = test.token - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/stackpath/client.go b/vendor/github.com/go-acme/lego/providers/dns/stackpath/client.go deleted file mode 100644 index 141c4f4..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/stackpath/client.go +++ /dev/null @@ -1,217 +0,0 @@ -package stackpath - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "path" - - "github.com/go-acme/lego/challenge/dns01" - "golang.org/x/net/publicsuffix" -) - -// Zones is the response struct from the Stackpath api GetZones -type Zones struct { - Zones []Zone `json:"zones"` -} - -// Zone a DNS zone representation -type Zone struct { - ID string - Domain string -} - -// Records is the response struct from the Stackpath api GetZoneRecords -type Records struct { - Records []Record `json:"records"` -} - -// Record a DNS record representation -type Record struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - TTL int `json:"ttl"` - Data string `json:"data"` -} - -// ErrorResponse the API error response representation -type ErrorResponse struct { - Code int `json:"code"` - Message string `json:"error"` -} - -func (e *ErrorResponse) Error() string { - return fmt.Sprintf("%d %s", e.Code, e.Message) -} - -// https://developer.stackpath.com/en/api/dns/#operation/GetZones -func (d *DNSProvider) getZones(domain string) (*Zone, error) { - domain = dns01.UnFqdn(domain) - tld, err := publicsuffix.EffectiveTLDPlusOne(domain) - if err != nil { - return nil, err - } - - req, err := d.newRequest(http.MethodGet, "/zones", nil) - if err != nil { - return nil, err - } - - query := req.URL.Query() - query.Add("page_request.filter", fmt.Sprintf("domain='%s'", tld)) - req.URL.RawQuery = query.Encode() - - var zones Zones - err = d.do(req, &zones) - if err != nil { - return nil, err - } - - if len(zones.Zones) == 0 { - return nil, fmt.Errorf("did not find zone with domain %s", domain) - } - - return &zones.Zones[0], nil -} - -// https://developer.stackpath.com/en/api/dns/#operation/GetZoneRecords -func (d *DNSProvider) getZoneRecords(name string, zone *Zone) ([]Record, error) { - u := fmt.Sprintf("/zones/%s/records", zone.ID) - req, err := d.newRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - query := req.URL.Query() - query.Add("page_request.filter", fmt.Sprintf("name='%s' and type='TXT'", name)) - req.URL.RawQuery = query.Encode() - - var records Records - err = d.do(req, &records) - if err != nil { - return nil, err - } - - if len(records.Records) == 0 { - return nil, fmt.Errorf("did not find record with name %s", name) - } - - return records.Records, nil -} - -// https://developer.stackpath.com/en/api/dns/#operation/CreateZoneRecord -func (d *DNSProvider) createZoneRecord(zone *Zone, record Record) error { - u := fmt.Sprintf("/zones/%s/records", zone.ID) - req, err := d.newRequest(http.MethodPost, u, record) - if err != nil { - return err - } - - return d.do(req, nil) -} - -// https://developer.stackpath.com/en/api/dns/#operation/DeleteZoneRecord -func (d *DNSProvider) deleteZoneRecord(zone *Zone, record Record) error { - u := fmt.Sprintf("/zones/%s/records/%s", zone.ID, record.ID) - req, err := d.newRequest(http.MethodDelete, u, nil) - if err != nil { - return err - } - - return d.do(req, nil) -} - -func (d *DNSProvider) newRequest(method, urlStr string, body interface{}) (*http.Request, error) { - u, err := d.BaseURL.Parse(path.Join(d.config.StackID, urlStr)) - if err != nil { - return nil, err - } - - if body == nil { - var req *http.Request - req, err = http.NewRequest(method, u.String(), nil) - if err != nil { - return nil, err - } - - return req, nil - } - - reqBody, err := json.Marshal(body) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, u.String(), bytes.NewBuffer(reqBody)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - - return req, nil -} - -func (d *DNSProvider) do(req *http.Request, v interface{}) error { - resp, err := d.client.Do(req) - if err != nil { - return err - } - - err = checkResponse(resp) - if err != nil { - return err - } - - if v == nil { - return nil - } - - raw, err := readBody(resp) - if err != nil { - return fmt.Errorf("failed to read body: %v", err) - } - - err = json.Unmarshal(raw, v) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(raw)) - } - - return nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode > 299 { - data, err := readBody(resp) - if err != nil { - return &ErrorResponse{Code: resp.StatusCode, Message: err.Error()} - } - - errResp := &ErrorResponse{} - err = json.Unmarshal(data, errResp) - if err != nil { - return &ErrorResponse{Code: resp.StatusCode, Message: fmt.Sprintf("unmarshaling error: %v: %s", err, string(data))} - } - return errResp - } - - return nil -} - -func readBody(resp *http.Response) ([]byte, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil") - } - - defer resp.Body.Close() - - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return rawBody, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.go b/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.go deleted file mode 100644 index 48f77e9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.go +++ /dev/null @@ -1,150 +0,0 @@ -// Package stackpath implements a DNS provider for solving the DNS-01 challenge using Stackpath DNS. -// https://developer.stackpath.com/en/api/dns/ -package stackpath - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "golang.org/x/oauth2/clientcredentials" -) - -const ( - defaultBaseURL = "https://gateway.stackpath.com/dns/v1/stacks/" - defaultAuthURL = "https://gateway.stackpath.com/identity/v1/oauth2/token" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - ClientID string - ClientSecret string - StackID string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("STACKPATH_TTL", 120), - PropagationTimeout: env.GetOrDefaultSecond("STACKPATH_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("STACKPATH_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - BaseURL *url.URL - client *http.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for Stackpath. -// Credentials must be passed in the environment variables: -// STACKPATH_CLIENT_ID, STACKPATH_CLIENT_SECRET, and STACKPATH_STACK_ID. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("STACKPATH_CLIENT_ID", "STACKPATH_CLIENT_SECRET", "STACKPATH_STACK_ID") - if err != nil { - return nil, fmt.Errorf("stackpath: %v", err) - } - - config := NewDefaultConfig() - config.ClientID = values["STACKPATH_CLIENT_ID"] - config.ClientSecret = values["STACKPATH_CLIENT_SECRET"] - config.StackID = values["STACKPATH_STACK_ID"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Stackpath. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("stackpath: the configuration of the DNS provider is nil") - } - - if len(config.ClientID) == 0 || len(config.ClientSecret) == 0 { - return nil, errors.New("stackpath: credentials missing") - } - - if len(config.StackID) == 0 { - return nil, errors.New("stackpath: stack id missing") - } - - baseURL, _ := url.Parse(defaultBaseURL) - - return &DNSProvider{ - BaseURL: baseURL, - client: getOathClient(config), - config: config, - }, nil -} - -func getOathClient(config *Config) *http.Client { - oathConfig := &clientcredentials.Config{ - TokenURL: defaultAuthURL, - ClientID: config.ClientID, - ClientSecret: config.ClientSecret, - } - - return oathConfig.Client(context.Background()) -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - zone, err := d.getZones(domain) - if err != nil { - return fmt.Errorf("stackpath: %v", err) - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - parts := strings.Split(fqdn, ".") - - record := Record{ - Name: parts[0], - Type: "TXT", - TTL: d.config.TTL, - Data: value, - } - - return d.createZoneRecord(zone, record) -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - zone, err := d.getZones(domain) - if err != nil { - return fmt.Errorf("stackpath: %v", err) - } - - fqdn, _ := dns01.GetRecord(domain, keyAuth) - parts := strings.Split(fqdn, ".") - - records, err := d.getZoneRecords(parts[0], zone) - if err != nil { - return err - } - - for _, record := range records { - err = d.deleteZoneRecord(zone, record) - if err != nil { - log.Printf("stackpath: failed to delete TXT record: %v", err) - } - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.toml b/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.toml deleted file mode 100644 index 1a492eb..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Stackpath" -Description = '''''' -URL = "https://www.stackpath.com/" -Code = "stackpath" -Since = "v1.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - STACKPATH_CLIENT_ID = "Client ID" - STACKPATH_CLIENT_SECRET = "Client secret" - STACKPATH_STACK_ID = "Stack ID" - [Configuration.Additional] - STACKPATH_POLLING_INTERVAL = "Time between DNS propagation check" - STACKPATH_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - STACKPATH_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://developer.stackpath.com/en/api/dns/#tag/Zone" diff --git a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath_test.go b/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath_test.go deleted file mode 100644 index 94bff7c..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath_test.go +++ /dev/null @@ -1,290 +0,0 @@ -package stackpath - -import ( - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest( - "STACKPATH_CLIENT_ID", - "STACKPATH_CLIENT_SECRET", - "STACKPATH_STACK_ID"). - WithDomain("STACKPATH_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "STACKPATH_CLIENT_ID": "test@example.com", - "STACKPATH_CLIENT_SECRET": "123", - "STACKPATH_STACK_ID": "ID", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "STACKPATH_CLIENT_ID": "", - "STACKPATH_CLIENT_SECRET": "", - "STACKPATH_STACK_ID": "", - }, - expected: "stackpath: some credentials information are missing: STACKPATH_CLIENT_ID,STACKPATH_CLIENT_SECRET,STACKPATH_STACK_ID", - }, - { - desc: "missing client id", - envVars: map[string]string{ - "STACKPATH_CLIENT_ID": "", - "STACKPATH_CLIENT_SECRET": "123", - "STACKPATH_STACK_ID": "ID", - }, - expected: "stackpath: some credentials information are missing: STACKPATH_CLIENT_ID", - }, - { - desc: "missing client secret", - envVars: map[string]string{ - "STACKPATH_CLIENT_ID": "test@example.com", - "STACKPATH_CLIENT_SECRET": "", - "STACKPATH_STACK_ID": "ID", - }, - expected: "stackpath: some credentials information are missing: STACKPATH_CLIENT_SECRET", - }, - { - desc: "missing stack id", - envVars: map[string]string{ - "STACKPATH_CLIENT_ID": "test@example.com", - "STACKPATH_CLIENT_SECRET": "123", - "STACKPATH_STACK_ID": "", - }, - expected: "stackpath: some credentials information are missing: STACKPATH_STACK_ID", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - assert.NotNil(t, p) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := map[string]struct { - config *Config - expectedErr string - }{ - "no_config": { - config: nil, - expectedErr: "stackpath: the configuration of the DNS provider is nil", - }, - "no_client_id": { - config: &Config{ - ClientSecret: "secret", - StackID: "stackID", - }, - expectedErr: "stackpath: credentials missing", - }, - "no_client_secret": { - config: &Config{ - ClientID: "clientID", - StackID: "stackID", - }, - expectedErr: "stackpath: credentials missing", - }, - "no_stack_id": { - config: &Config{ - ClientID: "clientID", - ClientSecret: "secret", - }, - expectedErr: "stackpath: stack id missing", - }, - } - - for desc, test := range testCases { - test := test - t.Run(desc, func(t *testing.T) { - t.Parallel() - - p, err := NewDNSProviderConfig(test.config) - require.EqualError(t, err, test.expectedErr) - assert.Nil(t, p) - }) - } -} - -func setupMockAPITest() (*DNSProvider, *http.ServeMux, func()) { - apiHandler := http.NewServeMux() - server := httptest.NewServer(apiHandler) - - config := NewDefaultConfig() - config.ClientID = "CLIENT_ID" - config.ClientSecret = "CLIENT_SECRET" - config.StackID = "STACK_ID" - - provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } - - provider.client = http.DefaultClient - provider.BaseURL, _ = url.Parse(server.URL + "/") - - return provider, apiHandler, server.Close -} - -func TestDNSProvider_getZoneRecords(t *testing.T) { - provider, mux, tearDown := setupMockAPITest() - defer tearDown() - - mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) { - content := ` - { - "records": [ - {"id":"1","name":"foo1","type":"TXT","ttl":120,"data":"txtTXTtxt"}, - {"id":"2","name":"foo2","type":"TXT","ttl":121,"data":"TXTtxtTXT"} - ] - }` - - _, err := w.Write([]byte(content)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - records, err := provider.getZoneRecords("foo1", &Zone{ID: "A", Domain: "test"}) - require.NoError(t, err) - - expected := []Record{ - {ID: "1", Name: "foo1", Type: "TXT", TTL: 120, Data: "txtTXTtxt"}, - {ID: "2", Name: "foo2", Type: "TXT", TTL: 121, Data: "TXTtxtTXT"}, - } - - assert.Equal(t, expected, records) -} - -func TestDNSProvider_getZoneRecords_apiError(t *testing.T) { - provider, mux, tearDown := setupMockAPITest() - defer tearDown() - - mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) { - content := ` -{ - "code": 401, - "error": "an unauthorized request is attempted." -}` - - w.WriteHeader(http.StatusUnauthorized) - _, err := w.Write([]byte(content)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - _, err := provider.getZoneRecords("foo1", &Zone{ID: "A", Domain: "test"}) - - expected := &ErrorResponse{Code: 401, Message: "an unauthorized request is attempted."} - assert.Equal(t, expected, err) -} - -func TestDNSProvider_getZones(t *testing.T) { - provider, mux, tearDown := setupMockAPITest() - defer tearDown() - - mux.HandleFunc("/STACK_ID/zones", func(w http.ResponseWriter, _ *http.Request) { - content := ` -{ - "pageInfo": { - "totalCount": "5", - "hasPreviousPage": false, - "hasNextPage": false, - "startCursor": "1", - "endCursor": "1" - }, - "zones": [ - { - "stackId": "my_stack", - "accountId": "my_account", - "id": "A", - "domain": "foo.com", - "version": "1", - "labels": { - "property1": "val1", - "property2": "val2" - }, - "created": "2018-10-07T02:31:49Z", - "updated": "2018-10-07T02:31:49Z", - "nameservers": [ - "1.1.1.1" - ], - "verified": "2018-10-07T02:31:49Z", - "status": "ACTIVE", - "disabled": false - } - ] -}` - - _, err := w.Write([]byte(content)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - zone, err := provider.getZones("sub.foo.com") - require.NoError(t, err) - - expected := &Zone{ID: "A", Domain: "foo.com"} - - assert.Equal(t, expected, zone) -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/transip/fixtures/private.key b/vendor/github.com/go-acme/lego/providers/dns/transip/fixtures/private.key deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/github.com/go-acme/lego/providers/dns/transip/transip.go b/vendor/github.com/go-acme/lego/providers/dns/transip/transip.go deleted file mode 100644 index 2343696..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/transip/transip.go +++ /dev/null @@ -1,160 +0,0 @@ -// Package transip implements a DNS provider for solving the DNS-01 challenge using TransIP. -package transip - -import ( - "errors" - "fmt" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/transip/gotransip" - transipdomain "github.com/transip/gotransip/domain" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AccountName string - PrivateKeyPath string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int64 -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: int64(env.GetOrDefaultInt("TRANSIP_TTL", 10)), - PropagationTimeout: env.GetOrDefaultSecond("TRANSIP_PROPAGATION_TIMEOUT", 10*time.Minute), - PollingInterval: env.GetOrDefaultSecond("TRANSIP_POLLING_INTERVAL", 10*time.Second), - } -} - -// DNSProvider describes a provider for TransIP -type DNSProvider struct { - config *Config - client gotransip.Client - dnsEntriesMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for TransIP. -// Credentials must be passed in the environment variables: -// TRANSIP_ACCOUNTNAME, TRANSIP_PRIVATEKEYPATH. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("TRANSIP_ACCOUNT_NAME", "TRANSIP_PRIVATE_KEY_PATH") - if err != nil { - return nil, fmt.Errorf("transip: %v", err) - } - - config := NewDefaultConfig() - config.AccountName = values["TRANSIP_ACCOUNT_NAME"] - config.PrivateKeyPath = values["TRANSIP_PRIVATE_KEY_PATH"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for TransIP. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("transip: the configuration of the DNS provider is nil") - } - - client, err := gotransip.NewSOAPClient(gotransip.ClientConfig{ - AccountName: config.AccountName, - PrivateKeyPath: config.PrivateKeyPath, - }) - if err != nil { - return nil, fmt.Errorf("transip: %v", err) - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - domainName := dns01.UnFqdn(authZone) - - // get the subDomain - subDomain := strings.TrimSuffix(dns01.UnFqdn(fqdn), "."+domainName) - - // use mutex to prevent race condition from GetInfo until SetDNSEntries - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - // get all DNS entries - info, err := transipdomain.GetInfo(d.client, domainName) - if err != nil { - return fmt.Errorf("transip: error for %s in Present: %v", domain, err) - } - - // include the new DNS entry - dnsEntries := append(info.DNSEntries, transipdomain.DNSEntry{ - Name: subDomain, - TTL: d.config.TTL, - Type: transipdomain.DNSEntryTypeTXT, - Content: value, - }) - - // set the updated DNS entries - err = transipdomain.SetDNSEntries(d.client, domainName, dnsEntries) - if err != nil { - return fmt.Errorf("transip: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - domainName := dns01.UnFqdn(authZone) - - // get the subDomain - subDomain := strings.TrimSuffix(dns01.UnFqdn(fqdn), "."+domainName) - - // use mutex to prevent race condition from GetInfo until SetDNSEntries - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - // get all DNS entries - info, err := transipdomain.GetInfo(d.client, domainName) - if err != nil { - return fmt.Errorf("transip: error for %s in CleanUp: %v", fqdn, err) - } - - // loop through the existing entries and remove the specific record - updatedEntries := info.DNSEntries[:0] - for _, e := range info.DNSEntries { - if e.Name != subDomain { - updatedEntries = append(updatedEntries, e) - } - } - - // set the updated DNS entries - err = transipdomain.SetDNSEntries(d.client, domainName, updatedEntries) - if err != nil { - return fmt.Errorf("transip: couldn't get Record ID in CleanUp: %sv", err) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/transip/transip.toml b/vendor/github.com/go-acme/lego/providers/dns/transip/transip.toml deleted file mode 100644 index 57bebe9..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/transip/transip.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "TransIP" -Description = '''''' -URL = "https://www.transip.nl/" -Code = "transip" -Since = "v2.0.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - TRANSIP_ACCOUNT_NAME = "Account name" - TRANSIP_PRIVATE_KEY_PATH = "Private key path" - [Configuration.Additional] - TRANSIP_POLLING_INTERVAL = "Time between DNS propagation check" - TRANSIP_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - TRANSIP_TTL = "The TTL of the TXT record used for the DNS challenge" - -[Links] - API = "https://api.transip.nl/docs/transip.nl/package-Transip.html" - GoClient = "https://github.com/transip/gotransip" - diff --git a/vendor/github.com/go-acme/lego/providers/dns/transip/transip_test.go b/vendor/github.com/go-acme/lego/providers/dns/transip/transip_test.go deleted file mode 100644 index 57342ef..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/transip/transip_test.go +++ /dev/null @@ -1,337 +0,0 @@ -package transip - -import ( - "encoding/xml" - "fmt" - "reflect" - "strings" - "sync" - "testing" - "time" - - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/transip/gotransip" - "github.com/transip/gotransip/domain" -) - -type argDNSEntries struct { - Items domain.DNSEntries `xml:"item"` -} - -type argDomainName struct { - DomainName string `xml:",chardata"` -} - -type fakeClient struct { - dnsEntries []domain.DNSEntry - setDNSEntriesLatency time.Duration - getInfoLatency time.Duration -} - -func (f *fakeClient) Call(r gotransip.SoapRequest, b interface{}) error { - switch r.Method { - case "getInfo": - d := b.(*domain.Domain) - cp := f.dnsEntries - - if f.getInfoLatency != 0 { - time.Sleep(f.getInfoLatency) - } - d.DNSEntries = cp - - log.Printf("getInfo: %+v\n", d.DNSEntries) - return nil - case "setDnsEntries": - var domainName argDomainName - var dnsEntries argDNSEntries - - args := readArgs(r) - for _, arg := range args { - if strings.HasPrefix(arg, " 2 and there is -// no such domain on the account - it'll recursively search for the first -// which is exists in Vscale Domains API. -func (c *Client) GetDomainByName(domainName string) (*Domain, error) { - uri := fmt.Sprintf("/%s", domainName) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - domain := &Domain{} - resp, err := c.do(req, domain) - if err != nil { - switch { - case resp.StatusCode == http.StatusNotFound && strings.Count(domainName, ".") > 1: - // Look up for the next sub domain - subIndex := strings.Index(domainName, ".") - return c.GetDomainByName(domainName[subIndex+1:]) - default: - return nil, err - } - } - - return domain, nil -} - -// AddRecord adds Record for given domain. -func (c *Client) AddRecord(domainID int, body Record) (*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodPost, uri, body) - if err != nil { - return nil, err - } - - record := &Record{} - _, err = c.do(req, record) - if err != nil { - return nil, err - } - - return record, nil -} - -// ListRecords returns list records for specific domain. -func (c *Client) ListRecords(domainID int) ([]*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - var records []*Record - _, err = c.do(req, &records) - if err != nil { - return nil, err - } - return records, nil -} - -// DeleteRecord deletes specific record. -func (c *Client) DeleteRecord(domainID, recordID int) error { - uri := fmt.Sprintf("/%d/records/%d", domainID, recordID) - req, err := c.newRequest(http.MethodDelete, uri, nil) - if err != nil { - return err - } - - _, err = c.do(req, nil) - return err -} - -func (c *Client) newRequest(method, uri string, body interface{}) (*http.Request, error) { - buf := new(bytes.Buffer) - - if body != nil { - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, fmt.Errorf("failed to encode request body with error: %v", err) - } - } - - req, err := http.NewRequest(method, c.baseURL+uri, buf) - if err != nil { - return nil, fmt.Errorf("failed to create new http request with error: %v", err) - } - - req.Header.Add("X-Token", c.token) - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - - return req, nil -} - -func (c *Client) do(req *http.Request, to interface{}) (*http.Response, error) { - resp, err := c.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("request failed with error: %v", err) - } - - err = checkResponse(resp) - if err != nil { - return resp, err - } - - if to != nil { - if err = unmarshalBody(resp, to); err != nil { - return resp, err - } - } - - return resp, nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode >= http.StatusBadRequest && - resp.StatusCode <= http.StatusNetworkAuthenticationRequired { - - if resp.Body == nil { - return fmt.Errorf("request failed with status code %d and empty body", resp.StatusCode) - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - apiError := APIError{} - err = json.Unmarshal(body, &apiError) - if err != nil { - return fmt.Errorf("request failed with status code %d, response body: %s", resp.StatusCode, string(body)) - } - - return fmt.Errorf("request failed with status code %d: %v", resp.StatusCode, apiError) - } - - return nil -} - -func unmarshalBody(resp *http.Response, to interface{}) error { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - err = json.Unmarshal(body, to) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.go b/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.go deleted file mode 100644 index f6ce207..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.go +++ /dev/null @@ -1,155 +0,0 @@ -// Package vscale implements a DNS provider for solving the DNS-01 challenge using Vscale Domains API. -// Vscale Domain API reference: https://developers.vscale.io/documentation/api/v1/#api-Domains -// Token: https://vscale.io/panel/settings/tokens/ -package vscale - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/providers/dns/vscale/internal" - - "github.com/go-acme/lego/platform/config/env" -) - -const ( - defaultBaseURL = "https://api.vscale.io/v1/domains" - minTTL = 60 -) - -const ( - envNamespace = "VSCALE_" - baseURLEnvVar = envNamespace + "BASE_URL" - apiTokenEnvVar = envNamespace + "API_TOKEN" - ttlEnvVar = envNamespace + "TTL" - propagationTimeoutEnvVar = envNamespace + "PROPAGATION_TIMEOUT" - pollingIntervalEnvVar = envNamespace + "POLLING_INTERVAL" - httpTimeoutEnvVar = envNamespace + "HTTP_TIMEOUT" -) - -// Config is used to configure the creation of the DNSProvider. -type Config struct { - BaseURL string - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider. -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: env.GetOrDefaultString(baseURLEnvVar, defaultBaseURL), - TTL: env.GetOrDefaultInt(ttlEnvVar, minTTL), - PropagationTimeout: env.GetOrDefaultSecond(propagationTimeoutEnvVar, 120*time.Second), - PollingInterval: env.GetOrDefaultSecond(pollingIntervalEnvVar, 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond(httpTimeoutEnvVar, 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Vscale Domains API. -// API token must be passed in the environment variable VSCALE_API_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(apiTokenEnvVar) - if err != nil { - return nil, fmt.Errorf("vscale: %v", err) - } - - config := NewDefaultConfig() - config.Token = values[apiTokenEnvVar] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Vscale. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("vscale: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("vscale: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("vscale: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client := internal.NewClient(internal.ClientOpts{ - BaseURL: config.BaseURL, - Token: config.Token, - HTTPClient: config.HTTPClient, - }) - - return &DNSProvider{config: config, client: client}, nil -} - -// Timeout returns the Timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill DNS-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - txtRecord := internal.Record{ - Type: "TXT", - TTL: d.config.TTL, - Name: fqdn, - Content: value, - } - _, err = d.client.AddRecord(domainObj.ID, txtRecord) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - return nil -} - -// CleanUp removes a TXT record used for DNS-01 challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - recordName := dns01.UnFqdn(fqdn) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - records, err := d.client.ListRecords(domainObj.ID) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - // Delete records with specific FQDN - var lastErr error - for _, record := range records { - if record.Name == recordName { - err = d.client.DeleteRecord(domainObj.ID, record.ID) - if err != nil { - lastErr = fmt.Errorf("vscale: %v", err) - } - } - } - - return lastErr -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.toml b/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.toml deleted file mode 100644 index b86da65..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Vscale" -Description = '''''' -URL = "https://vscale.io/" -Code = "vscale" -Since = "v2.0.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - VSCALE_API_TOKEN = "API token" - [Configuration.Additional] - VSCALE_BASE_URL = "API enddpoint URL" - VSCALE_POLLING_INTERVAL = "Time between DNS propagation check" - VSCALE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - VSCALE_TTL = "The TTL of the TXT record used for the DNS challenge" - VSCALE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://developers.vscale.io/documentation/api/v1/#api-Domains_Records" diff --git a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale_test.go b/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale_test.go deleted file mode 100644 index 7e7fd8f..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package vscale - -import ( - "fmt" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest(apiTokenEnvVar, ttlEnvVar) - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - apiTokenEnvVar: "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - apiTokenEnvVar: "", - }, - expected: fmt.Sprintf("vscale: some credentials information are missing: %s", apiTokenEnvVar), - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - token string - ttl int - expected string - }{ - { - desc: "success", - token: "123", - ttl: 60, - }, - { - desc: "missing api key", - token: "", - ttl: 60, - expected: "vscale: credentials missing", - }, - { - desc: "bad TTL value", - token: "123", - ttl: 59, - expected: fmt.Sprintf("vscale: invalid TTL, TTL (59) must be greater than %d", minTTL), - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.TTL = test.ttl - config.Token = test.token - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - assert.NotNil(t, p.config) - assert.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.go b/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.go deleted file mode 100644 index 94e5d86..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.go +++ /dev/null @@ -1,179 +0,0 @@ -// Package vultr implements a DNS provider for solving the DNS-01 challenge using the vultr DNS. -// See https://www.vultr.com/api/#dns -package vultr - -import ( - "crypto/tls" - "errors" - "fmt" - "net/http" - "strings" - "time" - - vultr "github.com/JamesClonk/vultr/lib" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("VULTR_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("VULTR_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("VULTR_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("VULTR_HTTP_TIMEOUT", 0), - // from Vultr Client - Transport: &http.Transport{ - TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), - }, - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *vultr.Client -} - -// NewDNSProvider returns a DNSProvider instance with a configured Vultr client. -// Authentication uses the VULTR_API_KEY environment variable. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("VULTR_API_KEY") - if err != nil { - return nil, fmt.Errorf("vultr: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["VULTR_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Vultr. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("vultr: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("vultr: credentials missing") - } - - options := &vultr.Options{ - HTTPClient: config.HTTPClient, - } - client := vultr.NewClient(config.APIKey, options) - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the DNS-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zoneDomain, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("vultr: %v", err) - } - - name := d.extractRecordName(fqdn, zoneDomain) - - err = d.client.CreateDNSRecord(zoneDomain, name, "TXT", `"`+value+`"`, 0, d.config.TTL) - if err != nil { - return fmt.Errorf("vultr: API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zoneDomain, records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return fmt.Errorf("vultr: %v", err) - } - - var allErr []string - for _, rec := range records { - err := d.client.DeleteDNSRecord(zoneDomain, rec.RecordID) - if err != nil { - allErr = append(allErr, err.Error()) - } - } - - if len(allErr) > 0 { - return errors.New(strings.Join(allErr, ": ")) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(domain string) (string, error) { - domains, err := d.client.GetDNSDomains() - if err != nil { - return "", fmt.Errorf("API call failed: %v", err) - } - - var hostedDomain vultr.DNSDomain - for _, dom := range domains { - if strings.HasSuffix(domain, dom.Domain) { - if len(dom.Domain) > len(hostedDomain.Domain) { - hostedDomain = dom - } - } - } - if hostedDomain.Domain == "" { - return "", fmt.Errorf("no matching Vultr domain found for domain %s", domain) - } - - return hostedDomain.Domain, nil -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) (string, []vultr.DNSRecord, error) { - zoneDomain, err := d.getHostedZone(domain) - if err != nil { - return "", nil, err - } - - var records []vultr.DNSRecord - result, err := d.client.GetDNSRecords(zoneDomain) - if err != nil { - return "", records, fmt.Errorf("API call has failed: %v", err) - } - - recordName := d.extractRecordName(fqdn, zoneDomain) - for _, record := range result { - if record.Type == "TXT" && record.Name == recordName { - records = append(records, record) - } - } - - return zoneDomain, records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.toml b/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.toml deleted file mode 100644 index b210407..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.toml +++ /dev/null @@ -1,20 +0,0 @@ -Name = "Vultr" -Description = '''''' -URL = "https://www.vultr.com/" -Code = "vultr" -Since = "v0.3.1" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - VULTR_API_KEY = "API key" - [Configuration.Additional] - VULTR_POLLING_INTERVAL = "Time between DNS propagation check" - VULTR_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - VULTR_TTL = "The TTL of the TXT record used for the DNS challenge" - VULTR_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://www.vultr.com/api/#dns" - GoClient = "https://github.com/JamesClonk/vultr" diff --git a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr_test.go b/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr_test.go deleted file mode 100644 index 74d7462..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package vultr - -import ( - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("VULTR_API_KEY"). - WithDomain("VULTR_TEST_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "VULTR_API_KEY": "123", - }, - }, - { - desc: "missing api key", - envVars: map[string]string{ - "VULTR_API_KEY": "", - }, - expected: "vultr: some credentials information are missing: VULTR_API_KEY", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiKey string - expected string - }{ - { - desc: "success", - apiKey: "123", - }, - { - desc: "missing credentials", - expected: "vultr: credentials missing", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - require.NotNil(t, p.client) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(1 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/zoneee/client.go b/vendor/github.com/go-acme/lego/providers/dns/zoneee/client.go deleted file mode 100644 index b48808b..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/zoneee/client.go +++ /dev/null @@ -1,132 +0,0 @@ -package zoneee - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "path" -) - -const defaultEndpoint = "https://api.zone.eu/v2/dns/" - -type txtRecord struct { - // Identifier (identificator) - ID string `json:"id,omitempty"` - // Hostname - Name string `json:"name"` - // TXT content value - Destination string `json:"destination"` - // Can this record be deleted - Delete bool `json:"delete,omitempty"` - // Can this record be modified - Modify bool `json:"modify,omitempty"` - // API url to get this entity - ResourceURL string `json:"resource_url,omitempty"` -} - -func (d *DNSProvider) addTxtRecord(domain string, record txtRecord) ([]txtRecord, error) { - reqBody := &bytes.Buffer{} - if err := json.NewEncoder(reqBody).Encode(record); err != nil { - return nil, err - } - - req, err := d.makeRequest(http.MethodPost, path.Join(domain, "txt"), reqBody) - if err != nil { - return nil, err - } - - var resp []txtRecord - if err := d.sendRequest(req, &resp); err != nil { - return nil, err - } - return resp, nil -} - -func (d *DNSProvider) getTxtRecords(domain string) ([]txtRecord, error) { - req, err := d.makeRequest(http.MethodGet, path.Join(domain, "txt"), nil) - if err != nil { - return nil, err - } - - var resp []txtRecord - if err := d.sendRequest(req, &resp); err != nil { - return nil, err - } - return resp, nil -} - -func (d *DNSProvider) removeTxtRecord(domain, id string) error { - req, err := d.makeRequest(http.MethodDelete, path.Join(domain, "txt", id), nil) - if err != nil { - return err - } - - return d.sendRequest(req, nil) -} - -func (d *DNSProvider) makeRequest(method, resource string, body io.Reader) (*http.Request, error) { - uri, err := d.config.Endpoint.Parse(resource) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, uri.String(), body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.SetBasicAuth(d.config.Username, d.config.APIKey) - - return req, nil -} - -func (d *DNSProvider) sendRequest(req *http.Request, result interface{}) error { - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - - if err = checkResponse(resp); err != nil { - return err - } - - defer resp.Body.Close() - - if result == nil { - return nil - } - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - err = json.Unmarshal(raw, result) - if err != nil { - return fmt.Errorf("unmarshaling %T error [status code=%d]: %v: %s", result, resp.StatusCode, err, string(raw)) - } - return err -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode < http.StatusBadRequest { - return nil - } - - if resp.Body == nil { - return fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) - } - - defer resp.Body.Close() - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) - } - - return fmt.Errorf("status code=%d: %s", resp.StatusCode, string(raw)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.go b/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.go deleted file mode 100644 index 8ede3d6..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.go +++ /dev/null @@ -1,134 +0,0 @@ -// Package zoneee implements a DNS provider for solving the DNS-01 challenge through zone.ee. -package zoneee - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Endpoint *url.URL - Username string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - endpoint, _ := url.Parse(defaultEndpoint) - - return &Config{ - Endpoint: endpoint, - // zone.ee can take up to 5min to propagate according to the support - PropagationTimeout: env.GetOrDefaultSecond("ZONEEE_PROPAGATION_TIMEOUT", 5*time.Minute), - PollingInterval: env.GetOrDefaultSecond("ZONEEE_POLLING_INTERVAL", 5*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("ZONEEE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider describes a provider for acme-proxy -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("ZONEEE_API_USER", "ZONEEE_API_KEY") - if err != nil { - return nil, fmt.Errorf("zoneee: %v", err) - } - - rawEndpoint := env.GetOrDefaultString("ZONEEE_ENDPOINT", defaultEndpoint) - endpoint, err := url.Parse(rawEndpoint) - if err != nil { - return nil, fmt.Errorf("zoneee: %v", err) - } - - config := NewDefaultConfig() - config.Username = values["ZONEEE_API_USER"] - config.APIKey = values["ZONEEE_API_KEY"] - config.Endpoint = endpoint - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider . -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("zoneee: the configuration of the DNS provider is nil") - } - - if config.Username == "" { - return nil, fmt.Errorf("zoneee: credentials missing: username") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("zoneee: credentials missing: API key") - } - - if config.Endpoint == nil { - return nil, errors.New("zoneee: the endpoint is missing") - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - record := txtRecord{ - Name: fqdn[:len(fqdn)-1], - Destination: value, - } - - _, err := d.addTxtRecord(domain, record) - if err != nil { - return fmt.Errorf("zoneee: %v", err) - } - return nil -} - -// CleanUp removes the TXT record previously created -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - - records, err := d.getTxtRecords(domain) - if err != nil { - return fmt.Errorf("zoneee: %v", err) - } - - var id string - for _, record := range records { - if record.Destination == value { - id = record.ID - } - } - - if id == "" { - return fmt.Errorf("zoneee: txt record does not exist for %v", value) - } - - if err = d.removeTxtRecord(domain, id); err != nil { - return fmt.Errorf("zoneee: %v", err) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.toml b/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.toml deleted file mode 100644 index fbff725..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.toml +++ /dev/null @@ -1,21 +0,0 @@ -Name = "Zone.ee" -Description = '''''' -URL = "https://www.zone.ee/" -Code = "zoneee" -Since = "v2.1.0" - -Example = '''''' - -[Configuration] - [Configuration.Credentials] - ZONEEE_API_USER = "API user" - ZONEEE_API_KEY = "API key" - [Configuration.Additional] - ZONEEE_ENDPOINT = "API endpoint URL" - ZONEEE_POLLING_INTERVAL = "Time between DNS propagation check" - ZONEEE_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation" - ZONEEE_TTL = "The TTL of the TXT record used for the DNS challenge" - ZONEEE_HTTP_TIMEOUT = "API request timeout" - -[Links] - API = "https://api.zone.eu/v2" diff --git a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee_test.go b/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee_test.go deleted file mode 100644 index 3838bd2..0000000 --- a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee_test.go +++ /dev/null @@ -1,412 +0,0 @@ -package zoneee - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/require" -) - -var envTest = tester.NewEnvTest("ZONEEE_ENDPOINT", "ZONEEE_API_USER", "ZONEEE_API_KEY"). - WithLiveTestRequirements("ZONEEE_API_USER", "ZONEEE_API_KEY"). - WithDomain("ZONEE_DOMAIN") - -func TestNewDNSProvider(t *testing.T) { - testCases := []struct { - desc string - envVars map[string]string - expected string - }{ - { - desc: "success", - envVars: map[string]string{ - "ZONEEE_API_USER": "123", - "ZONEEE_API_KEY": "456", - }, - }, - { - desc: "missing credentials", - envVars: map[string]string{ - "ZONEEE_API_USER": "", - "ZONEEE_API_KEY": "", - }, - expected: "zoneee: some credentials information are missing: ZONEEE_API_USER,ZONEEE_API_KEY", - }, - { - desc: "missing username", - envVars: map[string]string{ - "ZONEEE_API_USER": "", - "ZONEEE_API_KEY": "456", - }, - expected: "zoneee: some credentials information are missing: ZONEEE_API_USER", - }, - { - desc: "missing API key", - envVars: map[string]string{ - "ZONEEE_API_USER": "123", - "ZONEEE_API_KEY": "", - }, - expected: "zoneee: some credentials information are missing: ZONEEE_API_KEY", - }, - { - desc: "invalid URL", - envVars: map[string]string{ - "ZONEEE_API_USER": "123", - "ZONEEE_API_KEY": "456", - "ZONEEE_ENDPOINT": ":", - }, - expected: "zoneee: parse :: missing protocol scheme", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - defer envTest.RestoreEnv() - envTest.ClearEnv() - - envTest.Apply(test.envVars) - - p, err := NewDNSProvider() - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestNewDNSProviderConfig(t *testing.T) { - testCases := []struct { - desc string - apiUser string - apiKey string - endpoint string - expected string - }{ - { - desc: "success", - apiKey: "123", - apiUser: "456", - }, - { - desc: "missing credentials", - expected: "zoneee: credentials missing: username", - }, - { - desc: "missing api key", - apiUser: "456", - expected: "zoneee: credentials missing: API key", - }, - { - desc: "missing username", - apiKey: "123", - expected: "zoneee: credentials missing: username", - }, - } - - for _, test := range testCases { - t.Run(test.desc, func(t *testing.T) { - config := NewDefaultConfig() - config.APIKey = test.apiKey - config.Username = test.apiUser - - if len(test.endpoint) > 0 { - config.Endpoint = mustParse(test.endpoint) - } - - p, err := NewDNSProviderConfig(config) - - if len(test.expected) == 0 { - require.NoError(t, err) - require.NotNil(t, p) - require.NotNil(t, p.config) - } else { - require.EqualError(t, err, test.expected) - } - }) - } -} - -func TestDNSProvider_Present(t *testing.T) { - domain := "prefix.example.com" - - testCases := []struct { - desc string - username string - apiKey string - handlers map[string]http.HandlerFunc - expectedError string - }{ - { - desc: "success", - username: "bar", - apiKey: "foo", - handlers: map[string]http.HandlerFunc{ - "/" + domain + "/txt": mockHandlerCreateRecord, - }, - }, - { - desc: "invalid auth", - username: "nope", - apiKey: "foo", - handlers: map[string]http.HandlerFunc{ - "/" + domain + "/txt": mockHandlerCreateRecord, - }, - expectedError: "zoneee: status code=401: Unauthorized\n", - }, - { - desc: "error", - username: "bar", - apiKey: "foo", - expectedError: "zoneee: status code=404: 404 page not found\n", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - mux := http.NewServeMux() - for uri, handler := range test.handlers { - mux.HandleFunc(uri, handler) - } - - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.Endpoint = mustParse(server.URL) - config.Username = test.username - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = p.Present(domain, "token", "key") - if test.expectedError == "" { - require.NoError(t, err) - } else { - require.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestDNSProvider_Cleanup(t *testing.T) { - domain := "prefix.example.com" - - testCases := []struct { - desc string - username string - apiKey string - handlers map[string]http.HandlerFunc - expectedError string - }{ - { - desc: "success", - username: "bar", - apiKey: "foo", - handlers: map[string]http.HandlerFunc{ - "/" + domain + "/txt": mockHandlerGetRecords([]txtRecord{{ - ID: "1234", - Name: domain, - Destination: "LHDhK3oGRvkiefQnx7OOczTY5Tic_xZ6HcMOc_gmtoM", - Delete: true, - Modify: true, - }}), - "/" + domain + "/txt/1234": mockHandlerDeleteRecord, - }, - }, - { - desc: "no txt records", - username: "bar", - apiKey: "foo", - handlers: map[string]http.HandlerFunc{ - "/" + domain + "/txt": mockHandlerGetRecords([]txtRecord{}), - "/" + domain + "/txt/1234": mockHandlerDeleteRecord, - }, - expectedError: "zoneee: txt record does not exist for LHDhK3oGRvkiefQnx7OOczTY5Tic_xZ6HcMOc_gmtoM", - }, - { - desc: "invalid auth", - username: "nope", - apiKey: "foo", - handlers: map[string]http.HandlerFunc{ - "/" + domain + "/txt": mockHandlerGetRecords([]txtRecord{{ - ID: "1234", - Name: domain, - Destination: "LHDhK3oGRvkiefQnx7OOczTY5Tic_xZ6HcMOc_gmtoM", - Delete: true, - Modify: true, - }}), - "/" + domain + "/txt/1234": mockHandlerDeleteRecord, - }, - expectedError: "zoneee: status code=401: Unauthorized\n", - }, - { - desc: "error", - username: "bar", - apiKey: "foo", - expectedError: "zoneee: status code=404: 404 page not found\n", - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - mux := http.NewServeMux() - for uri, handler := range test.handlers { - mux.HandleFunc(uri, handler) - } - - server := httptest.NewServer(mux) - - config := NewDefaultConfig() - config.Endpoint = mustParse(server.URL) - config.Username = test.username - config.APIKey = test.apiKey - - p, err := NewDNSProviderConfig(config) - require.NoError(t, err) - - err = p.CleanUp(domain, "token", "key") - if test.expectedError == "" { - require.NoError(t, err) - } else { - require.EqualError(t, err, test.expectedError) - } - }) - } -} - -func TestLivePresent(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - err = provider.Present(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func TestLiveCleanUp(t *testing.T) { - if !envTest.IsLiveTest() { - t.Skip("skipping live test") - } - - envTest.RestoreEnv() - provider, err := NewDNSProvider() - require.NoError(t, err) - - time.Sleep(2 * time.Second) - - err = provider.CleanUp(envTest.GetDomain(), "", "123d==") - require.NoError(t, err) -} - -func mustParse(rawURL string) *url.URL { - uri, err := url.Parse(rawURL) - if err != nil { - panic(err) - } - return uri -} - -func mockHandlerCreateRecord(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - } - - username, apiKey, ok := req.BasicAuth() - if username != "bar" || apiKey != "foo" || !ok { - rw.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, "Please enter your username and API key.")) - http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - - record := txtRecord{} - err := json.NewDecoder(req.Body).Decode(&record) - if err != nil { - http.Error(rw, err.Error(), http.StatusBadRequest) - return - } - - record.ID = "1234" - record.Delete = true - record.Modify = true - record.ResourceURL = req.URL.String() + "/1234" - - bytes, err := json.Marshal([]txtRecord{record}) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - if _, err = rw.Write(bytes); err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } -} - -func mockHandlerGetRecords(records []txtRecord) http.HandlerFunc { - return func(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet { - http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - } - - username, apiKey, ok := req.BasicAuth() - if username != "bar" || apiKey != "foo" || !ok { - rw.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, "Please enter your username and API key.")) - http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - - for _, value := range records { - if len(value.ResourceURL) == 0 { - value.ResourceURL = req.URL.String() + "/" + value.ID - } - } - - bytes, err := json.Marshal(records) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - - if _, err = rw.Write(bytes); err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - } -} - -func mockHandlerDeleteRecord(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodDelete { - http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return - } - - username, apiKey, ok := req.BasicAuth() - if username != "bar" || apiKey != "foo" || !ok { - rw.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, "Please enter your username and API key.")) - http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - - rw.WriteHeader(http.StatusNoContent) -} diff --git a/vendor/github.com/go-acme/lego/providers/http/memcached/README.md b/vendor/github.com/go-acme/lego/providers/http/memcached/README.md deleted file mode 100644 index f14d216..0000000 --- a/vendor/github.com/go-acme/lego/providers/http/memcached/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Memcached http provider - -Publishes challenges into memcached where they can be retrieved by nginx. Allows -specifying multiple memcached servers and the responses will be published to all -of them, making it easier to verify when your domain is hosted on a cluster of -servers. - -Example nginx config: - -``` - location /.well-known/acme-challenge/ { - set $memcached_key "$uri"; - memcached_pass 127.0.0.1:11211; - } -``` diff --git a/vendor/github.com/go-acme/lego/providers/http/memcached/memcached.go b/vendor/github.com/go-acme/lego/providers/http/memcached/memcached.go deleted file mode 100644 index 830f4b4..0000000 --- a/vendor/github.com/go-acme/lego/providers/http/memcached/memcached.go +++ /dev/null @@ -1,60 +0,0 @@ -// Package memcached implements a HTTP provider for solving the HTTP-01 challenge using memcached -// in combination with a webserver. -package memcached - -import ( - "fmt" - "path" - - "github.com/go-acme/lego/challenge/http01" - "github.com/rainycape/memcache" -) - -// HTTPProvider implements HTTPProvider for `http-01` challenge -type HTTPProvider struct { - hosts []string -} - -// NewMemcachedProvider returns a HTTPProvider instance with a configured webroot path -func NewMemcachedProvider(hosts []string) (*HTTPProvider, error) { - if len(hosts) == 0 { - return nil, fmt.Errorf("no memcached hosts provided") - } - - c := &HTTPProvider{ - hosts: hosts, - } - - return c, nil -} - -// Present makes the token available at `HTTP01ChallengePath(token)` by creating a file in the given webroot path -func (w *HTTPProvider) Present(domain, token, keyAuth string) error { - var errs []error - - challengePath := path.Join("/", http01.ChallengePath(token)) - for _, host := range w.hosts { - mc, err := memcache.New(host) - if err != nil { - errs = append(errs, err) - continue - } - _ = mc.Add(&memcache.Item{ - Key: challengePath, - Value: []byte(keyAuth), - Expiration: 60, - }) - } - - if len(errs) == len(w.hosts) { - return fmt.Errorf("unable to store key in any of the memcache hosts -> %v", errs) - } - - return nil -} - -// CleanUp removes the file created for the challenge -func (w *HTTPProvider) CleanUp(domain, token, keyAuth string) error { - // Memcached will clean up itself, that's what expiration is for. - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/http/memcached/memcached_test.go b/vendor/github.com/go-acme/lego/providers/http/memcached/memcached_test.go deleted file mode 100644 index 9cf5d1f..0000000 --- a/vendor/github.com/go-acme/lego/providers/http/memcached/memcached_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package memcached - -import ( - "os" - "path" - "strings" - "testing" - - "github.com/go-acme/lego/challenge/http01" - "github.com/rainycape/memcache" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - domain = "lego.test" - token = "foo" - keyAuth = "bar" -) - -var memcachedHosts = loadMemcachedHosts() - -func loadMemcachedHosts() []string { - memcachedHostsStr := os.Getenv("MEMCACHED_HOSTS") - if len(memcachedHostsStr) > 0 { - return strings.Split(memcachedHostsStr, ",") - } - return nil -} - -func TestNewMemcachedProviderEmpty(t *testing.T) { - emptyHosts := make([]string, 0) - _, err := NewMemcachedProvider(emptyHosts) - assert.EqualError(t, err, "no memcached hosts provided") -} - -func TestNewMemcachedProviderValid(t *testing.T) { - if len(memcachedHosts) == 0 { - t.Skip("Skipping memcached tests") - } - _, err := NewMemcachedProvider(memcachedHosts) - require.NoError(t, err) -} - -func TestMemcachedPresentSingleHost(t *testing.T) { - if len(memcachedHosts) == 0 { - t.Skip("Skipping memcached tests") - } - p, err := NewMemcachedProvider(memcachedHosts[0:1]) - require.NoError(t, err) - - challengePath := path.Join("/", http01.ChallengePath(token)) - - err = p.Present(domain, token, keyAuth) - require.NoError(t, err) - mc, err := memcache.New(memcachedHosts[0]) - require.NoError(t, err) - i, err := mc.Get(challengePath) - require.NoError(t, err) - assert.Equal(t, i.Value, []byte(keyAuth)) -} - -func TestMemcachedPresentMultiHost(t *testing.T) { - if len(memcachedHosts) <= 1 { - t.Skip("Skipping memcached multi-host tests") - } - p, err := NewMemcachedProvider(memcachedHosts) - require.NoError(t, err) - - challengePath := path.Join("/", http01.ChallengePath(token)) - - err = p.Present(domain, token, keyAuth) - require.NoError(t, err) - for _, host := range memcachedHosts { - mc, err := memcache.New(host) - require.NoError(t, err) - i, err := mc.Get(challengePath) - require.NoError(t, err) - assert.Equal(t, i.Value, []byte(keyAuth)) - } -} - -func TestMemcachedPresentPartialFailureMultiHost(t *testing.T) { - if len(memcachedHosts) == 0 { - t.Skip("Skipping memcached tests") - } - hosts := append(memcachedHosts, "5.5.5.5:11211") - p, err := NewMemcachedProvider(hosts) - require.NoError(t, err) - - challengePath := path.Join("/", http01.ChallengePath(token)) - - err = p.Present(domain, token, keyAuth) - require.NoError(t, err) - for _, host := range memcachedHosts { - mc, err := memcache.New(host) - require.NoError(t, err) - i, err := mc.Get(challengePath) - require.NoError(t, err) - assert.Equal(t, i.Value, []byte(keyAuth)) - } -} - -func TestMemcachedCleanup(t *testing.T) { - if len(memcachedHosts) == 0 { - t.Skip("Skipping memcached tests") - } - p, err := NewMemcachedProvider(memcachedHosts) - require.NoError(t, err) - require.NoError(t, p.CleanUp(domain, token, keyAuth)) -} diff --git a/vendor/github.com/go-acme/lego/providers/http/webroot/webroot.go b/vendor/github.com/go-acme/lego/providers/http/webroot/webroot.go deleted file mode 100644 index d7c6fc1..0000000 --- a/vendor/github.com/go-acme/lego/providers/http/webroot/webroot.go +++ /dev/null @@ -1,53 +0,0 @@ -// Package webroot implements a HTTP provider for solving the HTTP-01 challenge using web server's root path. -package webroot - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/go-acme/lego/challenge/http01" -) - -// HTTPProvider implements ChallengeProvider for `http-01` challenge -type HTTPProvider struct { - path string -} - -// NewHTTPProvider returns a HTTPProvider instance with a configured webroot path -func NewHTTPProvider(path string) (*HTTPProvider, error) { - if _, err := os.Stat(path); os.IsNotExist(err) { - return nil, fmt.Errorf("webroot path does not exist") - } - - return &HTTPProvider{path: path}, nil -} - -// Present makes the token available at `HTTP01ChallengePath(token)` by creating a file in the given webroot path -func (w *HTTPProvider) Present(domain, token, keyAuth string) error { - var err error - - challengeFilePath := filepath.Join(w.path, http01.ChallengePath(token)) - err = os.MkdirAll(filepath.Dir(challengeFilePath), 0755) - if err != nil { - return fmt.Errorf("could not create required directories in webroot for HTTP challenge -> %v", err) - } - - err = ioutil.WriteFile(challengeFilePath, []byte(keyAuth), 0644) - if err != nil { - return fmt.Errorf("could not write file in webroot for HTTP challenge -> %v", err) - } - - return nil -} - -// CleanUp removes the file created for the challenge -func (w *HTTPProvider) CleanUp(domain, token, keyAuth string) error { - err := os.Remove(filepath.Join(w.path, http01.ChallengePath(token))) - if err != nil { - return fmt.Errorf("could not remove file in webroot after HTTP challenge -> %v", err) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/http/webroot/webroot_test.go b/vendor/github.com/go-acme/lego/providers/http/webroot/webroot_test.go deleted file mode 100644 index 5fccae3..0000000 --- a/vendor/github.com/go-acme/lego/providers/http/webroot/webroot_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package webroot - -import ( - "io/ioutil" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestHTTPProvider(t *testing.T) { - webroot := "webroot" - domain := "domain" - token := "token" - keyAuth := "keyAuth" - challengeFilePath := webroot + "/.well-known/acme-challenge/" + token - - require.NoError(t, os.MkdirAll(webroot+"/.well-known/acme-challenge", 0777)) - defer os.RemoveAll(webroot) - - provider, err := NewHTTPProvider(webroot) - require.NoError(t, err) - - err = provider.Present(domain, token, keyAuth) - require.NoError(t, err) - - if _, err = os.Stat(challengeFilePath); os.IsNotExist(err) { - t.Error("Challenge file was not created in webroot") - } - - var data []byte - data, err = ioutil.ReadFile(challengeFilePath) - require.NoError(t, err) - - dataStr := string(data) - assert.Equal(t, keyAuth, dataStr) - - err = provider.CleanUp(domain, token, keyAuth) - require.NoError(t, err) -} diff --git a/vendor/github.com/go-acme/lego/registration/registar.go b/vendor/github.com/go-acme/lego/registration/registar.go deleted file mode 100644 index 09e8665..0000000 --- a/vendor/github.com/go-acme/lego/registration/registar.go +++ /dev/null @@ -1,146 +0,0 @@ -package registration - -import ( - "errors" - "net/http" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/log" -) - -// Resource represents all important information about a registration -// of which the client needs to keep track itself. -// Deprecated: will be remove in the future (acme.ExtendedAccount). -type Resource struct { - Body acme.Account `json:"body,omitempty"` - URI string `json:"uri,omitempty"` -} - -type RegisterOptions struct { - TermsOfServiceAgreed bool -} - -type RegisterEABOptions struct { - TermsOfServiceAgreed bool - Kid string - HmacEncoded string -} - -type Registrar struct { - core *api.Core - user User -} - -func NewRegistrar(core *api.Core, user User) *Registrar { - return &Registrar{ - core: core, - user: user, - } -} - -// Register the current account to the ACME server. -func (r *Registrar) Register(options RegisterOptions) (*Resource, error) { - if r == nil || r.user == nil { - return nil, errors.New("acme: cannot register a nil client or user") - } - - accMsg := acme.Account{ - TermsOfServiceAgreed: options.TermsOfServiceAgreed, - Contact: []string{}, - } - - if r.user.GetEmail() != "" { - log.Infof("acme: Registering account for %s", r.user.GetEmail()) - accMsg.Contact = []string{"mailto:" + r.user.GetEmail()} - } - - account, err := r.core.Accounts.New(accMsg) - if err != nil { - // FIXME seems impossible - errorDetails, ok := err.(acme.ProblemDetails) - if !ok || errorDetails.HTTPStatus != http.StatusConflict { - return nil, err - } - } - - return &Resource{URI: account.Location, Body: account.Account}, nil -} - -// RegisterWithExternalAccountBinding Register the current account to the ACME server. -func (r *Registrar) RegisterWithExternalAccountBinding(options RegisterEABOptions) (*Resource, error) { - accMsg := acme.Account{ - TermsOfServiceAgreed: options.TermsOfServiceAgreed, - Contact: []string{}, - } - - if r.user.GetEmail() != "" { - log.Infof("acme: Registering account for %s", r.user.GetEmail()) - accMsg.Contact = []string{"mailto:" + r.user.GetEmail()} - } - - account, err := r.core.Accounts.NewEAB(accMsg, options.Kid, options.HmacEncoded) - if err != nil { - errorDetails, ok := err.(acme.ProblemDetails) - // FIXME seems impossible - if !ok || errorDetails.HTTPStatus != http.StatusConflict { - return nil, err - } - } - - return &Resource{URI: account.Location, Body: account.Account}, nil -} - -// QueryRegistration runs a POST request on the client's registration and returns the result. -// -// This is similar to the Register function, -// but acting on an existing registration link and resource. -func (r *Registrar) QueryRegistration() (*Resource, error) { - if r == nil || r.user == nil { - return nil, errors.New("acme: cannot query the registration of a nil client or user") - } - - // Log the URL here instead of the email as the email may not be set - log.Infof("acme: Querying account for %s", r.user.GetRegistration().URI) - - account, err := r.core.Accounts.Get(r.user.GetRegistration().URI) - if err != nil { - return nil, err - } - - return &Resource{ - Body: account, - // Location: header is not returned so this needs to be populated off of existing URI - URI: r.user.GetRegistration().URI, - }, nil -} - -// DeleteRegistration deletes the client's user registration from the ACME server. -func (r *Registrar) DeleteRegistration() error { - if r == nil || r.user == nil { - return errors.New("acme: cannot unregister a nil client or user") - } - - log.Infof("acme: Deleting account for %s", r.user.GetEmail()) - - return r.core.Accounts.Deactivate(r.user.GetRegistration().URI) -} - -// ResolveAccountByKey will attempt to look up an account using the given account key -// and return its registration resource. -func (r *Registrar) ResolveAccountByKey() (*Resource, error) { - log.Infof("acme: Trying to resolve account by key") - - accMsg := acme.Account{OnlyReturnExisting: true} - accountTransit, err := r.core.Accounts.New(accMsg) - if err != nil { - return nil, err - } - - account, err := r.core.Accounts.Get(accountTransit.Location) - if err != nil { - return nil, err - } - - return &Resource{URI: accountTransit.Location, Body: account}, nil -} diff --git a/vendor/github.com/go-acme/lego/registration/registar_test.go b/vendor/github.com/go-acme/lego/registration/registar_test.go deleted file mode 100644 index 5704318..0000000 --- a/vendor/github.com/go-acme/lego/registration/registar_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package registration - -import ( - "crypto/rand" - "crypto/rsa" - "net/http" - "testing" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/platform/tester" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestRegistrar_ResolveAccountByKey(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() - - mux.HandleFunc("/account", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Location", apiURL+"/account_recovery") - _, err := w.Write([]byte("{}")) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - - mux.HandleFunc("/account_recovery", func(w http.ResponseWriter, _ *http.Request) { - err := tester.WriteJSONResponse(w, acme.Account{ - Status: "valid", - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - }) - - key, err := rsa.GenerateKey(rand.Reader, 512) - require.NoError(t, err, "Could not generate test key") - - user := mockUser{ - email: "test@test.com", - regres: &Resource{}, - privatekey: key, - } - - core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key) - require.NoError(t, err) - - registrar := NewRegistrar(core, user) - - res, err := registrar.ResolveAccountByKey() - require.NoError(t, err, "Unexpected error resolving account by key") - - assert.Equal(t, "valid", res.Body.Status, "Unexpected account status") -} diff --git a/vendor/github.com/go-acme/lego/registration/user.go b/vendor/github.com/go-acme/lego/registration/user.go deleted file mode 100644 index 1e29300..0000000 --- a/vendor/github.com/go-acme/lego/registration/user.go +++ /dev/null @@ -1,13 +0,0 @@ -package registration - -import ( - "crypto" -) - -// User interface is to be implemented by users of this library. -// It is used by the client type to get user specific information. -type User interface { - GetEmail() string - GetRegistration() *Resource - GetPrivateKey() crypto.PrivateKey -} diff --git a/vendor/github.com/go-acme/lego/registration/user_test.go b/vendor/github.com/go-acme/lego/registration/user_test.go deleted file mode 100644 index b9c5de3..0000000 --- a/vendor/github.com/go-acme/lego/registration/user_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package registration - -import ( - "crypto" - "crypto/rsa" -) - -type mockUser struct { - email string - regres *Resource - privatekey *rsa.PrivateKey -} - -func (u mockUser) GetEmail() string { return u.email } -func (u mockUser) GetRegistration() *Resource { return u.regres } -func (u mockUser) GetPrivateKey() crypto.PrivateKey { return u.privatekey } diff --git a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/AUTHORS b/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/AUTHORS deleted file mode 100644 index c364af1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/AUTHORS +++ /dev/null @@ -1,15 +0,0 @@ -# This is the official list of cloud authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as: -# Name or Organization -# The email address is not required for organizations. - -Filippo Valsorda -Google Inc. -Ingo Oeser -Palm Stone Games, Inc. -Paweł Knap -Péter Szilágyi -Tyler Treat diff --git a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/CONTRIBUTORS b/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/CONTRIBUTORS deleted file mode 100644 index 3b3cbed..0000000 --- a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/CONTRIBUTORS +++ /dev/null @@ -1,40 +0,0 @@ -# People who have agreed to one of the CLAs and can contribute patches. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# https://developers.google.com/open-source/cla/individual -# https://developers.google.com/open-source/cla/corporate -# -# Names should be added to this file as: -# Name - -# Keep the list alphabetically sorted. - -Alexis Hunt -Andreas Litt -Andrew Gerrand -Brad Fitzpatrick -Burcu Dogan -Dave Day -David Sansome -David Symonds -Filippo Valsorda -Glenn Lewis -Ingo Oeser -James Hall -Johan Euphrosine -Jonathan Amsterdam -Kunpei Sakai -Luna Duclos -Magnus Hiie -Mario Castro -Michael McGreevy -Omar Jarjur -Paweł Knap -Péter Szilágyi -Sarah Adams -Thanatat Tamtan -Toby Burress -Tuo Shan -Tyler Treat diff --git a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/LICENSE b/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/LICENSE deleted file mode 100644 index d645695..0000000 --- a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/compute/metadata/metadata.go b/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/compute/metadata/metadata.go deleted file mode 100644 index 9d0660b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/cloud.google.com/go/compute/metadata/metadata.go +++ /dev/null @@ -1,503 +0,0 @@ -// Copyright 2014 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package metadata provides access to Google Compute Engine (GCE) -// metadata and API service accounts. -// -// This package is a wrapper around the GCE metadata service, -// as documented at https://developers.google.com/compute/docs/metadata. -package metadata // import "cloud.google.com/go/compute/metadata" - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "runtime" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/context/ctxhttp" -) - -const ( - // metadataIP is the documented metadata server IP address. - metadataIP = "169.254.169.254" - - // metadataHostEnv is the environment variable specifying the - // GCE metadata hostname. If empty, the default value of - // metadataIP ("169.254.169.254") is used instead. - // This is variable name is not defined by any spec, as far as - // I know; it was made up for the Go package. - metadataHostEnv = "GCE_METADATA_HOST" - - userAgent = "gcloud-golang/0.1" -) - -type cachedValue struct { - k string - trim bool - mu sync.Mutex - v string -} - -var ( - projID = &cachedValue{k: "project/project-id", trim: true} - projNum = &cachedValue{k: "project/numeric-project-id", trim: true} - instID = &cachedValue{k: "instance/id", trim: true} -) - -var ( - defaultClient = &Client{hc: &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - ResponseHeaderTimeout: 2 * time.Second, - }, - }} - subscribeClient = &Client{hc: &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - }, - }} -) - -// NotDefinedError is returned when requested metadata is not defined. -// -// The underlying string is the suffix after "/computeMetadata/v1/". -// -// This error is not returned if the value is defined to be the empty -// string. -type NotDefinedError string - -func (suffix NotDefinedError) Error() string { - return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix)) -} - -func (c *cachedValue) get(cl *Client) (v string, err error) { - defer c.mu.Unlock() - c.mu.Lock() - if c.v != "" { - return c.v, nil - } - if c.trim { - v, err = cl.getTrimmed(c.k) - } else { - v, err = cl.Get(c.k) - } - if err == nil { - c.v = v - } - return -} - -var ( - onGCEOnce sync.Once - onGCE bool -) - -// OnGCE reports whether this process is running on Google Compute Engine. -func OnGCE() bool { - onGCEOnce.Do(initOnGCE) - return onGCE -} - -func initOnGCE() { - onGCE = testOnGCE() -} - -func testOnGCE() bool { - // The user explicitly said they're on GCE, so trust them. - if os.Getenv(metadataHostEnv) != "" { - return true - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - resc := make(chan bool, 2) - - // Try two strategies in parallel. - // See https://github.com/GoogleCloudPlatform/google-cloud-go/issues/194 - go func() { - req, _ := http.NewRequest("GET", "http://"+metadataIP, nil) - req.Header.Set("User-Agent", userAgent) - res, err := ctxhttp.Do(ctx, defaultClient.hc, req) - if err != nil { - resc <- false - return - } - defer res.Body.Close() - resc <- res.Header.Get("Metadata-Flavor") == "Google" - }() - - go func() { - addrs, err := net.LookupHost("metadata.google.internal") - if err != nil || len(addrs) == 0 { - resc <- false - return - } - resc <- strsContains(addrs, metadataIP) - }() - - tryHarder := systemInfoSuggestsGCE() - if tryHarder { - res := <-resc - if res { - // The first strategy succeeded, so let's use it. - return true - } - // Wait for either the DNS or metadata server probe to - // contradict the other one and say we are running on - // GCE. Give it a lot of time to do so, since the system - // info already suggests we're running on a GCE BIOS. - timer := time.NewTimer(5 * time.Second) - defer timer.Stop() - select { - case res = <-resc: - return res - case <-timer.C: - // Too slow. Who knows what this system is. - return false - } - } - - // There's no hint from the system info that we're running on - // GCE, so use the first probe's result as truth, whether it's - // true or false. The goal here is to optimize for speed for - // users who are NOT running on GCE. We can't assume that - // either a DNS lookup or an HTTP request to a blackholed IP - // address is fast. Worst case this should return when the - // metaClient's Transport.ResponseHeaderTimeout or - // Transport.Dial.Timeout fires (in two seconds). - return <-resc -} - -// systemInfoSuggestsGCE reports whether the local system (without -// doing network requests) suggests that we're running on GCE. If this -// returns true, testOnGCE tries a bit harder to reach its metadata -// server. -func systemInfoSuggestsGCE() bool { - if runtime.GOOS != "linux" { - // We don't have any non-Linux clues available, at least yet. - return false - } - slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name") - name := strings.TrimSpace(string(slurp)) - return name == "Google" || name == "Google Compute Engine" -} - -// Subscribe calls Client.Subscribe on a client designed for subscribing (one with no -// ResponseHeaderTimeout). -func Subscribe(suffix string, fn func(v string, ok bool) error) error { - return subscribeClient.Subscribe(suffix, fn) -} - -// Get calls Client.Get on the default client. -func Get(suffix string) (string, error) { return defaultClient.Get(suffix) } - -// ProjectID returns the current instance's project ID string. -func ProjectID() (string, error) { return defaultClient.ProjectID() } - -// NumericProjectID returns the current instance's numeric project ID. -func NumericProjectID() (string, error) { return defaultClient.NumericProjectID() } - -// InternalIP returns the instance's primary internal IP address. -func InternalIP() (string, error) { return defaultClient.InternalIP() } - -// ExternalIP returns the instance's primary external (public) IP address. -func ExternalIP() (string, error) { return defaultClient.ExternalIP() } - -// Hostname returns the instance's hostname. This will be of the form -// ".c..internal". -func Hostname() (string, error) { return defaultClient.Hostname() } - -// InstanceTags returns the list of user-defined instance tags, -// assigned when initially creating a GCE instance. -func InstanceTags() ([]string, error) { return defaultClient.InstanceTags() } - -// InstanceID returns the current VM's numeric instance ID. -func InstanceID() (string, error) { return defaultClient.InstanceID() } - -// InstanceName returns the current VM's instance ID string. -func InstanceName() (string, error) { return defaultClient.InstanceName() } - -// Zone returns the current VM's zone, such as "us-central1-b". -func Zone() (string, error) { return defaultClient.Zone() } - -// InstanceAttributes calls Client.InstanceAttributes on the default client. -func InstanceAttributes() ([]string, error) { return defaultClient.InstanceAttributes() } - -// ProjectAttributes calls Client.ProjectAttributes on the default client. -func ProjectAttributes() ([]string, error) { return defaultClient.ProjectAttributes() } - -// InstanceAttributeValue calls Client.InstanceAttributeValue on the default client. -func InstanceAttributeValue(attr string) (string, error) { - return defaultClient.InstanceAttributeValue(attr) -} - -// ProjectAttributeValue calls Client.ProjectAttributeValue on the default client. -func ProjectAttributeValue(attr string) (string, error) { - return defaultClient.ProjectAttributeValue(attr) -} - -// Scopes calls Client.Scopes on the default client. -func Scopes(serviceAccount string) ([]string, error) { return defaultClient.Scopes(serviceAccount) } - -func strsContains(ss []string, s string) bool { - for _, v := range ss { - if v == s { - return true - } - } - return false -} - -// A Client provides metadata. -type Client struct { - hc *http.Client -} - -// NewClient returns a Client that can be used to fetch metadata. All HTTP requests -// will use the given http.Client instead of the default client. -func NewClient(c *http.Client) *Client { - return &Client{hc: c} -} - -// getETag returns a value from the metadata service as well as the associated ETag. -// This func is otherwise equivalent to Get. -func (c *Client) getETag(suffix string) (value, etag string, err error) { - // Using a fixed IP makes it very difficult to spoof the metadata service in - // a container, which is an important use-case for local testing of cloud - // deployments. To enable spoofing of the metadata service, the environment - // variable GCE_METADATA_HOST is first inspected to decide where metadata - // requests shall go. - host := os.Getenv(metadataHostEnv) - if host == "" { - // Using 169.254.169.254 instead of "metadata" here because Go - // binaries built with the "netgo" tag and without cgo won't - // know the search suffix for "metadata" is - // ".google.internal", and this IP address is documented as - // being stable anyway. - host = metadataIP - } - url := "http://" + host + "/computeMetadata/v1/" + suffix - req, _ := http.NewRequest("GET", url, nil) - req.Header.Set("Metadata-Flavor", "Google") - req.Header.Set("User-Agent", userAgent) - res, err := c.hc.Do(req) - if err != nil { - return "", "", err - } - defer res.Body.Close() - if res.StatusCode == http.StatusNotFound { - return "", "", NotDefinedError(suffix) - } - if res.StatusCode != 200 { - return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url) - } - all, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", err - } - return string(all), res.Header.Get("Etag"), nil -} - -// Get returns a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// -// If the GCE_METADATA_HOST environment variable is not defined, a default of -// 169.254.169.254 will be used instead. -// -// If the requested metadata is not defined, the returned error will -// be of type NotDefinedError. -func (c *Client) Get(suffix string) (string, error) { - val, _, err := c.getETag(suffix) - return val, err -} - -func (c *Client) getTrimmed(suffix string) (s string, err error) { - s, err = c.Get(suffix) - s = strings.TrimSpace(s) - return -} - -func (c *Client) lines(suffix string) ([]string, error) { - j, err := c.Get(suffix) - if err != nil { - return nil, err - } - s := strings.Split(strings.TrimSpace(j), "\n") - for i := range s { - s[i] = strings.TrimSpace(s[i]) - } - return s, nil -} - -// ProjectID returns the current instance's project ID string. -func (c *Client) ProjectID() (string, error) { return projID.get(c) } - -// NumericProjectID returns the current instance's numeric project ID. -func (c *Client) NumericProjectID() (string, error) { return projNum.get(c) } - -// InstanceID returns the current VM's numeric instance ID. -func (c *Client) InstanceID() (string, error) { return instID.get(c) } - -// InternalIP returns the instance's primary internal IP address. -func (c *Client) InternalIP() (string, error) { - return c.getTrimmed("instance/network-interfaces/0/ip") -} - -// ExternalIP returns the instance's primary external (public) IP address. -func (c *Client) ExternalIP() (string, error) { - return c.getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip") -} - -// Hostname returns the instance's hostname. This will be of the form -// ".c..internal". -func (c *Client) Hostname() (string, error) { - return c.getTrimmed("instance/hostname") -} - -// InstanceTags returns the list of user-defined instance tags, -// assigned when initially creating a GCE instance. -func (c *Client) InstanceTags() ([]string, error) { - var s []string - j, err := c.Get("instance/tags") - if err != nil { - return nil, err - } - if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil { - return nil, err - } - return s, nil -} - -// InstanceName returns the current VM's instance ID string. -func (c *Client) InstanceName() (string, error) { - host, err := c.Hostname() - if err != nil { - return "", err - } - return strings.Split(host, ".")[0], nil -} - -// Zone returns the current VM's zone, such as "us-central1-b". -func (c *Client) Zone() (string, error) { - zone, err := c.getTrimmed("instance/zone") - // zone is of the form "projects//zones/". - if err != nil { - return "", err - } - return zone[strings.LastIndex(zone, "/")+1:], nil -} - -// InstanceAttributes returns the list of user-defined attributes, -// assigned when initially creating a GCE VM instance. The value of an -// attribute can be obtained with InstanceAttributeValue. -func (c *Client) InstanceAttributes() ([]string, error) { return c.lines("instance/attributes/") } - -// ProjectAttributes returns the list of user-defined attributes -// applying to the project as a whole, not just this VM. The value of -// an attribute can be obtained with ProjectAttributeValue. -func (c *Client) ProjectAttributes() ([]string, error) { return c.lines("project/attributes/") } - -// InstanceAttributeValue returns the value of the provided VM -// instance attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// InstanceAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func (c *Client) InstanceAttributeValue(attr string) (string, error) { - return c.Get("instance/attributes/" + attr) -} - -// ProjectAttributeValue returns the value of the provided -// project attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// ProjectAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func (c *Client) ProjectAttributeValue(attr string) (string, error) { - return c.Get("project/attributes/" + attr) -} - -// Scopes returns the service account scopes for the given account. -// The account may be empty or the string "default" to use the instance's -// main account. -func (c *Client) Scopes(serviceAccount string) ([]string, error) { - if serviceAccount == "" { - serviceAccount = "default" - } - return c.lines("instance/service-accounts/" + serviceAccount + "/scopes") -} - -// Subscribe subscribes to a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// The suffix may contain query parameters. -// -// Subscribe calls fn with the latest metadata value indicated by the provided -// suffix. If the metadata value is deleted, fn is called with the empty string -// and ok false. Subscribe blocks until fn returns a non-nil error or the value -// is deleted. Subscribe returns the error value returned from the last call to -// fn, which may be nil when ok == false. -func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) error { - const failedSubscribeSleep = time.Second * 5 - - // First check to see if the metadata value exists at all. - val, lastETag, err := c.getETag(suffix) - if err != nil { - return err - } - - if err := fn(val, true); err != nil { - return err - } - - ok := true - if strings.ContainsRune(suffix, '?') { - suffix += "&wait_for_change=true&last_etag=" - } else { - suffix += "?wait_for_change=true&last_etag=" - } - for { - val, etag, err := c.getETag(suffix + url.QueryEscape(lastETag)) - if err != nil { - if _, deleted := err.(NotDefinedError); !deleted { - time.Sleep(failedSubscribeSleep) - continue // Retry on other errors. - } - ok = false - } - lastETag = etag - - if err := fn(val, ok); err != nil || !ok { - return err - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/LICENSE deleted file mode 100644 index af39a91..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2016 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/NOTICE b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/NOTICE deleted file mode 100644 index 2d1d726..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Microsoft Azure-SDK-for-Go -Copyright 2014-2017 Microsoft - -This product includes software developed at -the Microsoft Corporation (https://www.microsoft.com). diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/client.go deleted file mode 100644 index 482d2f9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/client.go +++ /dev/null @@ -1,51 +0,0 @@ -// Package dns implements the Azure ARM Dns service API version 2017-09-01. -// -// The DNS Management Client. -package dns - -// Copyright (c) Microsoft and contributors. 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. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/Azure/go-autorest/autorest" -) - -const ( - // DefaultBaseURI is the default URI used for the service Dns - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Dns. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string -} - -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWithBaseURI creates an instance of the BaseClient client. -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/models.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/models.go deleted file mode 100644 index ccdb50b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/models.go +++ /dev/null @@ -1,737 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. 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. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/to" - "net/http" -) - -// RecordType enumerates the values for record type. -type RecordType string - -const ( - // A ... - A RecordType = "A" - // AAAA ... - AAAA RecordType = "AAAA" - // CAA ... - CAA RecordType = "CAA" - // CNAME ... - CNAME RecordType = "CNAME" - // MX ... - MX RecordType = "MX" - // NS ... - NS RecordType = "NS" - // PTR ... - PTR RecordType = "PTR" - // SOA ... - SOA RecordType = "SOA" - // SRV ... - SRV RecordType = "SRV" - // TXT ... - TXT RecordType = "TXT" -) - -// PossibleRecordTypeValues returns an array of possible values for the RecordType const type. -func PossibleRecordTypeValues() []RecordType { - return []RecordType{A, AAAA, CAA, CNAME, MX, NS, PTR, SOA, SRV, TXT} -} - -// AaaaRecord an AAAA record. -type AaaaRecord struct { - // Ipv6Address - The IPv6 address of this AAAA record. - Ipv6Address *string `json:"ipv6Address,omitempty"` -} - -// ARecord an A record. -type ARecord struct { - // Ipv4Address - The IPv4 address of this A record. - Ipv4Address *string `json:"ipv4Address,omitempty"` -} - -// CaaRecord a CAA record. -type CaaRecord struct { - // Flags - The flags for this CAA record as an integer between 0 and 255. - Flags *int32 `json:"flags,omitempty"` - // Tag - The tag for this CAA record. - Tag *string `json:"tag,omitempty"` - // Value - The value for this CAA record. - Value *string `json:"value,omitempty"` -} - -// CloudError an error message -type CloudError struct { - // Error - The error message body - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody the body of an error message -type CloudErrorBody struct { - // Code - The error code - Code *string `json:"code,omitempty"` - // Message - A description of what caused the error - Message *string `json:"message,omitempty"` - // Target - The target resource of the error message - Target *string `json:"target,omitempty"` - // Details - Extra error information - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// CnameRecord a CNAME record. -type CnameRecord struct { - // Cname - The canonical name for this CNAME record. - Cname *string `json:"cname,omitempty"` -} - -// MxRecord an MX record. -type MxRecord struct { - // Preference - The preference value for this MX record. - Preference *int32 `json:"preference,omitempty"` - // Exchange - The domain name of the mail host for this MX record. - Exchange *string `json:"exchange,omitempty"` -} - -// NsRecord an NS record. -type NsRecord struct { - // Nsdname - The name server name for this NS record. - Nsdname *string `json:"nsdname,omitempty"` -} - -// PtrRecord a PTR record. -type PtrRecord struct { - // Ptrdname - The PTR target domain name for this PTR record. - Ptrdname *string `json:"ptrdname,omitempty"` -} - -// RecordSet describes a DNS record set (a collection of DNS records with the same name and type). -type RecordSet struct { - autorest.Response `json:"-"` - // ID - The ID of the record set. - ID *string `json:"id,omitempty"` - // Name - The name of the record set. - Name *string `json:"name,omitempty"` - // Type - The type of the record set. - Type *string `json:"type,omitempty"` - // Etag - The etag of the record set. - Etag *string `json:"etag,omitempty"` - // RecordSetProperties - The properties of the record set. - *RecordSetProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSet. -func (rs RecordSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rs.ID != nil { - objectMap["id"] = rs.ID - } - if rs.Name != nil { - objectMap["name"] = rs.Name - } - if rs.Type != nil { - objectMap["type"] = rs.Type - } - if rs.Etag != nil { - objectMap["etag"] = rs.Etag - } - if rs.RecordSetProperties != nil { - objectMap["properties"] = rs.RecordSetProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RecordSet struct. -func (rs *RecordSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rs.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rs.Etag = &etag - } - case "properties": - if v != nil { - var recordSetProperties RecordSetProperties - err = json.Unmarshal(*v, &recordSetProperties) - if err != nil { - return err - } - rs.RecordSetProperties = &recordSetProperties - } - } - } - - return nil -} - -// RecordSetListResult the response to a record set List operation. -type RecordSetListResult struct { - autorest.Response `json:"-"` - // Value - Information about the record sets in the response. - Value *[]RecordSet `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RecordSetListResultIterator provides access to a complete listing of RecordSet values. -type RecordSetListResultIterator struct { - i int - page RecordSetListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RecordSetListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RecordSetListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RecordSetListResultIterator) Response() RecordSetListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RecordSetListResultIterator) Value() RecordSet { - if !iter.page.NotDone() { - return RecordSet{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (rslr RecordSetListResult) IsEmpty() bool { - return rslr.Value == nil || len(*rslr.Value) == 0 -} - -// recordSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rslr RecordSetListResult) recordSetListResultPreparer() (*http.Request, error) { - if rslr.NextLink == nil || len(to.String(rslr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rslr.NextLink))) -} - -// RecordSetListResultPage contains a page of RecordSet values. -type RecordSetListResultPage struct { - fn func(RecordSetListResult) (RecordSetListResult, error) - rslr RecordSetListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RecordSetListResultPage) Next() error { - next, err := page.fn(page.rslr) - if err != nil { - return err - } - page.rslr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RecordSetListResultPage) NotDone() bool { - return !page.rslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RecordSetListResultPage) Response() RecordSetListResult { - return page.rslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RecordSetListResultPage) Values() []RecordSet { - if page.rslr.IsEmpty() { - return nil - } - return *page.rslr.Value -} - -// RecordSetProperties represents the properties of the records in the record set. -type RecordSetProperties struct { - // Metadata - The metadata attached to the record set. - Metadata map[string]*string `json:"metadata"` - // TTL - The TTL (time-to-live) of the records in the record set. - TTL *int64 `json:"TTL,omitempty"` - // Fqdn - Fully qualified domain name of the record set. - Fqdn *string `json:"fqdn,omitempty"` - // ARecords - The list of A records in the record set. - ARecords *[]ARecord `json:"ARecords,omitempty"` - // AaaaRecords - The list of AAAA records in the record set. - AaaaRecords *[]AaaaRecord `json:"AAAARecords,omitempty"` - // MxRecords - The list of MX records in the record set. - MxRecords *[]MxRecord `json:"MXRecords,omitempty"` - // NsRecords - The list of NS records in the record set. - NsRecords *[]NsRecord `json:"NSRecords,omitempty"` - // PtrRecords - The list of PTR records in the record set. - PtrRecords *[]PtrRecord `json:"PTRRecords,omitempty"` - // SrvRecords - The list of SRV records in the record set. - SrvRecords *[]SrvRecord `json:"SRVRecords,omitempty"` - // TxtRecords - The list of TXT records in the record set. - TxtRecords *[]TxtRecord `json:"TXTRecords,omitempty"` - // CnameRecord - The CNAME record in the record set. - CnameRecord *CnameRecord `json:"CNAMERecord,omitempty"` - // SoaRecord - The SOA record in the record set. - SoaRecord *SoaRecord `json:"SOARecord,omitempty"` - // CaaRecords - The list of CAA records in the record set. - CaaRecords *[]CaaRecord `json:"caaRecords,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSetProperties. -func (rsp RecordSetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rsp.Metadata != nil { - objectMap["metadata"] = rsp.Metadata - } - if rsp.TTL != nil { - objectMap["TTL"] = rsp.TTL - } - if rsp.Fqdn != nil { - objectMap["fqdn"] = rsp.Fqdn - } - if rsp.ARecords != nil { - objectMap["ARecords"] = rsp.ARecords - } - if rsp.AaaaRecords != nil { - objectMap["AAAARecords"] = rsp.AaaaRecords - } - if rsp.MxRecords != nil { - objectMap["MXRecords"] = rsp.MxRecords - } - if rsp.NsRecords != nil { - objectMap["NSRecords"] = rsp.NsRecords - } - if rsp.PtrRecords != nil { - objectMap["PTRRecords"] = rsp.PtrRecords - } - if rsp.SrvRecords != nil { - objectMap["SRVRecords"] = rsp.SrvRecords - } - if rsp.TxtRecords != nil { - objectMap["TXTRecords"] = rsp.TxtRecords - } - if rsp.CnameRecord != nil { - objectMap["CNAMERecord"] = rsp.CnameRecord - } - if rsp.SoaRecord != nil { - objectMap["SOARecord"] = rsp.SoaRecord - } - if rsp.CaaRecords != nil { - objectMap["caaRecords"] = rsp.CaaRecords - } - return json.Marshal(objectMap) -} - -// RecordSetUpdateParameters parameters supplied to update a record set. -type RecordSetUpdateParameters struct { - // RecordSet - Specifies information about the record set being updated. - RecordSet *RecordSet `json:"RecordSet,omitempty"` -} - -// Resource common properties of an Azure Resource Manager resource -type Resource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.ID != nil { - objectMap["id"] = r.ID - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// SoaRecord an SOA record. -type SoaRecord struct { - // Host - The domain name of the authoritative name server for this SOA record. - Host *string `json:"host,omitempty"` - // Email - The email contact for this SOA record. - Email *string `json:"email,omitempty"` - // SerialNumber - The serial number for this SOA record. - SerialNumber *int64 `json:"serialNumber,omitempty"` - // RefreshTime - The refresh value for this SOA record. - RefreshTime *int64 `json:"refreshTime,omitempty"` - // RetryTime - The retry time for this SOA record. - RetryTime *int64 `json:"retryTime,omitempty"` - // ExpireTime - The expire time for this SOA record. - ExpireTime *int64 `json:"expireTime,omitempty"` - // MinimumTTL - The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - MinimumTTL *int64 `json:"minimumTTL,omitempty"` -} - -// SrvRecord an SRV record. -type SrvRecord struct { - // Priority - The priority value for this SRV record. - Priority *int32 `json:"priority,omitempty"` - // Weight - The weight value for this SRV record. - Weight *int32 `json:"weight,omitempty"` - // Port - The port value for this SRV record. - Port *int32 `json:"port,omitempty"` - // Target - The target domain name for this SRV record. - Target *string `json:"target,omitempty"` -} - -// SubResource a reference to a another resource -type SubResource struct { - // ID - Resource Id. - ID *string `json:"id,omitempty"` -} - -// TxtRecord a TXT record. -type TxtRecord struct { - // Value - The text value of this TXT record. - Value *[]string `json:"value,omitempty"` -} - -// Zone describes a DNS zone. -type Zone struct { - autorest.Response `json:"-"` - // Etag - The etag of the zone. - Etag *string `json:"etag,omitempty"` - // ZoneProperties - The properties of the zone. - *ZoneProperties `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Zone. -func (z Zone) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if z.Etag != nil { - objectMap["etag"] = z.Etag - } - if z.ZoneProperties != nil { - objectMap["properties"] = z.ZoneProperties - } - if z.ID != nil { - objectMap["id"] = z.ID - } - if z.Name != nil { - objectMap["name"] = z.Name - } - if z.Type != nil { - objectMap["type"] = z.Type - } - if z.Location != nil { - objectMap["location"] = z.Location - } - if z.Tags != nil { - objectMap["tags"] = z.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Zone struct. -func (z *Zone) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - z.Etag = &etag - } - case "properties": - if v != nil { - var zoneProperties ZoneProperties - err = json.Unmarshal(*v, &zoneProperties) - if err != nil { - return err - } - z.ZoneProperties = &zoneProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - z.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - z.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - z.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - z.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - z.Tags = tags - } - } - } - - return nil -} - -// ZoneListResult the response to a Zone List or ListAll operation. -type ZoneListResult struct { - autorest.Response `json:"-"` - // Value - Information about the DNS zones. - Value *[]Zone `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ZoneListResultIterator provides access to a complete listing of Zone values. -type ZoneListResultIterator struct { - i int - page ZoneListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ZoneListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ZoneListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ZoneListResultIterator) Response() ZoneListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ZoneListResultIterator) Value() Zone { - if !iter.page.NotDone() { - return Zone{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (zlr ZoneListResult) IsEmpty() bool { - return zlr.Value == nil || len(*zlr.Value) == 0 -} - -// zoneListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (zlr ZoneListResult) zoneListResultPreparer() (*http.Request, error) { - if zlr.NextLink == nil || len(to.String(zlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(zlr.NextLink))) -} - -// ZoneListResultPage contains a page of Zone values. -type ZoneListResultPage struct { - fn func(ZoneListResult) (ZoneListResult, error) - zlr ZoneListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ZoneListResultPage) Next() error { - next, err := page.fn(page.zlr) - if err != nil { - return err - } - page.zlr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ZoneListResultPage) NotDone() bool { - return !page.zlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ZoneListResultPage) Response() ZoneListResult { - return page.zlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ZoneListResultPage) Values() []Zone { - if page.zlr.IsEmpty() { - return nil - } - return *page.zlr.Value -} - -// ZoneProperties represents the properties of the zone. -type ZoneProperties struct { - // MaxNumberOfRecordSets - The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - MaxNumberOfRecordSets *int64 `json:"maxNumberOfRecordSets,omitempty"` - // NumberOfRecordSets - The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NumberOfRecordSets *int64 `json:"numberOfRecordSets,omitempty"` - // NameServers - The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NameServers *[]string `json:"nameServers,omitempty"` -} - -// ZonesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ZonesDeleteFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *ZonesDeleteFuture) Result(client ZonesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.Done(client) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("dns.ZonesDeleteFuture") - return - } - ar.Response = future.Response() - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/recordsets.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/recordsets.go deleted file mode 100644 index 1bd1875..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/recordsets.go +++ /dev/null @@ -1,616 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. 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. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "net/http" -) - -// RecordSetsClient is the the DNS Management Client. -type RecordSetsClient struct { - BaseClient -} - -// NewRecordSetsClient creates an instance of the RecordSetsClient client. -func NewRecordSetsClient(subscriptionID string) RecordSetsClient { - return NewRecordSetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRecordSetsClientWithBaseURI creates an instance of the RecordSetsClient client. -func NewRecordSetsClientWithBaseURI(baseURI string, subscriptionID string) RecordSetsClient { - return RecordSetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a record set within a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. Record sets of type SOA can be updated but not -// created (they are created when the DNS zone is created). -// parameters - parameters supplied to the CreateOrUpdate operation. -// ifMatch - the etag of the record set. Omit this value to always overwrite the current record set. Specify -// the last-seen etag value to prevent accidentally overwritting any concurrent changes. -// ifNoneMatch - set to '*' to allow a new record set to be created, but to prevent updating an existing record -// set. Other values will be ignored. -func (client RecordSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RecordSetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - if len(ifNoneMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) CreateOrUpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a record set from a DNS zone. This operation cannot be undone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are -// deleted when the DNS zone is deleted). -// ifMatch - the etag of the record set. Omit this value to always delete the current record set. Specify the -// last-seen etag value to prevent accidentally deleting any concurrent changes. -func (client RecordSetsClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RecordSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a record set. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. -func (client RecordSetsClient) Get(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RecordSetsClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) GetResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByDNSZone lists all record sets in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByDNSZone(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListByDNSZone", err.Error()) - } - - result.fn = client.listByDNSZoneNextResults - req, err := client.ListByDNSZonePreparer(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure responding to request") - } - - return -} - -// ListByDNSZonePreparer prepares the ListByDNSZone request. -func (client RecordSetsClient) ListByDNSZonePreparer(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDNSZoneSender sends the ListByDNSZone request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByDNSZoneSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDNSZoneResponder handles the response to the ListByDNSZone request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByDNSZoneResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByDNSZoneNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByDNSZoneNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByDNSZoneComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByDNSZoneComplete(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByDNSZone(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - return -} - -// ListByType lists the record sets of a specified type in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// recordType - the type of record sets to enumerate. -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByType(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListByType", err.Error()) - } - - result.fn = client.listByTypeNextResults - req, err := client.ListByTypePreparer(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", nil, "Failure preparing request") - return - } - - resp, err := client.ListByTypeSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure responding to request") - } - - return -} - -// ListByTypePreparer prepares the ListByType request. -func (client RecordSetsClient) ListByTypePreparer(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByTypeSender sends the ListByType request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByTypeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByTypeResponder handles the response to the ListByType request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByTypeResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByTypeNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByTypeNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByTypeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByTypeComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByTypeComplete(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByType(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - return -} - -// Update updates a record set within a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. -// parameters - parameters supplied to the Update operation. -// ifMatch - the etag of the record set. Omit this value to always overwrite the current record set. Specify -// the last-seen etag value to prevent accidentally overwritting concurrent changes. -func (client RecordSetsClient) Update(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure responding to request") - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client RecordSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) UpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/version.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/version.go deleted file mode 100644 index 0556b61..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/version.go +++ /dev/null @@ -1,30 +0,0 @@ -package dns - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft and contributors. 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. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " dns/2017-09-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/zones.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/zones.go deleted file mode 100644 index 4a0be76..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/zones.go +++ /dev/null @@ -1,491 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. 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. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "net/http" -) - -// ZonesClient is the the DNS Management Client. -type ZonesClient struct { - BaseClient -} - -// NewZonesClient creates an instance of the ZonesClient client. -func NewZonesClient(subscriptionID string) ZonesClient { - return NewZonesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewZonesClientWithBaseURI creates an instance of the ZonesClient client. -func NewZonesClientWithBaseURI(baseURI string, subscriptionID string) ZonesClient { - return ZonesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DNS zone. Does not modify DNS records within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// parameters - parameters supplied to the CreateOrUpdate operation. -// ifMatch - the etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the -// last-seen etag value to prevent accidentally overwritting any concurrent changes. -// ifNoneMatch - set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. -// Other values will be ignored. -func (client ZonesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ZonesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - if len(ifNoneMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ZonesClient) CreateOrUpdateResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be -// undone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// ifMatch - the etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen -// etag value to prevent accidentally deleting any concurrent changes. -func (client ZonesClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (result ZonesDeleteFuture, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ZonesClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) DeleteSender(req *http.Request) (future ZonesDeleteFuture, err error) { - var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) - if err != nil { - return - } - future.Future, err = azure.NewFutureFromResponse(resp) - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ZonesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -func (client ZonesClient) Get(ctx context.Context, resourceGroupName string, zoneName string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client ZonesClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ZonesClient) GetResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists the DNS zones in all resource groups in a subscription. -// Parameters: -// top - the maximum number of DNS zones to return. If not specified, returns up to 100 zones. -func (client ZonesClient) List(ctx context.Context, top *int32) (result ZoneListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ZonesClient) ListPreparer(ctx context.Context, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ZonesClient) listNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListComplete(ctx context.Context, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.List(ctx, top) - return -} - -// ListByResourceGroup lists the DNS zones within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -func (client ZonesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "ListByResourceGroup", err.Error()) - } - - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure responding to request") - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ZonesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListByResourceGroupResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ZonesClient) listByResourceGroupNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, top) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/version/version.go deleted file mode 100644 index 3153043..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/azure-sdk-for-go/version/version.go +++ /dev/null @@ -1,21 +0,0 @@ -package version - -// Copyright (c) Microsoft and contributors. 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. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Number contains the semantic version of this SDK. -const Number = "v19.1.0" diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/LICENSE deleted file mode 100644 index b9d6a27..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/config.go deleted file mode 100644 index bee5e61..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/config.go +++ /dev/null @@ -1,81 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/url" -) - -const ( - activeDirectoryAPIVersion = "1.0" -) - -// OAuthConfig represents the endpoints needed -// in OAuth operations -type OAuthConfig struct { - AuthorityEndpoint url.URL `json:"authorityEndpoint"` - AuthorizeEndpoint url.URL `json:"authorizeEndpoint"` - TokenEndpoint url.URL `json:"tokenEndpoint"` - DeviceCodeEndpoint url.URL `json:"deviceCodeEndpoint"` -} - -// IsZero returns true if the OAuthConfig object is zero-initialized. -func (oac OAuthConfig) IsZero() bool { - return oac == OAuthConfig{} -} - -func validateStringParam(param, name string) error { - if len(param) == 0 { - return fmt.Errorf("parameter '" + name + "' cannot be empty") - } - return nil -} - -// NewOAuthConfig returns an OAuthConfig with tenant specific urls -func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { - if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { - return nil, err - } - // it's legal for tenantID to be empty so don't validate it - const activeDirectoryEndpointTemplate = "%s/oauth2/%s?api-version=%s" - u, err := url.Parse(activeDirectoryEndpoint) - if err != nil { - return nil, err - } - authorityURL, err := u.Parse(tenantID) - if err != nil { - return nil, err - } - authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", activeDirectoryAPIVersion)) - if err != nil { - return nil, err - } - tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", activeDirectoryAPIVersion)) - if err != nil { - return nil, err - } - deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", activeDirectoryAPIVersion)) - if err != nil { - return nil, err - } - - return &OAuthConfig{ - AuthorityEndpoint: *authorityURL, - AuthorizeEndpoint: *authorizeURL, - TokenEndpoint: *tokenURL, - DeviceCodeEndpoint: *deviceCodeURL, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go deleted file mode 100644 index b38f4c2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go +++ /dev/null @@ -1,242 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/* - This file is largely based on rjw57/oauth2device's code, with the follow differences: - * scope -> resource, and only allow a single one - * receive "Message" in the DeviceCode struct and show it to users as the prompt - * azure-xplat-cli has the following behavior that this emulates: - - does not send client_secret during the token exchange - - sends resource again in the token exchange request -*/ - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" -) - -const ( - logPrefix = "autorest/adal/devicetoken:" -) - -var ( - // ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow - ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix) - - // ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow - ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix) - - // ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow - ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix) - - // ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow - ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix) - - // ErrDeviceSlowDown represents the service telling us we're polling too often during device flow - ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix) - - // ErrDeviceCodeEmpty represents an empty device code from the device endpoint while using device flow - ErrDeviceCodeEmpty = fmt.Errorf("%s Error while retrieving device code: Device Code Empty", logPrefix) - - // ErrOAuthTokenEmpty represents an empty OAuth token from the token endpoint when using device flow - ErrOAuthTokenEmpty = fmt.Errorf("%s Error while retrieving OAuth token: Token Empty", logPrefix) - - errCodeSendingFails = "Error occurred while sending request for Device Authorization Code" - errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint" - errTokenSendingFails = "Error occurred while sending request with device code for a token" - errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)" - errStatusNotOK = "Error HTTP status != 200" -) - -// DeviceCode is the object returned by the device auth endpoint -// It contains information to instruct the user to complete the auth flow -type DeviceCode struct { - DeviceCode *string `json:"device_code,omitempty"` - UserCode *string `json:"user_code,omitempty"` - VerificationURL *string `json:"verification_url,omitempty"` - ExpiresIn *int64 `json:"expires_in,string,omitempty"` - Interval *int64 `json:"interval,string,omitempty"` - - Message *string `json:"message"` // Azure specific - Resource string // store the following, stored when initiating, used when exchanging - OAuthConfig OAuthConfig - ClientID string -} - -// TokenError is the object returned by the token exchange endpoint -// when something is amiss -type TokenError struct { - Error *string `json:"error,omitempty"` - ErrorCodes []int `json:"error_codes,omitempty"` - ErrorDescription *string `json:"error_description,omitempty"` - Timestamp *string `json:"timestamp,omitempty"` - TraceID *string `json:"trace_id,omitempty"` -} - -// DeviceToken is the object return by the token exchange endpoint -// It can either look like a Token or an ErrorToken, so put both here -// and check for presence of "Error" to know if we are in error state -type deviceToken struct { - Token - TokenError -} - -// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode -// that can be used with CheckForUserCompletion or WaitForUserCompletion. -func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { - v := url.Values{ - "client_id": []string{clientID}, - "resource": []string{resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) - } - - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrDeviceCodeEmpty - } - - var code DeviceCode - err = json.Unmarshal(rb, &code) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - code.ClientID = clientID - code.Resource = resource - code.OAuthConfig = oauthConfig - - return &code, nil -} - -// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint -// to see if the device flow has: been completed, timed out, or otherwise failed -func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - v := url.Values{ - "client_id": []string{code.ClientID}, - "code": []string{*code.DeviceCode}, - "grant_type": []string{OAuthGrantTypeDeviceCode}, - "resource": []string{code.Resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, code.OAuthConfig.TokenEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK && len(strings.Trim(string(rb), " ")) == 0 { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, errStatusNotOK) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrOAuthTokenEmpty - } - - var token deviceToken - err = json.Unmarshal(rb, &token) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if token.Error == nil { - return &token.Token, nil - } - - switch *token.Error { - case "authorization_pending": - return nil, ErrDeviceAuthorizationPending - case "slow_down": - return nil, ErrDeviceSlowDown - case "access_denied": - return nil, ErrDeviceAccessDenied - case "code_expired": - return nil, ErrDeviceCodeExpired - default: - return nil, ErrDeviceGeneric - } -} - -// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. -// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. -func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - intervalDuration := time.Duration(*code.Interval) * time.Second - waitDuration := intervalDuration - - for { - token, err := CheckForUserCompletion(sender, code) - - if err == nil { - return token, nil - } - - switch err { - case ErrDeviceSlowDown: - waitDuration += waitDuration - case ErrDeviceAuthorizationPending: - // noop - default: // everything else is "fatal" to us - return nil, err - } - - if waitDuration > (intervalDuration * 3) { - return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) - } - - time.Sleep(waitDuration) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go deleted file mode 100644 index 9e15f27..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go +++ /dev/null @@ -1,73 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" -) - -// LoadToken restores a Token object from a file located at 'path'. -func LoadToken(path string) (*Token, error) { - file, err := os.Open(path) - if err != nil { - return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - } - defer file.Close() - - var token Token - - dec := json.NewDecoder(file) - if err = dec.Decode(&token); err != nil { - return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err) - } - return &token, nil -} - -// SaveToken persists an oauth token at the given location on disk. -// It moves the new file into place so it can safely be used to replace an existing file -// that maybe accessed by multiple processes. -func SaveToken(path string, mode os.FileMode, token Token) error { - dir := filepath.Dir(path) - err := os.MkdirAll(dir, os.ModePerm) - if err != nil { - return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err) - } - - newFile, err := ioutil.TempFile(dir, "token") - if err != nil { - return fmt.Errorf("failed to create the temp file to write the token: %v", err) - } - tempPath := newFile.Name() - - if err := json.NewEncoder(newFile).Encode(token); err != nil { - return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err) - } - if err := newFile.Close(); err != nil { - return fmt.Errorf("failed to close temp file %s: %v", tempPath, err) - } - - // Atomic replace to avoid multi-writer file corruptions - if err := os.Rename(tempPath, path); err != nil { - return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err) - } - if err := os.Chmod(path, mode); err != nil { - return fmt.Errorf("failed to chmod the token file %s: %v", path, err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go deleted file mode 100644 index 0e5ad14..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go +++ /dev/null @@ -1,60 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "net/http" -) - -const ( - contentType = "Content-Type" - mimeTypeFormPost = "application/x-www-form-urlencoded" -) - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(&http.Client{}, decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/token.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/token.go deleted file mode 100644 index 32aea83..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/adal/token.go +++ /dev/null @@ -1,968 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "math" - "net" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/version" - "github.com/dgrijalva/jwt-go" -) - -const ( - defaultRefresh = 5 * time.Minute - - // OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow - OAuthGrantTypeDeviceCode = "device_code" - - // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows - OAuthGrantTypeClientCredentials = "client_credentials" - - // OAuthGrantTypeUserPass is the "grant_type" identifier used in username and password auth flows - OAuthGrantTypeUserPass = "password" - - // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows - OAuthGrantTypeRefreshToken = "refresh_token" - - // OAuthGrantTypeAuthorizationCode is the "grant_type" identifier used in authorization code flows - OAuthGrantTypeAuthorizationCode = "authorization_code" - - // metadataHeader is the header required by MSI extension - metadataHeader = "Metadata" - - // msiEndpoint is the well known endpoint for getting MSI authentications tokens - msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" - - // the default number of attempts to refresh an MSI authentication token - defaultMaxMSIRefreshAttempts = 5 -) - -// OAuthTokenProvider is an interface which should be implemented by an access token retriever -type OAuthTokenProvider interface { - OAuthToken() string -} - -// TokenRefreshError is an interface used by errors returned during token refresh. -type TokenRefreshError interface { - error - Response() *http.Response -} - -// Refresher is an interface for token refresh functionality -type Refresher interface { - Refresh() error - RefreshExchange(resource string) error - EnsureFresh() error -} - -// RefresherWithContext is an interface for token refresh functionality -type RefresherWithContext interface { - RefreshWithContext(ctx context.Context) error - RefreshExchangeWithContext(ctx context.Context, resource string) error - EnsureFreshWithContext(ctx context.Context) error -} - -// TokenRefreshCallback is the type representing callbacks that will be called after -// a successful token refresh -type TokenRefreshCallback func(Token) error - -// Token encapsulates the access token used to authorize Azure requests. -type Token struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - - ExpiresIn string `json:"expires_in"` - ExpiresOn string `json:"expires_on"` - NotBefore string `json:"not_before"` - - Resource string `json:"resource"` - Type string `json:"token_type"` -} - -// IsZero returns true if the token object is zero-initialized. -func (t Token) IsZero() bool { - return t == Token{} -} - -// Expires returns the time.Time when the Token expires. -func (t Token) Expires() time.Time { - s, err := strconv.Atoi(t.ExpiresOn) - if err != nil { - s = -3600 - } - - expiration := date.NewUnixTimeFromSeconds(float64(s)) - - return time.Time(expiration).UTC() -} - -// IsExpired returns true if the Token is expired, false otherwise. -func (t Token) IsExpired() bool { - return t.WillExpireIn(0) -} - -// WillExpireIn returns true if the Token will expire after the passed time.Duration interval -// from now, false otherwise. -func (t Token) WillExpireIn(d time.Duration) bool { - return !t.Expires().After(time.Now().Add(d)) -} - -//OAuthToken return the current access token -func (t *Token) OAuthToken() string { - return t.AccessToken -} - -// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form -// that is submitted when acquiring an oAuth token. -type ServicePrincipalSecret interface { - SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error -} - -// ServicePrincipalNoSecret represents a secret type that contains no secret -// meaning it is not valid for fetching a fresh token. This is used by Manual -type ServicePrincipalNoSecret struct { -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret -// It only returns an error for the ServicePrincipalNoSecret type -func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") -} - -// MarshalJSON implements the json.Marshaler interface. -func (noSecret ServicePrincipalNoSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalNoSecret", - }) -} - -// ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization. -type ServicePrincipalTokenSecret struct { - ClientSecret string `json:"value"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using the client_secret. -func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("client_secret", tokenSecret.ClientSecret) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (tokenSecret ServicePrincipalTokenSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Value string `json:"value"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalTokenSecret", - Value: tokenSecret.ClientSecret, - }) -} - -// ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs. -type ServicePrincipalCertificateSecret struct { - Certificate *x509.Certificate - PrivateKey *rsa.PrivateKey -} - -// SignJwt returns the JWT signed with the certificate's private key. -func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { - hasher := sha1.New() - _, err := hasher.Write(secret.Certificate.Raw) - if err != nil { - return "", err - } - - thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) - - // The jti (JWT ID) claim provides a unique identifier for the JWT. - jti := make([]byte, 20) - _, err = rand.Read(jti) - if err != nil { - return "", err - } - - token := jwt.New(jwt.SigningMethodRS256) - token.Header["x5t"] = thumbprint - token.Claims = jwt.MapClaims{ - "aud": spt.inner.OauthConfig.TokenEndpoint.String(), - "iss": spt.inner.ClientID, - "sub": spt.inner.ClientID, - "jti": base64.URLEncoding.EncodeToString(jti), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(time.Hour * 24).Unix(), - } - - signedString, err := token.SignedString(secret.PrivateKey) - return signedString, err -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate. -func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - jwt, err := secret.SignJwt(spt) - if err != nil { - return err - } - - v.Set("client_assertion", jwt) - v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalCertificateSecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalCertificateSecret is not supported") -} - -// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension. -type ServicePrincipalMSISecret struct { -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (msiSecret ServicePrincipalMSISecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalMSISecret is not supported") -} - -// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth. -type ServicePrincipalUsernamePasswordSecret struct { - Username string `json:"username"` - Password string `json:"password"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("username", secret.Username) - v.Set("password", secret.Password) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalUsernamePasswordSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Username string `json:"username"` - Password string `json:"password"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalUsernamePasswordSecret", - Username: secret.Username, - Password: secret.Password, - }) -} - -// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth. -type ServicePrincipalAuthorizationCodeSecret struct { - ClientSecret string `json:"value"` - AuthorizationCode string `json:"authCode"` - RedirectURI string `json:"redirect"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("code", secret.AuthorizationCode) - v.Set("client_secret", secret.ClientSecret) - v.Set("redirect_uri", secret.RedirectURI) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalAuthorizationCodeSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Value string `json:"value"` - AuthCode string `json:"authCode"` - Redirect string `json:"redirect"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalAuthorizationCodeSecret", - Value: secret.ClientSecret, - AuthCode: secret.AuthorizationCode, - Redirect: secret.RedirectURI, - }) -} - -// ServicePrincipalToken encapsulates a Token created for a Service Principal. -type ServicePrincipalToken struct { - inner servicePrincipalToken - refreshLock *sync.RWMutex - sender Sender - refreshCallbacks []TokenRefreshCallback - // MaxMSIRefreshAttempts is the maximum number of attempts to refresh an MSI token. - MaxMSIRefreshAttempts int -} - -// MarshalTokenJSON returns the marshalled inner token. -func (spt ServicePrincipalToken) MarshalTokenJSON() ([]byte, error) { - return json.Marshal(spt.inner.Token) -} - -// SetRefreshCallbacks replaces any existing refresh callbacks with the specified callbacks. -func (spt *ServicePrincipalToken) SetRefreshCallbacks(callbacks []TokenRefreshCallback) { - spt.refreshCallbacks = callbacks -} - -// MarshalJSON implements the json.Marshaler interface. -func (spt ServicePrincipalToken) MarshalJSON() ([]byte, error) { - return json.Marshal(spt.inner) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (spt *ServicePrincipalToken) UnmarshalJSON(data []byte) error { - // need to determine the token type - raw := map[string]interface{}{} - err := json.Unmarshal(data, &raw) - if err != nil { - return err - } - secret := raw["secret"].(map[string]interface{}) - switch secret["type"] { - case "ServicePrincipalNoSecret": - spt.inner.Secret = &ServicePrincipalNoSecret{} - case "ServicePrincipalTokenSecret": - spt.inner.Secret = &ServicePrincipalTokenSecret{} - case "ServicePrincipalCertificateSecret": - return errors.New("unmarshalling ServicePrincipalCertificateSecret is not supported") - case "ServicePrincipalMSISecret": - return errors.New("unmarshalling ServicePrincipalMSISecret is not supported") - case "ServicePrincipalUsernamePasswordSecret": - spt.inner.Secret = &ServicePrincipalUsernamePasswordSecret{} - case "ServicePrincipalAuthorizationCodeSecret": - spt.inner.Secret = &ServicePrincipalAuthorizationCodeSecret{} - default: - return fmt.Errorf("unrecognized token type '%s'", secret["type"]) - } - err = json.Unmarshal(data, &spt.inner) - if err != nil { - return err - } - spt.refreshLock = &sync.RWMutex{} - spt.sender = &http.Client{} - return nil -} - -// internal type used for marshalling/unmarshalling -type servicePrincipalToken struct { - Token Token `json:"token"` - Secret ServicePrincipalSecret `json:"secret"` - OauthConfig OAuthConfig `json:"oauth"` - ClientID string `json:"clientID"` - Resource string `json:"resource"` - AutoRefresh bool `json:"autoRefresh"` - RefreshWithin time.Duration `json:"refreshWithin"` -} - -func validateOAuthConfig(oac OAuthConfig) error { - if oac.IsZero() { - return fmt.Errorf("parameter 'oauthConfig' cannot be zero-initialized") - } - return nil -} - -// NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. -func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(id, "id"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - spt := &ServicePrincipalToken{ - inner: servicePrincipalToken{ - OauthConfig: oauthConfig, - Secret: secret, - ClientID: id, - Resource: resource, - AutoRefresh: true, - RefreshWithin: defaultRefresh, - }, - refreshLock: &sync.RWMutex{}, - sender: &http.Client{}, - refreshCallbacks: callbacks, - } - return spt, nil -} - -// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token -func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalNoSecret{}, - callbacks...) - if err != nil { - return nil, err - } - - spt.inner.Token = token - - return spt, nil -} - -// NewServicePrincipalTokenFromManualTokenSecret creates a ServicePrincipalToken using the supplied token and secret -func NewServicePrincipalTokenFromManualTokenSecret(oauthConfig OAuthConfig, clientID string, resource string, token Token, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - secret, - callbacks...) - if err != nil { - return nil, err - } - - spt.inner.Token = token - - return spt, nil -} - -// NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal -// credentials scoped to the named resource. -func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(secret, "secret"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalTokenSecret{ - ClientSecret: secret, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromCertificate creates a ServicePrincipalToken from the supplied pkcs12 bytes. -func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if certificate == nil { - return nil, fmt.Errorf("parameter 'certificate' cannot be nil") - } - if privateKey == nil { - return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromUsernamePassword creates a ServicePrincipalToken from the username and password. -func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(username, "username"); err != nil { - return nil, err - } - if err := validateStringParam(password, "password"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalUsernamePasswordSecret{ - Username: username, - Password: password, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromAuthorizationCode creates a ServicePrincipalToken from the -func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(clientSecret, "clientSecret"); err != nil { - return nil, err - } - if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { - return nil, err - } - if err := validateStringParam(redirectURI, "redirectURI"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalAuthorizationCodeSecret{ - ClientSecret: clientSecret, - AuthorizationCode: authorizationCode, - RedirectURI: redirectURI, - }, - callbacks..., - ) -} - -// GetMSIVMEndpoint gets the MSI endpoint on Virtual Machines. -func GetMSIVMEndpoint() (string, error) { - return msiEndpoint, nil -} - -// NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the system assigned identity when creating the token. -func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...) -} - -// NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the specified user assigned identity when creating the token. -func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...) -} - -func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedID *string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(msiEndpoint, "msiEndpoint"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if userAssignedID != nil { - if err := validateStringParam(*userAssignedID, "userAssignedID"); err != nil { - return nil, err - } - } - // We set the oauth config token endpoint to be MSI's endpoint - msiEndpointURL, err := url.Parse(msiEndpoint) - if err != nil { - return nil, err - } - - v := url.Values{} - v.Set("resource", resource) - v.Set("api-version", "2018-02-01") - if userAssignedID != nil { - v.Set("client_id", *userAssignedID) - } - msiEndpointURL.RawQuery = v.Encode() - - spt := &ServicePrincipalToken{ - inner: servicePrincipalToken{ - OauthConfig: OAuthConfig{ - TokenEndpoint: *msiEndpointURL, - }, - Secret: &ServicePrincipalMSISecret{}, - Resource: resource, - AutoRefresh: true, - RefreshWithin: defaultRefresh, - }, - refreshLock: &sync.RWMutex{}, - sender: &http.Client{}, - refreshCallbacks: callbacks, - MaxMSIRefreshAttempts: defaultMaxMSIRefreshAttempts, - } - - if userAssignedID != nil { - spt.inner.ClientID = *userAssignedID - } - - return spt, nil -} - -// internal type that implements TokenRefreshError -type tokenRefreshError struct { - message string - resp *http.Response -} - -// Error implements the error interface which is part of the TokenRefreshError interface. -func (tre tokenRefreshError) Error() string { - return tre.message -} - -// Response implements the TokenRefreshError interface, it returns the raw HTTP response from the refresh operation. -func (tre tokenRefreshError) Response() *http.Response { - return tre.resp -} - -func newTokenRefreshError(message string, resp *http.Response) TokenRefreshError { - return tokenRefreshError{message: message, resp: resp} -} - -// EnsureFresh will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFresh() error { - return spt.EnsureFreshWithContext(context.Background()) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - if spt.inner.AutoRefresh && spt.inner.Token.WillExpireIn(spt.inner.RefreshWithin) { - // take the write lock then check to see if the token was already refreshed - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - if spt.inner.Token.WillExpireIn(spt.inner.RefreshWithin) { - return spt.refreshInternal(ctx, spt.inner.Resource) - } - } - return nil -} - -// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization -func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { - if spt.refreshCallbacks != nil { - for _, callback := range spt.refreshCallbacks { - err := callback(spt.inner.Token) - if err != nil { - return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) - } - } - } - return nil -} - -// Refresh obtains a fresh token for the Service Principal. -// This method is not safe for concurrent use and should be syncrhonized. -func (spt *ServicePrincipalToken) Refresh() error { - return spt.RefreshWithContext(context.Background()) -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -// This method is not safe for concurrent use and should be syncrhonized. -func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(ctx, spt.inner.Resource) -} - -// RefreshExchange refreshes the token, but for a different resource. -// This method is not safe for concurrent use and should be syncrhonized. -func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { - return spt.RefreshExchangeWithContext(context.Background(), resource) -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -// This method is not safe for concurrent use and should be syncrhonized. -func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(ctx, resource) -} - -func (spt *ServicePrincipalToken) getGrantType() string { - switch spt.inner.Secret.(type) { - case *ServicePrincipalUsernamePasswordSecret: - return OAuthGrantTypeUserPass - case *ServicePrincipalAuthorizationCodeSecret: - return OAuthGrantTypeAuthorizationCode - default: - return OAuthGrantTypeClientCredentials - } -} - -func isIMDS(u url.URL) bool { - imds, err := url.Parse(msiEndpoint) - if err != nil { - return false - } - return u.Host == imds.Host && u.Path == imds.Path -} - -func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource string) error { - req, err := http.NewRequest(http.MethodPost, spt.inner.OauthConfig.TokenEndpoint.String(), nil) - if err != nil { - return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err) - } - req.Header.Add("User-Agent", version.UserAgent()) - req = req.WithContext(ctx) - if !isIMDS(spt.inner.OauthConfig.TokenEndpoint) { - v := url.Values{} - v.Set("client_id", spt.inner.ClientID) - v.Set("resource", resource) - - if spt.inner.Token.RefreshToken != "" { - v.Set("grant_type", OAuthGrantTypeRefreshToken) - v.Set("refresh_token", spt.inner.Token.RefreshToken) - // web apps must specify client_secret when refreshing tokens - // see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code#refreshing-the-access-tokens - if spt.getGrantType() == OAuthGrantTypeAuthorizationCode { - err := spt.inner.Secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - } else { - v.Set("grant_type", spt.getGrantType()) - err := spt.inner.Secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - req.Body = body - } - - if _, ok := spt.inner.Secret.(*ServicePrincipalMSISecret); ok { - req.Method = http.MethodGet - req.Header.Set(metadataHeader, "true") - } - - var resp *http.Response - if isIMDS(spt.inner.OauthConfig.TokenEndpoint) { - resp, err = retryForIMDS(spt.sender, req, spt.MaxMSIRefreshAttempts) - } else { - resp, err = spt.sender.Do(req) - } - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Failed to execute the refresh request. Error = '%v'", err), nil) - } - - defer resp.Body.Close() - rb, err := ioutil.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusOK { - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Failed reading response body: %v", resp.StatusCode, err), resp) - } - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Response body: %s", resp.StatusCode, string(rb)), resp) - } - - // for the following error cases don't return a TokenRefreshError. the operation succeeded - // but some transient failure happened during deserialization. by returning a generic error - // the retry logic will kick in (we don't retry on TokenRefreshError). - - if err != nil { - return fmt.Errorf("adal: Failed to read a new service principal token during refresh. Error = '%v'", err) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return fmt.Errorf("adal: Empty service principal token received during refresh") - } - var token Token - err = json.Unmarshal(rb, &token) - if err != nil { - return fmt.Errorf("adal: Failed to unmarshal the service principal token during refresh. Error = '%v' JSON = '%s'", err, string(rb)) - } - - spt.inner.Token = token - - return spt.InvokeRefreshCallbacks(token) -} - -// retry logic specific to retrieving a token from the IMDS endpoint -func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) { - // copied from client.go due to circular dependency - retries := []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } - // extra retry status codes specific to IMDS - retries = append(retries, - http.StatusNotFound, - http.StatusGone, - // all remaining 5xx - http.StatusNotImplemented, - http.StatusHTTPVersionNotSupported, - http.StatusVariantAlsoNegotiates, - http.StatusInsufficientStorage, - http.StatusLoopDetected, - http.StatusNotExtended, - http.StatusNetworkAuthenticationRequired) - - // see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance - - const maxDelay time.Duration = 60 * time.Second - - attempt := 0 - delay := time.Duration(0) - - for attempt < maxAttempts { - resp, err = sender.Do(req) - // retry on temporary network errors, e.g. transient network failures. - // if we don't receive a response then assume we can't connect to the - // endpoint so we're likely not running on an Azure VM so don't retry. - if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) { - return - } - - // perform exponential backoff with a cap. - // must increment attempt before calculating delay. - attempt++ - // the base value of 2 is the "delta backoff" as specified in the guidance doc - delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second) - if delay > maxDelay { - delay = maxDelay - } - - select { - case <-time.After(delay): - // intentionally left blank - case <-req.Context().Done(): - err = req.Context().Err() - return - } - } - return -} - -// returns true if the specified error is a temporary network error or false if it's not. -// if the error doesn't implement the net.Error interface the return value is true. -func isTemporaryNetworkError(err error) bool { - if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { - return true - } - return false -} - -// returns true if slice ints contains the value n -func containsInt(ints []int, n int) bool { - for _, i := range ints { - if i == n { - return true - } - } - return false -} - -// SetAutoRefresh enables or disables automatic refreshing of stale tokens. -func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool) { - spt.inner.AutoRefresh = autoRefresh -} - -// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will -// refresh the token. -func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { - spt.inner.RefreshWithin = d - return -} - -// SetSender sets the http.Client used when obtaining the Service Principal token. An -// undecorated http.Client is used by default. -func (spt *ServicePrincipalToken) SetSender(s Sender) { spt.sender = s } - -// OAuthToken implements the OAuthTokenProvider interface. It returns the current access token. -func (spt *ServicePrincipalToken) OAuthToken() string { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.inner.Token.OAuthToken() -} - -// Token returns a copy of the current token. -func (spt *ServicePrincipalToken) Token() Token { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.inner.Token -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/authorization.go deleted file mode 100644 index 77eff45..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/authorization.go +++ /dev/null @@ -1,259 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/Azure/go-autorest/autorest/adal" -) - -const ( - bearerChallengeHeader = "Www-Authenticate" - bearer = "Bearer" - tenantID = "tenantID" - apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key" - bingAPISdkHeader = "X-BingApis-SDK-Client" - golangBingAPISdkHeaderValue = "Go-SDK" -) - -// Authorizer is the interface that provides a PrepareDecorator used to supply request -// authorization. Most often, the Authorizer decorator runs last so it has access to the full -// state of the formed HTTP request. -type Authorizer interface { - WithAuthorization() PrepareDecorator -} - -// NullAuthorizer implements a default, "do nothing" Authorizer. -type NullAuthorizer struct{} - -// WithAuthorization returns a PrepareDecorator that does nothing. -func (na NullAuthorizer) WithAuthorization() PrepareDecorator { - return WithNothing() -} - -// APIKeyAuthorizer implements API Key authorization. -type APIKeyAuthorizer struct { - headers map[string]interface{} - queryParameters map[string]interface{} -} - -// NewAPIKeyAuthorizerWithHeaders creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizerWithHeaders(headers map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(headers, nil) -} - -// NewAPIKeyAuthorizerWithQueryParameters creates an ApiKeyAuthorizer with query parameters. -func NewAPIKeyAuthorizerWithQueryParameters(queryParameters map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(nil, queryParameters) -} - -// NewAPIKeyAuthorizer creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer { - return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Paramaters -func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters)) - } -} - -// CognitiveServicesAuthorizer implements authorization for Cognitive Services. -type CognitiveServicesAuthorizer struct { - subscriptionKey string -} - -// NewCognitiveServicesAuthorizer is -func NewCognitiveServicesAuthorizer(subscriptionKey string) *CognitiveServicesAuthorizer { - return &CognitiveServicesAuthorizer{subscriptionKey: subscriptionKey} -} - -// WithAuthorization is -func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator { - headers := make(map[string]interface{}) - headers[apiKeyAuthorizerHeader] = csa.subscriptionKey - headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue - - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// BearerAuthorizer implements the bearer authorization -type BearerAuthorizer struct { - tokenProvider adal.OAuthTokenProvider -} - -// NewBearerAuthorizer crates a BearerAuthorizer using the given token provider -func NewBearerAuthorizer(tp adal.OAuthTokenProvider) *BearerAuthorizer { - return &BearerAuthorizer{tokenProvider: tp} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the token. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // the ordering is important here, prefer RefresherWithContext if available - if refresher, ok := ba.tokenProvider.(adal.RefresherWithContext); ok { - err = refresher.EnsureFreshWithContext(r.Context()) - } else if refresher, ok := ba.tokenProvider.(adal.Refresher); ok { - err = refresher.EnsureFresh() - } - if err != nil { - var resp *http.Response - if tokError, ok := err.(adal.TokenRefreshError); ok { - resp = tokError.Response() - } - return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", resp, - "Failed to refresh the Token for request to %s", r.URL) - } - return Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", ba.tokenProvider.OAuthToken()))) - } - return r, err - }) - } -} - -// BearerAuthorizerCallbackFunc is the authentication callback signature. -type BearerAuthorizerCallbackFunc func(tenantID, resource string) (*BearerAuthorizer, error) - -// BearerAuthorizerCallback implements bearer authorization via a callback. -type BearerAuthorizerCallback struct { - sender Sender - callback BearerAuthorizerCallbackFunc -} - -// NewBearerAuthorizerCallback creates a bearer authorization callback. The callback -// is invoked when the HTTP request is submitted. -func NewBearerAuthorizerCallback(sender Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback { - if sender == nil { - sender = &http.Client{} - } - return &BearerAuthorizerCallback{sender: sender, callback: callback} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value -// is "Bearer " followed by the token. The BearerAuthorizer is obtained via a user-supplied callback. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (bacb *BearerAuthorizerCallback) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // make a copy of the request and remove the body as it's not - // required and avoids us having to create a copy of it. - rCopy := *r - removeRequestBody(&rCopy) - - resp, err := bacb.sender.Do(&rCopy) - if err == nil && resp.StatusCode == 401 { - defer resp.Body.Close() - if hasBearerChallenge(resp) { - bc, err := newBearerChallenge(resp) - if err != nil { - return r, err - } - if bacb.callback != nil { - ba, err := bacb.callback(bc.values[tenantID], bc.values["resource"]) - if err != nil { - return r, err - } - return Prepare(r, ba.WithAuthorization()) - } - } - } - } - return r, err - }) - } -} - -// returns true if the HTTP response contains a bearer challenge -func hasBearerChallenge(resp *http.Response) bool { - authHeader := resp.Header.Get(bearerChallengeHeader) - if len(authHeader) == 0 || strings.Index(authHeader, bearer) < 0 { - return false - } - return true -} - -type bearerChallenge struct { - values map[string]string -} - -func newBearerChallenge(resp *http.Response) (bc bearerChallenge, err error) { - challenge := strings.TrimSpace(resp.Header.Get(bearerChallengeHeader)) - trimmedChallenge := challenge[len(bearer)+1:] - - // challenge is a set of key=value pairs that are comma delimited - pairs := strings.Split(trimmedChallenge, ",") - if len(pairs) < 1 { - err = fmt.Errorf("challenge '%s' contains no pairs", challenge) - return bc, err - } - - bc.values = make(map[string]string) - for i := range pairs { - trimmedPair := strings.TrimSpace(pairs[i]) - pair := strings.Split(trimmedPair, "=") - if len(pair) == 2 { - // remove the enclosing quotes - key := strings.Trim(pair[0], "\"") - value := strings.Trim(pair[1], "\"") - - switch key { - case "authorization", "authorization_uri": - // strip the tenant ID from the authorization URL - asURL, err := url.Parse(value) - if err != nil { - return bc, err - } - bc.values[tenantID] = asURL.Path[1:] - default: - bc.values[key] = value - } - } - } - - return bc, err -} - -// EventGridKeyAuthorizer implements authorization for event grid using key authentication. -type EventGridKeyAuthorizer struct { - topicKey string -} - -// NewEventGridKeyAuthorizer creates a new EventGridKeyAuthorizer -// with the specified topic key. -func NewEventGridKeyAuthorizer(topicKey string) EventGridKeyAuthorizer { - return EventGridKeyAuthorizer{topicKey: topicKey} -} - -// WithAuthorization returns a PrepareDecorator that adds the aeg-sas-key authentication header. -func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator { - headers := map[string]interface{}{ - "aeg-sas-key": egta.topicKey, - } - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/autorest.go deleted file mode 100644 index aafdf02..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Package autorest implements an HTTP request pipeline suitable for use across multiple go-routines -and provides the shared routines relied on by AutoRest (see https://github.com/Azure/autorest/) -generated Go code. - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) - -will set the URL to: - - https://microsoft.com/a/b/c - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., ByUnmarshallingJson) is likely incorrect. - -Lastly, the Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure -correct parsing and formatting. - -Errors raised by autorest objects and methods will conform to the autorest.Error interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. -*/ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "net/http" - "time" -) - -const ( - // HeaderLocation specifies the HTTP Location header. - HeaderLocation = "Location" - - // HeaderRetryAfter specifies the HTTP Retry-After header. - HeaderRetryAfter = "Retry-After" -) - -// ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set -// and false otherwise. -func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { - if resp == nil { - return false - } - return containsInt(codes, resp.StatusCode) -} - -// GetLocation retrieves the URL from the Location header of the passed response. -func GetLocation(resp *http.Response) string { - return resp.Header.Get(HeaderLocation) -} - -// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If -// the header is absent or is malformed, it will return the supplied default delay time.Duration. -func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { - retry := resp.Header.Get(HeaderRetryAfter) - if retry == "" { - return defaultDelay - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - return defaultDelay - } - - return d -} - -// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. -func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare(&http.Request{Cancel: cancel}, - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} - -// NewPollingRequestWithContext allocates and returns a new http.Request with the specified context to poll for the passed response. -func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare((&http.Request{}).WithContext(ctx), - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/async.go deleted file mode 100644 index cfd981a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ /dev/null @@ -1,930 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -const ( - headerAsyncOperation = "Azure-AsyncOperation" -) - -const ( - operationInProgress string = "InProgress" - operationCanceled string = "Canceled" - operationFailed string = "Failed" - operationSucceeded string = "Succeeded" -) - -var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.StatusCreated, http.StatusOK} - -// Future provides a mechanism to access the status and results of an asynchronous request. -// Since futures are stateful they should be passed by value to avoid race conditions. -type Future struct { - req *http.Request // legacy - pt pollingTracker -} - -// NewFuture returns a new Future object initialized with the specified request. -// Deprecated: Please use NewFutureFromResponse instead. -func NewFuture(req *http.Request) Future { - return Future{req: req} -} - -// NewFutureFromResponse returns a new Future object initialized -// with the initial response from an asynchronous operation. -func NewFutureFromResponse(resp *http.Response) (Future, error) { - pt, err := createPollingTracker(resp) - if err != nil { - return Future{}, err - } - return Future{pt: pt}, nil -} - -// Response returns the last HTTP response. -func (f Future) Response() *http.Response { - if f.pt == nil { - return nil - } - return f.pt.latestResponse() -} - -// Status returns the last status message of the operation. -func (f Future) Status() string { - if f.pt == nil { - return "" - } - return f.pt.pollingStatus() -} - -// PollingMethod returns the method used to monitor the status of the asynchronous operation. -func (f Future) PollingMethod() PollingMethodType { - if f.pt == nil { - return PollingUnknown - } - return f.pt.pollingMethod() -} - -// Done queries the service to see if the operation has completed. -func (f *Future) Done(sender autorest.Sender) (bool, error) { - // support for legacy Future implementation - if f.req != nil { - resp, err := sender.Do(f.req) - if err != nil { - return false, err - } - pt, err := createPollingTracker(resp) - if err != nil { - return false, err - } - f.pt = pt - f.req = nil - } - // end legacy - if f.pt == nil { - return false, autorest.NewError("Future", "Done", "future is not initialized") - } - if f.pt.hasTerminated() { - return true, f.pt.pollingError() - } - if err := f.pt.pollForStatus(sender); err != nil { - return false, err - } - if err := f.pt.checkForErrors(); err != nil { - return f.pt.hasTerminated(), err - } - if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil { - return false, err - } - if err := f.pt.updateHeaders(); err != nil { - return false, err - } - return f.pt.hasTerminated(), f.pt.pollingError() -} - -// GetPollingDelay returns a duration the application should wait before checking -// the status of the asynchronous request and true; this value is returned from -// the service via the Retry-After response header. If the header wasn't returned -// then the function returns the zero-value time.Duration and false. -func (f Future) GetPollingDelay() (time.Duration, bool) { - if f.pt == nil { - return 0, false - } - resp := f.pt.latestResponse() - if resp == nil { - return 0, false - } - - retry := resp.Header.Get(autorest.HeaderRetryAfter) - if retry == "" { - return 0, false - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - panic(err) - } - - return d, true -} - -// WaitForCompletion will return when one of the following conditions is met: the long -// running operation has completed, the provided context is cancelled, or the client's -// polling duration has been exceeded. It will retry failed polling attempts based on -// the retry value defined in the client up to the maximum retry attempts. -// Deprecated: Please use WaitForCompletionRef() instead. -func (f Future) WaitForCompletion(ctx context.Context, client autorest.Client) error { - return f.WaitForCompletionRef(ctx, client) -} - -// WaitForCompletionRef will return when one of the following conditions is met: the long -// running operation has completed, the provided context is cancelled, or the client's -// polling duration has been exceeded. It will retry failed polling attempts based on -// the retry value defined in the client up to the maximum retry attempts. -func (f *Future) WaitForCompletionRef(ctx context.Context, client autorest.Client) error { - ctx, cancel := context.WithTimeout(ctx, client.PollingDuration) - defer cancel() - done, err := f.Done(client) - for attempts := 0; !done; done, err = f.Done(client) { - if attempts >= client.RetryAttempts { - return autorest.NewErrorWithError(err, "Future", "WaitForCompletion", f.pt.latestResponse(), "the number of retries has been exceeded") - } - // we want delayAttempt to be zero in the non-error case so - // that DelayForBackoff doesn't perform exponential back-off - var delayAttempt int - var delay time.Duration - if err == nil { - // check for Retry-After delay, if not present use the client's polling delay - var ok bool - delay, ok = f.GetPollingDelay() - if !ok { - delay = client.PollingDelay - } - } else { - // there was an error polling for status so perform exponential - // back-off based on the number of attempts using the client's retry - // duration. update attempts after delayAttempt to avoid off-by-one. - delayAttempt = attempts - delay = client.RetryDuration - attempts++ - } - // wait until the delay elapses or the context is cancelled - delayElapsed := autorest.DelayForBackoff(delay, delayAttempt, ctx.Done()) - if !delayElapsed { - return autorest.NewErrorWithError(ctx.Err(), "Future", "WaitForCompletion", f.pt.latestResponse(), "context has been cancelled") - } - } - return err -} - -// MarshalJSON implements the json.Marshaler interface. -func (f Future) MarshalJSON() ([]byte, error) { - return json.Marshal(f.pt) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (f *Future) UnmarshalJSON(data []byte) error { - // unmarshal into JSON object to determine the tracker type - obj := map[string]interface{}{} - err := json.Unmarshal(data, &obj) - if err != nil { - return err - } - if obj["method"] == nil { - return autorest.NewError("Future", "UnmarshalJSON", "missing 'method' property") - } - method := obj["method"].(string) - switch strings.ToUpper(method) { - case http.MethodDelete: - f.pt = &pollingTrackerDelete{} - case http.MethodPatch: - f.pt = &pollingTrackerPatch{} - case http.MethodPost: - f.pt = &pollingTrackerPost{} - case http.MethodPut: - f.pt = &pollingTrackerPut{} - default: - return autorest.NewError("Future", "UnmarshalJSON", "unsupoorted method '%s'", method) - } - // now unmarshal into the tracker - return json.Unmarshal(data, &f.pt) -} - -// PollingURL returns the URL used for retrieving the status of the long-running operation. -func (f Future) PollingURL() string { - if f.pt == nil { - return "" - } - return f.pt.pollingURL() -} - -// GetResult should be called once polling has completed successfully. -// It makes the final GET call to retrieve the resultant payload. -func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) { - if f.pt.finalGetURL() == "" { - // we can end up in this situation if the async operation returns a 200 - // with no polling URLs. in that case return the response which should - // contain the JSON payload (only do this for successful terminal cases). - if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() { - return lr, nil - } - return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result") - } - req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil) - if err != nil { - return nil, err - } - return sender.Do(req) -} - -type pollingTracker interface { - // these methods can differ per tracker - - // checks the response headers and status code to determine the polling mechanism - updateHeaders() error - - // checks the response for tracker-specific error conditions - checkForErrors() error - - // returns true if provisioning state should be checked - provisioningStateApplicable() bool - - // methods common to all trackers - - // initializes the tracker's internal state, call this when the tracker is created - initializeState() error - - // makes an HTTP request to check the status of the LRO - pollForStatus(sender autorest.Sender) error - - // updates internal tracker state, call this after each call to pollForStatus - updatePollingState(provStateApl bool) error - - // returns the error response from the service, can be nil - pollingError() error - - // returns the polling method being used - pollingMethod() PollingMethodType - - // returns the state of the LRO as returned from the service - pollingStatus() string - - // returns the URL used for polling status - pollingURL() string - - // returns the URL used for the final GET to retrieve the resource - finalGetURL() string - - // returns true if the LRO is in a terminal state - hasTerminated() bool - - // returns true if the LRO is in a failed terminal state - hasFailed() bool - - // returns true if the LRO is in a successful terminal state - hasSucceeded() bool - - // returns the cached HTTP response after a call to pollForStatus(), can be nil - latestResponse() *http.Response -} - -type pollingTrackerBase struct { - // resp is the last response, either from the submission of the LRO or from polling - resp *http.Response - - // method is the HTTP verb, this is needed for deserialization - Method string `json:"method"` - - // rawBody is the raw JSON response body - rawBody map[string]interface{} - - // denotes if polling is using async-operation or location header - Pm PollingMethodType `json:"pollingMethod"` - - // the URL to poll for status - URI string `json:"pollingURI"` - - // the state of the LRO as returned from the service - State string `json:"lroState"` - - // the URL to GET for the final result - FinalGetURI string `json:"resultURI"` - - // used to hold an error object returned from the service - Err *ServiceError `json:"error,omitempty"` -} - -func (pt *pollingTrackerBase) initializeState() error { - // determine the initial polling state based on response body and/or HTTP status - // code. this is applicable to the initial LRO response, not polling responses! - pt.Method = pt.resp.Request.Method - if err := pt.updateRawBody(); err != nil { - return err - } - switch pt.resp.StatusCode { - case http.StatusOK: - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - if pt.hasFailed() { - pt.updateErrorFromResponse() - return pt.pollingError() - } - } else { - pt.State = operationSucceeded - } - case http.StatusCreated: - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - } else { - pt.State = operationInProgress - } - case http.StatusAccepted: - pt.State = operationInProgress - case http.StatusNoContent: - pt.State = operationSucceeded - default: - pt.State = operationFailed - pt.updateErrorFromResponse() - return pt.pollingError() - } - return nil -} - -func (pt pollingTrackerBase) getProvisioningState() *string { - if pt.rawBody != nil && pt.rawBody["properties"] != nil { - p := pt.rawBody["properties"].(map[string]interface{}) - if ps := p["provisioningState"]; ps != nil { - s := ps.(string) - return &s - } - } - return nil -} - -func (pt *pollingTrackerBase) updateRawBody() error { - pt.rawBody = map[string]interface{}{} - if pt.resp.ContentLength != 0 { - defer pt.resp.Body.Close() - b, err := ioutil.ReadAll(pt.resp.Body) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to read response body") - } - // put the body back so it's available to other callers - pt.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - if err = json.Unmarshal(b, &pt.rawBody); err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to unmarshal response body") - } - } - return nil -} - -func (pt *pollingTrackerBase) pollForStatus(sender autorest.Sender) error { - req, err := http.NewRequest(http.MethodGet, pt.URI, nil) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to create HTTP request") - } - // attach the context from the original request if available (it will be absent for deserialized futures) - if pt.resp != nil { - req = req.WithContext(pt.resp.Request.Context()) - } - pt.resp, err = sender.Do(req) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to send HTTP request") - } - if autorest.ResponseHasStatusCode(pt.resp, pollingCodes[:]...) { - // reset the service error on success case - pt.Err = nil - err = pt.updateRawBody() - } else { - // check response body for error content - pt.updateErrorFromResponse() - } - return err -} - -// attempts to unmarshal a ServiceError type from the response body. -// if that fails then make a best attempt at creating something meaningful. -// NOTE: this assumes that the async operation has failed. -func (pt *pollingTrackerBase) updateErrorFromResponse() { - var err error - if pt.resp.ContentLength != 0 { - type respErr struct { - ServiceError *ServiceError `json:"error"` - } - re := respErr{} - defer pt.resp.Body.Close() - var b []byte - if b, err = ioutil.ReadAll(pt.resp.Body); err != nil { - goto Default - } - if err = json.Unmarshal(b, &re); err != nil { - goto Default - } - // unmarshalling the error didn't yield anything, try unwrapped error - if re.ServiceError == nil { - err = json.Unmarshal(b, &re.ServiceError) - if err != nil { - goto Default - } - } - // the unmarshaller will ensure re.ServiceError is non-nil - // even if there was no content unmarshalled so check the code. - if re.ServiceError.Code != "" { - pt.Err = re.ServiceError - return - } - } -Default: - se := &ServiceError{ - Code: pt.pollingStatus(), - Message: "The async operation failed.", - } - if err != nil { - se.InnerError = make(map[string]interface{}) - se.InnerError["unmarshalError"] = err.Error() - } - // stick the response body into the error object in hopes - // it contains something useful to help diagnose the failure. - if len(pt.rawBody) > 0 { - se.AdditionalInfo = []map[string]interface{}{ - pt.rawBody, - } - } - pt.Err = se -} - -func (pt *pollingTrackerBase) updatePollingState(provStateApl bool) error { - if pt.Pm == PollingAsyncOperation && pt.rawBody["status"] != nil { - pt.State = pt.rawBody["status"].(string) - } else { - if pt.resp.StatusCode == http.StatusAccepted { - pt.State = operationInProgress - } else if provStateApl { - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - } else { - pt.State = operationSucceeded - } - } else { - return autorest.NewError("pollingTrackerBase", "updatePollingState", "the response from the async operation has an invalid status code") - } - } - // if the operation has failed update the error state - if pt.hasFailed() { - pt.updateErrorFromResponse() - } - return nil -} - -func (pt pollingTrackerBase) pollingError() error { - if pt.Err == nil { - return nil - } - return pt.Err -} - -func (pt pollingTrackerBase) pollingMethod() PollingMethodType { - return pt.Pm -} - -func (pt pollingTrackerBase) pollingStatus() string { - return pt.State -} - -func (pt pollingTrackerBase) pollingURL() string { - return pt.URI -} - -func (pt pollingTrackerBase) finalGetURL() string { - return pt.FinalGetURI -} - -func (pt pollingTrackerBase) hasTerminated() bool { - return strings.EqualFold(pt.State, operationCanceled) || strings.EqualFold(pt.State, operationFailed) || strings.EqualFold(pt.State, operationSucceeded) -} - -func (pt pollingTrackerBase) hasFailed() bool { - return strings.EqualFold(pt.State, operationCanceled) || strings.EqualFold(pt.State, operationFailed) -} - -func (pt pollingTrackerBase) hasSucceeded() bool { - return strings.EqualFold(pt.State, operationSucceeded) -} - -func (pt pollingTrackerBase) latestResponse() *http.Response { - return pt.resp -} - -// error checking common to all trackers -func (pt pollingTrackerBase) baseCheckForErrors() error { - // for Azure-AsyncOperations the response body cannot be nil or empty - if pt.Pm == PollingAsyncOperation { - if pt.resp.Body == nil || pt.resp.ContentLength == 0 { - return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil") - } - if pt.rawBody["status"] == nil { - return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body") - } - } - return nil -} - -// DELETE - -type pollingTrackerDelete struct { - pollingTrackerBase -} - -func (pt *pollingTrackerDelete) updateHeaders() error { - // for 201 the Location header is required - if pt.resp.StatusCode == http.StatusCreated { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerDelete", "updateHeaders", "missing Location header in 201 response") - } else { - pt.URI = lh - } - pt.Pm = PollingLocation - pt.FinalGetURI = pt.URI - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerDelete) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerDelete) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusNoContent -} - -// PATCH - -type pollingTrackerPatch struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPatch) updateHeaders() error { - // by default we can use the original URL for polling and final GET - if pt.URI == "" { - pt.URI = pt.resp.Request.URL.String() - } - if pt.FinalGetURI == "" { - pt.FinalGetURI = pt.resp.Request.URL.String() - } - if pt.Pm == PollingUnknown { - pt.Pm = PollingRequestURI - } - // for 201 it's permissible for no headers to be returned - if pt.resp.StatusCode == http.StatusCreated { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - // note the absense of the "final GET" mechanism for PATCH - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - if ao == "" { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerPatch", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } else { - pt.URI = lh - pt.Pm = PollingLocation - } - } - } - return nil -} - -func (pt pollingTrackerPatch) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerPatch) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusCreated -} - -// POST - -type pollingTrackerPost struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPost) updateHeaders() error { - // 201 requires Location header - if pt.resp.StatusCode == http.StatusCreated { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "missing Location header in 201 response") - } else { - pt.URI = lh - pt.FinalGetURI = lh - pt.Pm = PollingLocation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerPost) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerPost) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusNoContent -} - -// PUT - -type pollingTrackerPut struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPut) updateHeaders() error { - // by default we can use the original URL for polling and final GET - if pt.URI == "" { - pt.URI = pt.resp.Request.URL.String() - } - if pt.FinalGetURI == "" { - pt.FinalGetURI = pt.resp.Request.URL.String() - } - if pt.Pm == PollingUnknown { - pt.Pm = PollingRequestURI - } - // for 201 it's permissible for no headers to be returned - if pt.resp.StatusCode == http.StatusCreated { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPut", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerPut) checkForErrors() error { - err := pt.baseCheckForErrors() - if err != nil { - return err - } - // if there are no LRO headers then the body cannot be empty - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } - lh, err := getURLFromLocationHeader(pt.resp) - if err != nil { - return err - } - if ao == "" && lh == "" && len(pt.rawBody) == 0 { - return autorest.NewError("pollingTrackerPut", "checkForErrors", "the response did not contain a body") - } - return nil -} - -func (pt pollingTrackerPut) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusCreated -} - -// creates a polling tracker based on the verb of the original request -func createPollingTracker(resp *http.Response) (pollingTracker, error) { - var pt pollingTracker - switch strings.ToUpper(resp.Request.Method) { - case http.MethodDelete: - pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPatch: - pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPost: - pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPut: - pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}} - default: - return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method) - } - if err := pt.initializeState(); err != nil { - return pt, err - } - // this initializes the polling header values, we do this during creation in case the - // initial response send us invalid values; this way the API call will return a non-nil - // error (not doing this means the error shows up in Future.Done) - return pt, pt.updateHeaders() -} - -// gets the polling URL from the Azure-AsyncOperation header. -// ensures the URL is well-formed and absolute. -func getURLFromAsyncOpHeader(resp *http.Response) (string, error) { - s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) - if s == "" { - return "", nil - } - if !isValidURL(s) { - return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s) - } - return s, nil -} - -// gets the polling URL from the Location header. -// ensures the URL is well-formed and absolute. -func getURLFromLocationHeader(resp *http.Response) (string, error) { - s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation)) - if s == "" { - return "", nil - } - if !isValidURL(s) { - return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s) - } - return s, nil -} - -// verify that the URL is valid and absolute -func isValidURL(s string) bool { - u, err := url.Parse(s) - return err == nil && u.IsAbs() -} - -// DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure -// long-running operation. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled via -// the context associated with the http.Request. -// Deprecated: Prefer using Futures to allow for non-blocking async operations. -func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - return resp, err - } - if !autorest.ResponseHasStatusCode(resp, pollingCodes[:]...) { - return resp, nil - } - future, err := NewFutureFromResponse(resp) - if err != nil { - return resp, err - } - // retry until either the LRO completes or we receive an error - var done bool - for done, err = future.Done(s); !done && err == nil; done, err = future.Done(s) { - // check for Retry-After delay, if not present use the specified polling delay - if pd, ok := future.GetPollingDelay(); ok { - delay = pd - } - // wait until the delay elapses or the context is cancelled - if delayElapsed := autorest.DelayForBackoff(delay, 0, r.Context().Done()); !delayElapsed { - return future.Response(), - autorest.NewErrorWithError(r.Context().Err(), "azure", "DoPollForAsynchronous", future.Response(), "context has been cancelled") - } - } - return future.Response(), err - }) - } -} - -// PollingMethodType defines a type used for enumerating polling mechanisms. -type PollingMethodType string - -const ( - // PollingAsyncOperation indicates the polling method uses the Azure-AsyncOperation header. - PollingAsyncOperation PollingMethodType = "AsyncOperation" - - // PollingLocation indicates the polling method uses the Location header. - PollingLocation PollingMethodType = "Location" - - // PollingRequestURI indicates the polling method uses the original request URI. - PollingRequestURI PollingMethodType = "RequestURI" - - // PollingUnknown indicates an unknown polling method and is the default value. - PollingUnknown PollingMethodType = "" -) - -// AsyncOpIncompleteError is the type that's returned from a future that has not completed. -type AsyncOpIncompleteError struct { - // FutureType is the name of the type composed of a azure.Future. - FutureType string -} - -// Error returns an error message including the originating type name of the error. -func (e AsyncOpIncompleteError) Error() string { - return fmt.Sprintf("%s: asynchronous operation has not completed", e.FutureType) -} - -// NewAsyncOpIncompleteError creates a new AsyncOpIncompleteError with the specified parameters. -func NewAsyncOpIncompleteError(futureType string) AsyncOpIncompleteError { - return AsyncOpIncompleteError{ - FutureType: futureType, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go deleted file mode 100644 index a14b879..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go +++ /dev/null @@ -1,444 +0,0 @@ -package auth - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "crypto/rsa" - "crypto/x509" - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "log" - "os" - "strings" - "unicode/utf16" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/dimchansky/utfbom" - "golang.org/x/crypto/pkcs12" -) - -// NewAuthorizerFromEnvironment creates an Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func NewAuthorizerFromEnvironment() (autorest.Authorizer, error) { - settings, err := getAuthenticationSettings() - if err != nil { - return nil, err - } - - if settings.resource == "" { - settings.resource = settings.environment.ResourceManagerEndpoint - } - - return settings.getAuthorizer() -} - -// NewAuthorizerFromEnvironmentWithResource creates an Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func NewAuthorizerFromEnvironmentWithResource(resource string) (autorest.Authorizer, error) { - settings, err := getAuthenticationSettings() - if err != nil { - return nil, err - } - settings.resource = resource - return settings.getAuthorizer() -} - -type settings struct { - tenantID string - clientID string - clientSecret string - certificatePath string - certificatePassword string - username string - password string - envName string - resource string - environment azure.Environment -} - -func getAuthenticationSettings() (s settings, err error) { - s = settings{ - tenantID: os.Getenv("AZURE_TENANT_ID"), - clientID: os.Getenv("AZURE_CLIENT_ID"), - clientSecret: os.Getenv("AZURE_CLIENT_SECRET"), - certificatePath: os.Getenv("AZURE_CERTIFICATE_PATH"), - certificatePassword: os.Getenv("AZURE_CERTIFICATE_PASSWORD"), - username: os.Getenv("AZURE_USERNAME"), - password: os.Getenv("AZURE_PASSWORD"), - envName: os.Getenv("AZURE_ENVIRONMENT"), - resource: os.Getenv("AZURE_AD_RESOURCE"), - } - - if s.envName == "" { - s.environment = azure.PublicCloud - } else { - s.environment, err = azure.EnvironmentFromName(s.envName) - } - return -} - -func (settings settings) getAuthorizer() (autorest.Authorizer, error) { - //1.Client Credentials - if settings.clientSecret != "" { - config := NewClientCredentialsConfig(settings.clientID, settings.clientSecret, settings.tenantID) - config.AADEndpoint = settings.environment.ActiveDirectoryEndpoint - config.Resource = settings.resource - return config.Authorizer() - } - - //2. Client Certificate - if settings.certificatePath != "" { - config := NewClientCertificateConfig(settings.certificatePath, settings.certificatePassword, settings.clientID, settings.tenantID) - config.AADEndpoint = settings.environment.ActiveDirectoryEndpoint - config.Resource = settings.resource - return config.Authorizer() - } - - //3. Username Password - if settings.username != "" && settings.password != "" { - config := NewUsernamePasswordConfig(settings.username, settings.password, settings.clientID, settings.tenantID) - config.AADEndpoint = settings.environment.ActiveDirectoryEndpoint - config.Resource = settings.resource - return config.Authorizer() - } - - // 4. MSI - config := NewMSIConfig() - config.Resource = settings.resource - config.ClientID = settings.clientID - return config.Authorizer() -} - -// NewAuthorizerFromFile creates an Authorizer configured from a configuration file. -func NewAuthorizerFromFile(baseURI string) (autorest.Authorizer, error) { - fileLocation := os.Getenv("AZURE_AUTH_LOCATION") - if fileLocation == "" { - return nil, errors.New("auth file not found. Environment variable AZURE_AUTH_LOCATION is not set") - } - - contents, err := ioutil.ReadFile(fileLocation) - if err != nil { - return nil, err - } - - // Auth file might be encoded - decoded, err := decode(contents) - if err != nil { - return nil, err - } - - file := file{} - err = json.Unmarshal(decoded, &file) - if err != nil { - return nil, err - } - - resource, err := getResourceForToken(file, baseURI) - if err != nil { - return nil, err - } - - config, err := adal.NewOAuthConfig(file.ActiveDirectoryEndpoint, file.TenantID) - if err != nil { - return nil, err - } - - spToken, err := adal.NewServicePrincipalToken(*config, file.ClientID, file.ClientSecret, resource) - if err != nil { - return nil, err - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// File represents the authentication file -type file struct { - ClientID string `json:"clientId,omitempty"` - ClientSecret string `json:"clientSecret,omitempty"` - SubscriptionID string `json:"subscriptionId,omitempty"` - TenantID string `json:"tenantId,omitempty"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpointUrl,omitempty"` - ResourceManagerEndpoint string `json:"resourceManagerEndpointUrl,omitempty"` - GraphResourceID string `json:"activeDirectoryGraphResourceId,omitempty"` - SQLManagementEndpoint string `json:"sqlManagementEndpointUrl,omitempty"` - GalleryEndpoint string `json:"galleryEndpointUrl,omitempty"` - ManagementEndpoint string `json:"managementEndpointUrl,omitempty"` -} - -func decode(b []byte) ([]byte, error) { - reader, enc := utfbom.Skip(bytes.NewReader(b)) - - switch enc { - case utfbom.UTF16LittleEndian: - u16 := make([]uint16, (len(b)/2)-1) - err := binary.Read(reader, binary.LittleEndian, &u16) - if err != nil { - return nil, err - } - return []byte(string(utf16.Decode(u16))), nil - case utfbom.UTF16BigEndian: - u16 := make([]uint16, (len(b)/2)-1) - err := binary.Read(reader, binary.BigEndian, &u16) - if err != nil { - return nil, err - } - return []byte(string(utf16.Decode(u16))), nil - } - return ioutil.ReadAll(reader) -} - -func getResourceForToken(f file, baseURI string) (string, error) { - // Compare dafault base URI from the SDK to the endpoints from the public cloud - // Base URI and token resource are the same string. This func finds the authentication - // file field that matches the SDK base URI. The SDK defines the public cloud - // endpoint as its default base URI - if !strings.HasSuffix(baseURI, "/") { - baseURI += "/" - } - switch baseURI { - case azure.PublicCloud.ServiceManagementEndpoint: - return f.ManagementEndpoint, nil - case azure.PublicCloud.ResourceManagerEndpoint: - return f.ResourceManagerEndpoint, nil - case azure.PublicCloud.ActiveDirectoryEndpoint: - return f.ActiveDirectoryEndpoint, nil - case azure.PublicCloud.GalleryEndpoint: - return f.GalleryEndpoint, nil - case azure.PublicCloud.GraphEndpoint: - return f.GraphResourceID, nil - } - return "", fmt.Errorf("auth: base URI not found in endpoints") -} - -// NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string) ClientCredentialsConfig { - return ClientCredentialsConfig{ - ClientID: clientID, - ClientSecret: clientSecret, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewClientCertificateConfig creates a ClientCertificateConfig object configured to obtain an Authorizer through client certificate. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewClientCertificateConfig(certificatePath string, certificatePassword string, clientID string, tenantID string) ClientCertificateConfig { - return ClientCertificateConfig{ - CertificatePath: certificatePath, - CertificatePassword: certificatePassword, - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewUsernamePasswordConfig creates an UsernamePasswordConfig object configured to obtain an Authorizer through username and password. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewUsernamePasswordConfig(username string, password string, clientID string, tenantID string) UsernamePasswordConfig { - return UsernamePasswordConfig{ - Username: username, - Password: password, - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewMSIConfig creates an MSIConfig object configured to obtain an Authorizer through MSI. -func NewMSIConfig() MSIConfig { - return MSIConfig{ - Resource: azure.PublicCloud.ResourceManagerEndpoint, - } -} - -// NewDeviceFlowConfig creates a DeviceFlowConfig object configured to obtain an Authorizer through device flow. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewDeviceFlowConfig(clientID string, tenantID string) DeviceFlowConfig { - return DeviceFlowConfig{ - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -//AuthorizerConfig provides an authorizer from the configuration provided. -type AuthorizerConfig interface { - Authorizer() (autorest.Authorizer, error) -} - -// ClientCredentialsConfig provides the options to get a bearer authorizer from client credentials. -type ClientCredentialsConfig struct { - ClientID string - ClientSecret string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from client credentials. -func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) { - oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID) - if err != nil { - return nil, err - } - - spToken, err := adal.NewServicePrincipalToken(*oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// ClientCertificateConfig provides the options to get a bearer authorizer from a client certificate. -type ClientCertificateConfig struct { - ClientID string - CertificatePath string - CertificatePassword string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets an authorizer object from client certificate. -func (ccc ClientCertificateConfig) Authorizer() (autorest.Authorizer, error) { - oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID) - - certData, err := ioutil.ReadFile(ccc.CertificatePath) - if err != nil { - return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err) - } - - certificate, rsaPrivateKey, err := decodePkcs12(certData, ccc.CertificatePassword) - if err != nil { - return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) - } - - spToken, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource) - - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// DeviceFlowConfig provides the options to get a bearer authorizer using device flow authentication. -type DeviceFlowConfig struct { - ClientID string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from device flow. -func (dfc DeviceFlowConfig) Authorizer() (autorest.Authorizer, error) { - oauthClient := &autorest.Client{} - oauthConfig, err := adal.NewOAuthConfig(dfc.AADEndpoint, dfc.TenantID) - deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthConfig, dfc.ClientID, dfc.Resource) - if err != nil { - return nil, fmt.Errorf("failed to start device auth flow: %s", err) - } - - log.Println(*deviceCode.Message) - - token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) - if err != nil { - return nil, fmt.Errorf("failed to finish device auth flow: %s", err) - } - - spToken, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, dfc.ClientID, dfc.Resource, *token) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from device flow: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) { - privateKey, certificate, err := pkcs12.Decode(pkcs, password) - if err != nil { - return nil, nil, err - } - - rsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey) - if !isRsaKey { - return nil, nil, fmt.Errorf("PKCS#12 certificate must contain an RSA private key") - } - - return certificate, rsaPrivateKey, nil -} - -// UsernamePasswordConfig provides the options to get a bearer authorizer from a username and a password. -type UsernamePasswordConfig struct { - ClientID string - Username string - Password string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from a username and a password. -func (ups UsernamePasswordConfig) Authorizer() (autorest.Authorizer, error) { - - oauthConfig, err := adal.NewOAuthConfig(ups.AADEndpoint, ups.TenantID) - - spToken, err := adal.NewServicePrincipalTokenFromUsernamePassword(*oauthConfig, ups.ClientID, ups.Username, ups.Password, ups.Resource) - - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from username and password auth: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// MSIConfig provides the options to get a bearer authorizer through MSI. -type MSIConfig struct { - Resource string - ClientID string -} - -// Authorizer gets the authorizer from MSI. -func (mc MSIConfig) Authorizer() (autorest.Authorizer, error) { - msiEndpoint, err := adal.GetMSIVMEndpoint() - if err != nil { - return nil, err - } - - spToken, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, mc.Resource) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go deleted file mode 100644 index 3a0a439..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go +++ /dev/null @@ -1,326 +0,0 @@ -// Package azure provides Azure-specific implementations used with AutoRest. -// See the included examples for more detail. -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -const ( - // HeaderClientID is the Azure extension header to set a user-specified request ID. - HeaderClientID = "x-ms-client-request-id" - - // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID - // should be included in the response. - HeaderReturnClientID = "x-ms-return-client-request-id" - - // HeaderRequestID is the Azure extension header of the service generated request ID returned - // in the response. - HeaderRequestID = "x-ms-request-id" -) - -// ServiceError encapsulates the error response from an Azure service. -// It adhears to the OData v4 specification for error responses. -type ServiceError struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details []map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo"` -} - -func (se ServiceError) Error() string { - result := fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) - - if se.Target != nil { - result += fmt.Sprintf(" Target=%q", *se.Target) - } - - if se.Details != nil { - d, err := json.Marshal(se.Details) - if err != nil { - result += fmt.Sprintf(" Details=%v", se.Details) - } - result += fmt.Sprintf(" Details=%v", string(d)) - } - - if se.InnerError != nil { - d, err := json.Marshal(se.InnerError) - if err != nil { - result += fmt.Sprintf(" InnerError=%v", se.InnerError) - } - result += fmt.Sprintf(" InnerError=%v", string(d)) - } - - if se.AdditionalInfo != nil { - d, err := json.Marshal(se.AdditionalInfo) - if err != nil { - result += fmt.Sprintf(" AdditionalInfo=%v", se.AdditionalInfo) - } - result += fmt.Sprintf(" AdditionalInfo=%v", string(d)) - } - - return result -} - -// UnmarshalJSON implements the json.Unmarshaler interface for the ServiceError type. -func (se *ServiceError) UnmarshalJSON(b []byte) error { - // per the OData v4 spec the details field must be an array of JSON objects. - // unfortunately not all services adhear to the spec and just return a single - // object instead of an array with one object. so we have to perform some - // shenanigans to accommodate both cases. - // http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091 - - type serviceError1 struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details []map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo"` - } - - type serviceError2 struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo"` - } - - se1 := serviceError1{} - err := json.Unmarshal(b, &se1) - if err == nil { - se.populate(se1.Code, se1.Message, se1.Target, se1.Details, se1.InnerError, se1.AdditionalInfo) - return nil - } - - se2 := serviceError2{} - err = json.Unmarshal(b, &se2) - if err == nil { - se.populate(se2.Code, se2.Message, se2.Target, nil, se2.InnerError, se2.AdditionalInfo) - se.Details = append(se.Details, se2.Details) - return nil - } - return err -} - -func (se *ServiceError) populate(code, message string, target *string, details []map[string]interface{}, inner map[string]interface{}, additional []map[string]interface{}) { - se.Code = code - se.Message = message - se.Target = target - se.Details = details - se.InnerError = inner - se.AdditionalInfo = additional -} - -// RequestError describes an error response returned by Azure service. -type RequestError struct { - autorest.DetailedError - - // The error returned by the Azure service. - ServiceError *ServiceError `json:"error"` - - // The request id (from the x-ms-request-id-header) of the request. - RequestID string -} - -// Error returns a human-friendly error message from service error. -func (e RequestError) Error() string { - return fmt.Sprintf("autorest/azure: Service returned an error. Status=%v %v", - e.StatusCode, e.ServiceError) -} - -// IsAzureError returns true if the passed error is an Azure Service error; false otherwise. -func IsAzureError(e error) bool { - _, ok := e.(*RequestError) - return ok -} - -// Resource contains details about an Azure resource. -type Resource struct { - SubscriptionID string - ResourceGroup string - Provider string - ResourceType string - ResourceName string -} - -// ParseResourceID parses a resource ID into a ResourceDetails struct. -// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-functions-resource#return-value-4. -func ParseResourceID(resourceID string) (Resource, error) { - - const resourceIDPatternText = `(?i)subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)` - resourceIDPattern := regexp.MustCompile(resourceIDPatternText) - match := resourceIDPattern.FindStringSubmatch(resourceID) - - if len(match) == 0 { - return Resource{}, fmt.Errorf("parsing failed for %s. Invalid resource Id format", resourceID) - } - - v := strings.Split(match[5], "/") - resourceName := v[len(v)-1] - - result := Resource{ - SubscriptionID: match[1], - ResourceGroup: match[2], - Provider: match[3], - ResourceType: match[4], - ResourceName: resourceName, - } - - return result, nil -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError { - if v, ok := original.(*RequestError); ok { - return *v - } - - statusCode := autorest.UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - return RequestError{ - DetailedError: autorest.DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - }, - } -} - -// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id -// header to true such that UUID accompanies the http.Response. -func WithReturningClientID(uuid string) autorest.PrepareDecorator { - preparer := autorest.CreatePreparer( - WithClientID(uuid), - WithReturnClientID(true)) - - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - return preparer.Prepare(r) - }) - } -} - -// WithClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). -func WithClientID(uuid string) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderClientID, uuid) -} - -// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-return-client-request-id whose boolean value indicates if the value of the -// x-ms-client-request-id header should be included in the http.Response. -func WithReturnClientID(b bool) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) -} - -// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the -// http.Request sent to the service (and returned in the http.Response) -func ExtractClientID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderClientID, resp) -} - -// ExtractRequestID extracts the Azure server generated request identifier from the -// x-ms-request-id header. -func ExtractRequestID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderRequestID, resp) -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an -// azure.RequestError by reading the response body unless the response HTTP status code -// is among the set passed. -// -// If there is a chance service may return responses other than the Azure error -// format and the response cannot be parsed into an error, a decoding error will -// be returned containing the response body. In any case, the Responder will -// return an error if the status code is not satisfied. -// -// If this Responder returns an error, the response body will be replaced with -// an in-memory reader, which needs no further closing. -func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator { - return func(r autorest.Responder) autorest.Responder { - return autorest.ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !autorest.ResponseHasStatusCode(resp, codes...) { - var e RequestError - defer resp.Body.Close() - - // Copy and replace the Body in case it does not contain an error object. - // This will leave the Body available to the caller. - b, decodeErr := autorest.CopyAndDecode(autorest.EncodedAsJSON, resp.Body, &e) - resp.Body = ioutil.NopCloser(&b) - if decodeErr != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), decodeErr) - } - if e.ServiceError == nil { - // Check if error is unwrapped ServiceError - if err := json.Unmarshal(b.Bytes(), &e.ServiceError); err != nil { - return err - } - } - if e.ServiceError.Message == "" { - // if we're here it means the returned error wasn't OData v4 compliant. - // try to unmarshal the body as raw JSON in hopes of getting something. - rawBody := map[string]interface{}{} - if err := json.Unmarshal(b.Bytes(), &rawBody); err != nil { - return err - } - e.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - } - if len(rawBody) > 0 { - e.ServiceError.Details = []map[string]interface{}{rawBody} - } - } - e.Response = resp - e.RequestID = ExtractRequestID(resp) - if e.StatusCode == nil { - e.StatusCode = resp.StatusCode - } - err = &e - } - return err - }) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go deleted file mode 100644 index 7e41f7f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ /dev/null @@ -1,191 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "strings" -) - -// EnvironmentFilepathName captures the name of the environment variable containing the path to the file -// to be used while populating the Azure Environment. -const EnvironmentFilepathName = "AZURE_ENVIRONMENT_FILEPATH" - -var environments = map[string]Environment{ - "AZURECHINACLOUD": ChinaCloud, - "AZUREGERMANCLOUD": GermanCloud, - "AZUREPUBLICCLOUD": PublicCloud, - "AZUREUSGOVERNMENTCLOUD": USGovernmentCloud, -} - -// Environment represents a set of endpoints for each of Azure's Clouds. -type Environment struct { - Name string `json:"name"` - ManagementPortalURL string `json:"managementPortalURL"` - PublishSettingsURL string `json:"publishSettingsURL"` - ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` - ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` - GalleryEndpoint string `json:"galleryEndpoint"` - KeyVaultEndpoint string `json:"keyVaultEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - ServiceBusEndpoint string `json:"serviceBusEndpoint"` - BatchManagementEndpoint string `json:"batchManagementEndpoint"` - StorageEndpointSuffix string `json:"storageEndpointSuffix"` - SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` - TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` - KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` - ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` - ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` - ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` - ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` - TokenAudience string `json:"tokenAudience"` -} - -var ( - // PublicCloud is the default public Azure cloud environment - PublicCloud = Environment{ - Name: "AzurePublicCloud", - ManagementPortalURL: "https://manage.windowsazure.com/", - PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.windows.net/", - ResourceManagerEndpoint: "https://management.azure.com/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", - GalleryEndpoint: "https://gallery.azure.com/", - KeyVaultEndpoint: "https://vault.azure.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.windows.net/", - BatchManagementEndpoint: "https://batch.core.windows.net/", - StorageEndpointSuffix: "core.windows.net", - SQLDatabaseDNSSuffix: "database.windows.net", - TrafficManagerDNSSuffix: "trafficmanager.net", - KeyVaultDNSSuffix: "vault.azure.net", - ServiceBusEndpointSuffix: "servicebus.windows.net", - ServiceManagementVMDNSSuffix: "cloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.azure.com", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.azure.com/", - } - - // USGovernmentCloud is the cloud environment for the US Government - USGovernmentCloud = Environment{ - Name: "AzureUSGovernmentCloud", - ManagementPortalURL: "https://manage.windowsazure.us/", - PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", - ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.us/", - GalleryEndpoint: "https://gallery.usgovcloudapi.net/", - KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.usgovcloudapi.net/", - BatchManagementEndpoint: "https://batch.core.usgovcloudapi.net/", - StorageEndpointSuffix: "core.usgovcloudapi.net", - SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", - TrafficManagerDNSSuffix: "usgovtrafficmanager.net", - KeyVaultDNSSuffix: "vault.usgovcloudapi.net", - ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", - ServiceManagementVMDNSSuffix: "usgovcloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.usgovcloudapi.net/", - } - - // ChinaCloud is the cloud environment operated in China - ChinaCloud = Environment{ - Name: "AzureChinaCloud", - ManagementPortalURL: "https://manage.chinacloudapi.com/", - PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", - ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", - ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/", - GalleryEndpoint: "https://gallery.chinacloudapi.cn/", - KeyVaultEndpoint: "https://vault.azure.cn/", - GraphEndpoint: "https://graph.chinacloudapi.cn/", - ServiceBusEndpoint: "https://servicebus.chinacloudapi.cn/", - BatchManagementEndpoint: "https://batch.chinacloudapi.cn/", - StorageEndpointSuffix: "core.chinacloudapi.cn", - SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", - TrafficManagerDNSSuffix: "trafficmanager.cn", - KeyVaultDNSSuffix: "vault.azure.cn", - ServiceBusEndpointSuffix: "servicebus.chinacloudapi.cn", - ServiceManagementVMDNSSuffix: "chinacloudapp.cn", - ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.chinacloudapi.cn/", - } - - // GermanCloud is the cloud environment operated in Germany - GermanCloud = Environment{ - Name: "AzureGermanCloud", - ManagementPortalURL: "http://portal.microsoftazure.de/", - PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.cloudapi.de/", - ResourceManagerEndpoint: "https://management.microsoftazure.de/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", - GalleryEndpoint: "https://gallery.cloudapi.de/", - KeyVaultEndpoint: "https://vault.microsoftazure.de/", - GraphEndpoint: "https://graph.cloudapi.de/", - ServiceBusEndpoint: "https://servicebus.cloudapi.de/", - BatchManagementEndpoint: "https://batch.cloudapi.de/", - StorageEndpointSuffix: "core.cloudapi.de", - SQLDatabaseDNSSuffix: "database.cloudapi.de", - TrafficManagerDNSSuffix: "azuretrafficmanager.de", - KeyVaultDNSSuffix: "vault.microsoftazure.de", - ServiceBusEndpointSuffix: "servicebus.cloudapi.de", - ServiceManagementVMDNSSuffix: "azurecloudapp.de", - ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.microsoftazure.de/", - } -) - -// EnvironmentFromName returns an Environment based on the common name specified. -func EnvironmentFromName(name string) (Environment, error) { - // IMPORTANT - // As per @radhikagupta5: - // This is technical debt, fundamentally here because Kubernetes is not currently accepting - // contributions to the providers. Once that is an option, the provider should be updated to - // directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation - // from this method based on the name that is provided to us. - if strings.EqualFold(name, "AZURESTACKCLOUD") { - return EnvironmentFromFile(os.Getenv(EnvironmentFilepathName)) - } - - name = strings.ToUpper(name) - env, ok := environments[name] - if !ok { - return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) - } - - return env, nil -} - -// EnvironmentFromFile loads an Environment from a configuration file available on disk. -// This function is particularly useful in the Hybrid Cloud model, where one must define their own -// endpoints. -func EnvironmentFromFile(location string) (unmarshaled Environment, err error) { - fileContents, err := ioutil.ReadFile(location) - if err != nil { - return - } - - err = json.Unmarshal(fileContents, &unmarshaled) - - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go deleted file mode 100644 index 507f9e9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go +++ /dev/null @@ -1,245 +0,0 @@ -package azure - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -type audience []string - -type authentication struct { - LoginEndpoint string `json:"loginEndpoint"` - Audiences audience `json:"audiences"` -} - -type environmentMetadataInfo struct { - GalleryEndpoint string `json:"galleryEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - PortalEndpoint string `json:"portalEndpoint"` - Authentication authentication `json:"authentication"` -} - -// EnvironmentProperty represent property names that clients can override -type EnvironmentProperty string - -const ( - // EnvironmentName ... - EnvironmentName EnvironmentProperty = "name" - // EnvironmentManagementPortalURL .. - EnvironmentManagementPortalURL EnvironmentProperty = "managementPortalURL" - // EnvironmentPublishSettingsURL ... - EnvironmentPublishSettingsURL EnvironmentProperty = "publishSettingsURL" - // EnvironmentServiceManagementEndpoint ... - EnvironmentServiceManagementEndpoint EnvironmentProperty = "serviceManagementEndpoint" - // EnvironmentResourceManagerEndpoint ... - EnvironmentResourceManagerEndpoint EnvironmentProperty = "resourceManagerEndpoint" - // EnvironmentActiveDirectoryEndpoint ... - EnvironmentActiveDirectoryEndpoint EnvironmentProperty = "activeDirectoryEndpoint" - // EnvironmentGalleryEndpoint ... - EnvironmentGalleryEndpoint EnvironmentProperty = "galleryEndpoint" - // EnvironmentKeyVaultEndpoint ... - EnvironmentKeyVaultEndpoint EnvironmentProperty = "keyVaultEndpoint" - // EnvironmentGraphEndpoint ... - EnvironmentGraphEndpoint EnvironmentProperty = "graphEndpoint" - // EnvironmentServiceBusEndpoint ... - EnvironmentServiceBusEndpoint EnvironmentProperty = "serviceBusEndpoint" - // EnvironmentBatchManagementEndpoint ... - EnvironmentBatchManagementEndpoint EnvironmentProperty = "batchManagementEndpoint" - // EnvironmentStorageEndpointSuffix ... - EnvironmentStorageEndpointSuffix EnvironmentProperty = "storageEndpointSuffix" - // EnvironmentSQLDatabaseDNSSuffix ... - EnvironmentSQLDatabaseDNSSuffix EnvironmentProperty = "sqlDatabaseDNSSuffix" - // EnvironmentTrafficManagerDNSSuffix ... - EnvironmentTrafficManagerDNSSuffix EnvironmentProperty = "trafficManagerDNSSuffix" - // EnvironmentKeyVaultDNSSuffix ... - EnvironmentKeyVaultDNSSuffix EnvironmentProperty = "keyVaultDNSSuffix" - // EnvironmentServiceBusEndpointSuffix ... - EnvironmentServiceBusEndpointSuffix EnvironmentProperty = "serviceBusEndpointSuffix" - // EnvironmentServiceManagementVMDNSSuffix ... - EnvironmentServiceManagementVMDNSSuffix EnvironmentProperty = "serviceManagementVMDNSSuffix" - // EnvironmentResourceManagerVMDNSSuffix ... - EnvironmentResourceManagerVMDNSSuffix EnvironmentProperty = "resourceManagerVMDNSSuffix" - // EnvironmentContainerRegistryDNSSuffix ... - EnvironmentContainerRegistryDNSSuffix EnvironmentProperty = "containerRegistryDNSSuffix" - // EnvironmentTokenAudience ... - EnvironmentTokenAudience EnvironmentProperty = "tokenAudience" -) - -// OverrideProperty represents property name and value that clients can override -type OverrideProperty struct { - Key EnvironmentProperty - Value string -} - -// EnvironmentFromURL loads an Environment from a URL -// This function is particularly useful in the Hybrid Cloud model, where one may define their own -// endpoints. -func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) { - var metadataEnvProperties environmentMetadataInfo - - if resourceManagerEndpoint == "" { - return environment, fmt.Errorf("Metadata resource manager endpoint is empty") - } - - if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil { - return environment, err - } - - // Give priority to user's override values - overrideProperties(&environment, properties) - - if environment.Name == "" { - environment.Name = "HybridEnvironment" - } - stampDNSSuffix := environment.StorageEndpointSuffix - if stampDNSSuffix == "" { - stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/") - environment.StorageEndpointSuffix = stampDNSSuffix - } - if environment.KeyVaultDNSSuffix == "" { - environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix) - } - if environment.KeyVaultEndpoint == "" { - environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix) - } - if environment.TokenAudience == "" { - environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0] - } - if environment.ActiveDirectoryEndpoint == "" { - environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint - } - if environment.ResourceManagerEndpoint == "" { - environment.ResourceManagerEndpoint = resourceManagerEndpoint - } - if environment.GalleryEndpoint == "" { - environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint - } - if environment.GraphEndpoint == "" { - environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint - } - - return environment, nil -} - -func overrideProperties(environment *Environment, properties []OverrideProperty) { - for _, property := range properties { - switch property.Key { - case EnvironmentName: - { - environment.Name = property.Value - } - case EnvironmentManagementPortalURL: - { - environment.ManagementPortalURL = property.Value - } - case EnvironmentPublishSettingsURL: - { - environment.PublishSettingsURL = property.Value - } - case EnvironmentServiceManagementEndpoint: - { - environment.ServiceManagementEndpoint = property.Value - } - case EnvironmentResourceManagerEndpoint: - { - environment.ResourceManagerEndpoint = property.Value - } - case EnvironmentActiveDirectoryEndpoint: - { - environment.ActiveDirectoryEndpoint = property.Value - } - case EnvironmentGalleryEndpoint: - { - environment.GalleryEndpoint = property.Value - } - case EnvironmentKeyVaultEndpoint: - { - environment.KeyVaultEndpoint = property.Value - } - case EnvironmentGraphEndpoint: - { - environment.GraphEndpoint = property.Value - } - case EnvironmentServiceBusEndpoint: - { - environment.ServiceBusEndpoint = property.Value - } - case EnvironmentBatchManagementEndpoint: - { - environment.BatchManagementEndpoint = property.Value - } - case EnvironmentStorageEndpointSuffix: - { - environment.StorageEndpointSuffix = property.Value - } - case EnvironmentSQLDatabaseDNSSuffix: - { - environment.SQLDatabaseDNSSuffix = property.Value - } - case EnvironmentTrafficManagerDNSSuffix: - { - environment.TrafficManagerDNSSuffix = property.Value - } - case EnvironmentKeyVaultDNSSuffix: - { - environment.KeyVaultDNSSuffix = property.Value - } - case EnvironmentServiceBusEndpointSuffix: - { - environment.ServiceBusEndpointSuffix = property.Value - } - case EnvironmentServiceManagementVMDNSSuffix: - { - environment.ServiceManagementVMDNSSuffix = property.Value - } - case EnvironmentResourceManagerVMDNSSuffix: - { - environment.ResourceManagerVMDNSSuffix = property.Value - } - case EnvironmentContainerRegistryDNSSuffix: - { - environment.ContainerRegistryDNSSuffix = property.Value - } - case EnvironmentTokenAudience: - { - environment.TokenAudience = property.Value - } - } - } -} - -func retrieveMetadataEnvironment(endpoint string) (environment environmentMetadataInfo, err error) { - client := autorest.NewClientWithUserAgent("") - managementEndpoint := fmt.Sprintf("%s%s", strings.TrimSuffix(endpoint, "/"), "/metadata/endpoints?api-version=1.0") - req, _ := http.NewRequest("GET", managementEndpoint, nil) - response, err := client.Do(req) - if err != nil { - return environment, err - } - defer response.Body.Close() - jsonResponse, err := ioutil.ReadAll(response.Body) - if err != nil { - return environment, err - } - err = json.Unmarshal(jsonResponse, &environment) - return environment, err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go deleted file mode 100644 index bd34f0e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 azure - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -// DoRetryWithRegistration tries to register the resource provider in case it is unregistered. -// It also handles request retries -func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := autorest.NewRetriableRequest(r) - for currentAttempt := 0; currentAttempt < client.RetryAttempts; currentAttempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - - resp, err = autorest.SendWithSender(s, rr.Request(), - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return resp, err - } - - if resp.StatusCode != http.StatusConflict || client.SkipResourceProviderRegistration { - return resp, err - } - var re RequestError - err = autorest.Respond( - resp, - autorest.ByUnmarshallingJSON(&re), - ) - if err != nil { - return resp, err - } - err = re - - if re.ServiceError != nil && re.ServiceError.Code == "MissingSubscriptionRegistration" { - regErr := register(client, r, re) - if regErr != nil { - return resp, fmt.Errorf("failed auto registering Resource Provider: %s. Original error: %s", regErr, err) - } - } - } - return resp, err - }) - } -} - -func getProvider(re RequestError) (string, error) { - if re.ServiceError != nil && len(re.ServiceError.Details) > 0 { - return re.ServiceError.Details[0]["target"].(string), nil - } - return "", errors.New("provider was not found in the response") -} - -func register(client autorest.Client, originalReq *http.Request, re RequestError) error { - subID := getSubscription(originalReq.URL.Path) - if subID == "" { - return errors.New("missing parameter subscriptionID to register resource provider") - } - providerName, err := getProvider(re) - if err != nil { - return fmt.Errorf("missing parameter provider to register resource provider: %s", err) - } - newURL := url.URL{ - Scheme: originalReq.URL.Scheme, - Host: originalReq.URL.Host, - } - - // taken from the resources SDK - // with almost identical code, this sections are easier to mantain - // It is also not a good idea to import the SDK here - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L252 - pathParameters := map[string]interface{}{ - "resourceProviderNamespace": autorest.Encode("path", providerName), - "subscriptionId": autorest.Encode("path", subID), - } - - const APIVersion = "2016-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - - req, err := preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - type Provider struct { - RegistrationState *string `json:"registrationState,omitempty"` - } - var provider Provider - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - // poll for registered provisioning state - now := time.Now() - for err == nil && time.Since(now) < client.PollingDuration { - // taken from the resources SDK - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L45 - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - req, err = preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - if provider.RegistrationState != nil && - *provider.RegistrationState == "Registered" { - break - } - - delayed := autorest.DelayWithRetryAfter(resp, originalReq.Context().Done()) - if !delayed && !autorest.DelayForBackoff(client.PollingDelay, 0, originalReq.Context().Done()) { - return originalReq.Context().Err() - } - } - if !(time.Since(now) < client.PollingDuration) { - return errors.New("polling for resource provider registration has exceeded the polling duration") - } - return err -} - -func getSubscription(path string) string { - parts := strings.Split(path, "/") - for i, v := range parts { - if v == "subscriptions" && (i+1) < len(parts) { - return parts[i+1] - } - } - return "" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/client.go deleted file mode 100644 index 5c558c8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/client.go +++ /dev/null @@ -1,267 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "net/http/cookiejar" - "strings" - "time" - - "github.com/Azure/go-autorest/logger" - "github.com/Azure/go-autorest/version" -) - -const ( - // DefaultPollingDelay is a reasonable delay between polling requests. - DefaultPollingDelay = 60 * time.Second - - // DefaultPollingDuration is a reasonable total polling duration. - DefaultPollingDuration = 15 * time.Minute - - // DefaultRetryAttempts is number of attempts for retry status codes (5xx). - DefaultRetryAttempts = 3 - - // DefaultRetryDuration is the duration to wait between retries. - DefaultRetryDuration = 30 * time.Second -) - -var ( - // StatusCodesForRetry are a defined group of status code for which the client will retry - StatusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } -) - -const ( - requestFormat = `HTTP Request Begin =================================================== -%s -===================================================== HTTP Request End -` - responseFormat = `HTTP Response Begin =================================================== -%s -===================================================== HTTP Response End -` -) - -// Response serves as the base for all responses from generated clients. It provides access to the -// last http.Response. -type Response struct { - *http.Response `json:"-"` -} - -// LoggingInspector implements request and response inspectors that log the full request and -// response to a supplied log. -type LoggingInspector struct { - Logger *log.Logger -} - -// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - var body, b bytes.Buffer - - defer r.Body.Close() - - r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) - if err := r.Write(&b); err != nil { - return nil, fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(requestFormat, b.String()) - - r.Body = ioutil.NopCloser(&body) - return p.Prepare(r) - }) - } -} - -// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - var body, b bytes.Buffer - defer resp.Body.Close() - resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) - if err := resp.Write(&b); err != nil { - return fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(responseFormat, b.String()) - - resp.Body = ioutil.NopCloser(&body) - return r.Respond(resp) - }) - } -} - -// Client is the base for autorest generated clients. It provides default, "do nothing" -// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the -// standard, undecorated http.Client as a default Sender. -// -// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and -// return responses that compose with Response. -// -// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom -// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit -// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence -// sending the request by providing a decorated Sender. -type Client struct { - Authorizer Authorizer - Sender Sender - RequestInspector PrepareDecorator - ResponseInspector RespondDecorator - - // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header - PollingDelay time.Duration - - // PollingDuration sets the maximum polling time after which an error is returned. - PollingDuration time.Duration - - // RetryAttempts sets the default number of retry attempts for client. - RetryAttempts int - - // RetryDuration sets the delay duration for retries. - RetryDuration time.Duration - - // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent - // through the Do method. - UserAgent string - - Jar http.CookieJar - - // Set to true to skip attempted registration of resource providers (false by default). - SkipResourceProviderRegistration bool -} - -// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed -// string. -func NewClientWithUserAgent(ua string) Client { - c := Client{ - PollingDelay: DefaultPollingDelay, - PollingDuration: DefaultPollingDuration, - RetryAttempts: DefaultRetryAttempts, - RetryDuration: DefaultRetryDuration, - UserAgent: version.UserAgent(), - } - c.Sender = c.sender() - c.AddToUserAgent(ua) - return c -} - -// AddToUserAgent adds an extension to the current user agent -func (c *Client) AddToUserAgent(extension string) error { - if extension != "" { - c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension) - return nil - } - return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent) -} - -// Do implements the Sender interface by invoking the active Sender after applying authorization. -// If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent -// is set, apply set the User-Agent header. -func (c Client) Do(r *http.Request) (*http.Response, error) { - if r.UserAgent() == "" { - r, _ = Prepare(r, - WithUserAgent(c.UserAgent)) - } - // NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations - r, err := Prepare(r, - c.WithAuthorization(), - c.WithInspection()) - if err != nil { - var resp *http.Response - if detErr, ok := err.(DetailedError); ok { - // if the authorization failed (e.g. invalid credentials) there will - // be a response associated with the error, be sure to return it. - resp = detErr.Response - } - return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") - } - logger.Instance.WriteRequest(r, logger.Filter{ - Header: func(k string, v []string) (bool, []string) { - // remove the auth token from the log - if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") { - v = []string{"**REDACTED**"} - } - return true, v - }, - }) - resp, err := SendWithSender(c.sender(), r) - logger.Instance.WriteResponse(resp, logger.Filter{}) - Respond(resp, c.ByInspecting()) - return resp, err -} - -// sender returns the Sender to which to send requests. -func (c Client) sender() Sender { - if c.Sender == nil { - j, _ := cookiejar.New(nil) - return &http.Client{Jar: j} - } - return c.Sender -} - -// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator -// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. -func (c Client) WithAuthorization() PrepareDecorator { - return c.authorizer().WithAuthorization() -} - -// authorizer returns the Authorizer to use. -func (c Client) authorizer() Authorizer { - if c.Authorizer == nil { - return NullAuthorizer{} - } - return c.Authorizer -} - -// WithInspection is a convenience method that passes the request to the supplied RequestInspector, -// if present, or returns the WithNothing PrepareDecorator otherwise. -func (c Client) WithInspection() PrepareDecorator { - if c.RequestInspector == nil { - return WithNothing() - } - return c.RequestInspector -} - -// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, -// if present, or returns the ByIgnoring RespondDecorator otherwise. -func (c Client) ByInspecting() RespondDecorator { - if c.ResponseInspector == nil { - return ByIgnoring() - } - return c.ResponseInspector -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/date.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/date.go deleted file mode 100644 index c457106..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/date.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Package date provides time.Time derivatives that conform to the Swagger.io (https://swagger.io/) -defined date formats: Date and DateTime. Both types may, in most cases, be used in lieu of -time.Time types. And both convert to time.Time through a ToTime method. -*/ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "time" -) - -const ( - fullDate = "2006-01-02" - fullDateJSON = `"2006-01-02"` - dateFormat = "%04d-%02d-%02d" - jsonFormat = `"%04d-%02d-%02d"` -) - -// Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e., -// 2006-01-02). -type Date struct { - time.Time -} - -// ParseDate create a new Date from the passed string. -func ParseDate(date string) (d Date, err error) { - return parseDate(date, fullDate) -} - -func parseDate(date string, format string) (Date, error) { - d, err := time.Parse(format, date) - return Date{Time: d}, err -} - -// MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalBinary() ([]byte, error) { - return d.MarshalText() -} - -// UnmarshalBinary reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalBinary(data []byte) error { - return d.UnmarshalText(data) -} - -// MarshalJSON preserves the Date as a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalJSON() (json []byte, err error) { - return []byte(fmt.Sprintf(jsonFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalJSON(data []byte) (err error) { - d.Time, err = time.Parse(fullDateJSON, string(data)) - return err -} - -// MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalText() (text []byte, err error) { - return []byte(fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalText(data []byte) (err error) { - d.Time, err = time.Parse(fullDate, string(data)) - return err -} - -// String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02). -func (d Date) String() string { - return fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day()) -} - -// ToTime returns a Date as a time.Time -func (d Date) ToTime() time.Time { - return d.Time -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/time.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/time.go deleted file mode 100644 index b453fad..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/time.go +++ /dev/null @@ -1,103 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "regexp" - "time" -) - -// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -const ( - azureUtcFormatJSON = `"2006-01-02T15:04:05.999999999"` - azureUtcFormat = "2006-01-02T15:04:05.999999999" - rfc3339JSON = `"` + time.RFC3339Nano + `"` - rfc3339 = time.RFC3339Nano - tzOffsetRegex = `(Z|z|\+|-)(\d+:\d+)*"*$` -) - -// Time defines a type similar to time.Time but assumes a layout of RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -type Time struct { - time.Time -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalBinary() ([]byte, error) { - return t.Time.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalJSON() (json []byte, err error) { - return t.Time.MarshalJSON() -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalJSON(data []byte) (err error) { - timeFormat := azureUtcFormatJSON - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339JSON - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// MarshalText preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalText() (text []byte, err error) { - return t.Time.MarshalText() -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalText(data []byte) (err error) { - timeFormat := azureUtcFormat - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339 - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// String returns the Time formatted as an RFC3339 date-time string (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) String() string { - // Note: time.Time.String does not return an RFC3339 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} - -// ToTime returns a Time as a time.Time -func (t Time) ToTime() time.Time { - return t.Time -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go deleted file mode 100644 index 48fb39b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go +++ /dev/null @@ -1,100 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "errors" - "time" -) - -const ( - rfc1123JSON = `"` + time.RFC1123 + `"` - rfc1123 = time.RFC1123 -) - -// TimeRFC1123 defines a type similar to time.Time but assumes a layout of RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -type TimeRFC1123 struct { - time.Time -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalJSON(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123JSON, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalJSON() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") - } - b := []byte(t.Format(rfc1123JSON)) - return b, nil -} - -// MarshalText preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalText() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") - } - - b := []byte(t.Format(rfc1123)) - return b, nil -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalText(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalBinary() ([]byte, error) { - return t.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// ToTime returns a Time as a time.Time -func (t TimeRFC1123) ToTime() time.Time { - return t.Time -} - -// String returns the Time formatted as an RFC1123 date-time string (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) String() string { - // Note: time.Time.String does not return an RFC1123 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go deleted file mode 100644 index 7073959..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go +++ /dev/null @@ -1,123 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "time" -) - -// unixEpoch is the moment in time that should be treated as timestamp 0. -var unixEpoch = time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) - -// UnixTime marshals and unmarshals a time that is represented as the number -// of seconds (ignoring skip-seconds) since the Unix Epoch. -type UnixTime time.Time - -// Duration returns the time as a Duration since the UnixEpoch. -func (t UnixTime) Duration() time.Duration { - return time.Time(t).Sub(unixEpoch) -} - -// NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch. -func NewUnixTimeFromSeconds(seconds float64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) -} - -// NewUnixTimeFromNanoseconds creates a UnixTime as a number of nanoseconds from the UnixEpoch. -func NewUnixTimeFromNanoseconds(nanoseconds int64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(nanoseconds)) -} - -// NewUnixTimeFromDuration creates a UnixTime as a duration of time since the UnixEpoch. -func NewUnixTimeFromDuration(dur time.Duration) UnixTime { - return UnixTime(unixEpoch.Add(dur)) -} - -// UnixEpoch retreives the moment considered the Unix Epoch. I.e. The time represented by '0' -func UnixEpoch() time.Time { - return unixEpoch -} - -// MarshalJSON preserves the UnixTime as a JSON number conforming to Unix Timestamp requirements. -// (i.e. the number of seconds since midnight January 1st, 1970 not considering leap seconds.) -func (t UnixTime) MarshalJSON() ([]byte, error) { - buffer := &bytes.Buffer{} - enc := json.NewEncoder(buffer) - err := enc.Encode(float64(time.Time(t).UnixNano()) / 1e9) - if err != nil { - return nil, err - } - return buffer.Bytes(), nil -} - -// UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since -// midnight January 1st, 1970. -func (t *UnixTime) UnmarshalJSON(text []byte) error { - dec := json.NewDecoder(bytes.NewReader(text)) - - var secondsSinceEpoch float64 - if err := dec.Decode(&secondsSinceEpoch); err != nil { - return err - } - - *t = NewUnixTimeFromSeconds(secondsSinceEpoch) - - return nil -} - -// MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number. -func (t UnixTime) MarshalText() ([]byte, error) { - cast := time.Time(t) - return cast.MarshalText() -} - -// UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch. -func (t *UnixTime) UnmarshalText(raw []byte) error { - var unmarshaled time.Time - - if err := unmarshaled.UnmarshalText(raw); err != nil { - return err - } - - *t = UnixTime(unmarshaled) - return nil -} - -// MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch. -func (t UnixTime) MarshalBinary() ([]byte, error) { - buf := &bytes.Buffer{} - - payload := int64(t.Duration()) - - if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -// UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime. -func (t *UnixTime) UnmarshalBinary(raw []byte) error { - var nanosecondsSinceEpoch int64 - - if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { - return err - } - *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/utility.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/utility.go deleted file mode 100644 index 12addf0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/date/utility.go +++ /dev/null @@ -1,25 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "strings" - "time" -) - -// ParseTime to parse Time string to specified format. -func ParseTime(format string, t string) (d time.Time, err error) { - return time.Parse(format, strings.ToUpper(t)) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/error.go deleted file mode 100644 index f724f33..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/error.go +++ /dev/null @@ -1,98 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" -) - -const ( - // UndefinedStatusCode is used when HTTP status code is not available for an error. - UndefinedStatusCode = 0 -) - -// DetailedError encloses a error with details of the package, method, and associated HTTP -// status code (if any). -type DetailedError struct { - Original error - - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // StatusCode is the HTTP Response StatusCode (if non-zero) that led to the error. - StatusCode interface{} - - // Message is the error message. - Message string - - // Service Error is the response body of failed API in bytes - ServiceError []byte - - // Response is the response object that was returned during failure if applicable. - Response *http.Response -} - -// NewError creates a new Error conforming object from the passed packageType, method, and -// message. message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, nil, message, args...) -} - -// NewErrorWithResponse creates a new Error conforming object from the passed -// packageType, method, statusCode of the given resp (UndefinedStatusCode if -// resp is nil), and message. message is treated as a format string to which the -// optional args apply. -func NewErrorWithResponse(packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, resp, message, args...) -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - if v, ok := original.(DetailedError); ok { - return v - } - - statusCode := UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - - return DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - Response: resp, - } -} - -// Error returns a formatted containing all available details (i.e., PackageType, Method, -// StatusCode, Message, and original error (if any)). -func (e DetailedError) Error() string { - if e.Original == nil { - return fmt.Sprintf("%s#%s: %s: StatusCode=%d", e.PackageType, e.Method, e.Message, e.StatusCode) - } - return fmt.Sprintf("%s#%s: %s: StatusCode=%d -- Original Error: %v", e.PackageType, e.Method, e.Message, e.StatusCode, e.Original) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/preparer.go deleted file mode 100644 index 6d67bd7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ /dev/null @@ -1,480 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" -) - -const ( - mimeTypeJSON = "application/json" - mimeTypeOctetStream = "application/octet-stream" - mimeTypeFormPost = "application/x-www-form-urlencoded" - - headerAuthorization = "Authorization" - headerContentType = "Content-Type" - headerUserAgent = "User-Agent" -) - -// Preparer is the interface that wraps the Prepare method. -// -// Prepare accepts and possibly modifies an http.Request (e.g., adding Headers). Implementations -// must ensure to not share or hold per-invocation state since Preparers may be shared and re-used. -type Preparer interface { - Prepare(*http.Request) (*http.Request, error) -} - -// PreparerFunc is a method that implements the Preparer interface. -type PreparerFunc func(*http.Request) (*http.Request, error) - -// Prepare implements the Preparer interface on PreparerFunc. -func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { - return pf(r) -} - -// PrepareDecorator takes and possibly decorates, by wrapping, a Preparer. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then affect the result. -type PrepareDecorator func(Preparer) Preparer - -// CreatePreparer creates, decorates, and returns a Preparer. -// Without decorators, the returned Preparer returns the passed http.Request unmodified. -// Preparers are safe to share and re-use. -func CreatePreparer(decorators ...PrepareDecorator) Preparer { - return DecoratePreparer( - Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), - decorators...) -} - -// DecoratePreparer accepts a Preparer and a, possibly empty, set of PrepareDecorators, which it -// applies to the Preparer. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (change the http.Request and then pass it -// along) or a post-decorator (pass the http.Request along and alter it on return). -func DecoratePreparer(p Preparer, decorators ...PrepareDecorator) Preparer { - for _, decorate := range decorators { - p = decorate(p) - } - return p -} - -// Prepare accepts an http.Request and a, possibly empty, set of PrepareDecorators. -// It creates a Preparer from the decorators which it then applies to the passed http.Request. -func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { - if r == nil { - return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") - } - return CreatePreparer(decorators...).Prepare(r) -} - -// WithNothing returns a "do nothing" PrepareDecorator that makes no changes to the passed -// http.Request. -func WithNothing() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - return p.Prepare(r) - }) - } -} - -// WithHeader returns a PrepareDecorator that sets the specified HTTP header of the http.Request to -// the passed value. It canonicalizes the passed header name (via http.CanonicalHeaderKey) before -// adding the header. -func WithHeader(header string, value string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(http.CanonicalHeaderKey(header), value) - } - return r, err - }) - } -} - -// WithHeaders returns a PrepareDecorator that sets the specified HTTP headers of the http.Request to -// the passed value. It canonicalizes the passed headers name (via http.CanonicalHeaderKey) before -// adding them. -func WithHeaders(headers map[string]interface{}) PrepareDecorator { - h := ensureValueStrings(headers) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.Header == nil { - r.Header = make(http.Header) - } - - for name, value := range h { - r.Header.Set(http.CanonicalHeaderKey(name), value) - } - } - return r, err - }) - } -} - -// WithBearerAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the supplied token. -func WithBearerAuthorization(token string) PrepareDecorator { - return WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", token)) -} - -// AsContentType returns a PrepareDecorator that adds an HTTP Content-Type header whose value -// is the passed contentType. -func AsContentType(contentType string) PrepareDecorator { - return WithHeader(headerContentType, contentType) -} - -// WithUserAgent returns a PrepareDecorator that adds an HTTP User-Agent header whose value is the -// passed string. -func WithUserAgent(ua string) PrepareDecorator { - return WithHeader(headerUserAgent, ua) -} - -// AsFormURLEncoded returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/x-www-form-urlencoded". -func AsFormURLEncoded() PrepareDecorator { - return AsContentType(mimeTypeFormPost) -} - -// AsJSON returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/json". -func AsJSON() PrepareDecorator { - return AsContentType(mimeTypeJSON) -} - -// AsOctetStream returns a PrepareDecorator that adds the "application/octet-stream" Content-Type header. -func AsOctetStream() PrepareDecorator { - return AsContentType(mimeTypeOctetStream) -} - -// WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The -// decorator does not validate that the passed method string is a known HTTP method. -func WithMethod(method string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r.Method = method - return p.Prepare(r) - }) - } -} - -// AsDelete returns a PrepareDecorator that sets the HTTP method to DELETE. -func AsDelete() PrepareDecorator { return WithMethod("DELETE") } - -// AsGet returns a PrepareDecorator that sets the HTTP method to GET. -func AsGet() PrepareDecorator { return WithMethod("GET") } - -// AsHead returns a PrepareDecorator that sets the HTTP method to HEAD. -func AsHead() PrepareDecorator { return WithMethod("HEAD") } - -// AsOptions returns a PrepareDecorator that sets the HTTP method to OPTIONS. -func AsOptions() PrepareDecorator { return WithMethod("OPTIONS") } - -// AsPatch returns a PrepareDecorator that sets the HTTP method to PATCH. -func AsPatch() PrepareDecorator { return WithMethod("PATCH") } - -// AsPost returns a PrepareDecorator that sets the HTTP method to POST. -func AsPost() PrepareDecorator { return WithMethod("POST") } - -// AsPut returns a PrepareDecorator that sets the HTTP method to PUT. -func AsPut() PrepareDecorator { return WithMethod("PUT") } - -// WithBaseURL returns a PrepareDecorator that populates the http.Request with a url.URL constructed -// from the supplied baseUrl. -func WithBaseURL(baseURL string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var u *url.URL - if u, err = url.Parse(baseURL); err != nil { - return r, err - } - if u.Scheme == "" { - err = fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) - } - if err == nil { - r.URL = u - } - } - return r, err - }) - } -} - -// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the -// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. -func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(urlParameters) - for key, value := range parameters { - baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1) - } - return WithBaseURL(baseURL) -} - -// WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the -// http.Request body. -func WithFormData(v url.Values) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - s := v.Encode() - - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(http.CanonicalHeaderKey(headerContentType), mimeTypeFormPost) - r.ContentLength = int64(len(s)) - r.Body = ioutil.NopCloser(strings.NewReader(s)) - } - return r, err - }) - } -} - -// WithMultiPartFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) form parameters -// into the http.Request body. -func WithMultiPartFormData(formDataParameters map[string]interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var body bytes.Buffer - writer := multipart.NewWriter(&body) - for key, value := range formDataParameters { - if rc, ok := value.(io.ReadCloser); ok { - var fd io.Writer - if fd, err = writer.CreateFormFile(key, key); err != nil { - return r, err - } - if _, err = io.Copy(fd, rc); err != nil { - return r, err - } - } else { - if err = writer.WriteField(key, ensureValueString(value)); err != nil { - return r, err - } - } - } - if err = writer.Close(); err != nil { - return r, err - } - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(http.CanonicalHeaderKey(headerContentType), writer.FormDataContentType()) - r.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - r.ContentLength = int64(body.Len()) - return r, err - } - return r, err - }) - } -} - -// WithFile returns a PrepareDecorator that sends file in request body. -func WithFile(f io.ReadCloser) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := ioutil.ReadAll(f) - if err != nil { - return r, err - } - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - r.ContentLength = int64(len(b)) - } - return r, err - }) - } -} - -// WithBool returns a PrepareDecorator that encodes the passed bool into the body of the request -// and sets the Content-Length header. -func WithBool(v bool) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat32 returns a PrepareDecorator that encodes the passed float32 into the body of the -// request and sets the Content-Length header. -func WithFloat32(v float32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat64 returns a PrepareDecorator that encodes the passed float64 into the body of the -// request and sets the Content-Length header. -func WithFloat64(v float64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt32 returns a PrepareDecorator that encodes the passed int32 into the body of the request -// and sets the Content-Length header. -func WithInt32(v int32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt64 returns a PrepareDecorator that encodes the passed int64 into the body of the request -// and sets the Content-Length header. -func WithInt64(v int64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithString returns a PrepareDecorator that encodes the passed string into the body of the request -// and sets the Content-Length header. -func WithString(v string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - r.ContentLength = int64(len(v)) - r.Body = ioutil.NopCloser(strings.NewReader(v)) - } - return r, err - }) - } -} - -// WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the -// request and sets the Content-Length header. -func WithJSON(v interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := json.Marshal(v) - if err == nil { - r.ContentLength = int64(len(b)) - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - } - return r, err - }) - } -} - -// WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path -// is absolute (that is, it begins with a "/"), it replaces the existing path. -func WithPath(path string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPath", "Invoked with a nil URL") - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithEscapedPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. The -// values will be escaped (aka URL encoded) before insertion into the path. -func WithEscapedPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := escapeValueStrings(ensureValueStrings(pathParameters)) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithEscapedPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. -func WithPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(pathParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -func parseURL(u *url.URL, path string) (*url.URL, error) { - p := strings.TrimRight(u.String(), "/") - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - return url.Parse(p + path) -} - -// WithQueryParameters returns a PrepareDecorators that encodes and applies the query parameters -// given in the supplied map (i.e., key=value). -func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(queryParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") - } - - v := r.URL.Query() - for key, value := range parameters { - d, err := url.QueryUnescape(value) - if err != nil { - return r, err - } - v.Add(key, d) - } - r.URL.RawQuery = v.Encode() - } - return r, err - }) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/responder.go deleted file mode 100644 index a908a0a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ /dev/null @@ -1,250 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// Responder is the interface that wraps the Respond method. -// -// Respond accepts and reacts to an http.Response. Implementations must ensure to not share or hold -// state since Responders may be shared and re-used. -type Responder interface { - Respond(*http.Response) error -} - -// ResponderFunc is a method that implements the Responder interface. -type ResponderFunc func(*http.Response) error - -// Respond implements the Responder interface on ResponderFunc. -func (rf ResponderFunc) Respond(r *http.Response) error { - return rf(r) -} - -// RespondDecorator takes and possibly decorates, by wrapping, a Responder. Decorators may react to -// the http.Response and pass it along or, first, pass the http.Response along then react. -type RespondDecorator func(Responder) Responder - -// CreateResponder creates, decorates, and returns a Responder. Without decorators, the returned -// Responder returns the passed http.Response unmodified. Responders may or may not be safe to share -// and re-used: It depends on the applied decorators. For example, a standard decorator that closes -// the response body is fine to share whereas a decorator that reads the body into a passed struct -// is not. -// -// To prevent memory leaks, ensure that at least one Responder closes the response body. -func CreateResponder(decorators ...RespondDecorator) Responder { - return DecorateResponder( - Responder(ResponderFunc(func(r *http.Response) error { return nil })), - decorators...) -} - -// DecorateResponder accepts a Responder and a, possibly empty, set of RespondDecorators, which it -// applies to the Responder. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (react to the http.Response and then pass it -// along) or a post-decorator (pass the http.Response along and then react). -func DecorateResponder(r Responder, decorators ...RespondDecorator) Responder { - for _, decorate := range decorators { - r = decorate(r) - } - return r -} - -// Respond accepts an http.Response and a, possibly empty, set of RespondDecorators. -// It creates a Responder from the decorators it then applies to the passed http.Response. -func Respond(r *http.Response, decorators ...RespondDecorator) error { - if r == nil { - return nil - } - return CreateResponder(decorators...).Respond(r) -} - -// ByIgnoring returns a RespondDecorator that ignores the passed http.Response passing it unexamined -// to the next RespondDecorator. -func ByIgnoring() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - return r.Respond(resp) - }) - } -} - -// ByCopying copies the contents of the http.Response Body into the passed bytes.Buffer as -// the Body is read. -func ByCopying(b *bytes.Buffer) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - resp.Body = TeeReadCloser(resp.Body, b) - } - return err - }) - } -} - -// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which -// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed -// Responder is invoked prior to discarding the response body, the decorator may occur anywhere -// within the set. -func ByDiscardingBody() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { - return fmt.Errorf("Error discarding the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosing returns a RespondDecorator that first invokes the passed Responder after which it -// closes the response body. Since the passed Responder is invoked prior to closing the response -// body, the decorator may occur anywhere within the set. -func ByClosing() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosingIfError returns a RespondDecorator that first invokes the passed Responder after which -// it closes the response if the passed Responder returns an error and the response body exists. -func ByClosingIfError() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err != nil && resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingJSON(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - // Some responses might include a BOM, remove for successful unmarshalling - b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else if len(strings.Trim(string(b), " ")) > 0 { - errInner = json.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling JSON - Error = '%v' JSON = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// ByUnmarshallingXML returns a RespondDecorator that decodes a XML document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingXML(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else { - errInner = xml.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling Xml - Error = '%v' Xml = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response -// StatusCode is among the set passed. On error, response body is fully read into a buffer and -// presented in the returned error, as well as in the response body. -func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - derr := NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - if resp.Body != nil { - defer resp.Body.Close() - b, _ := ioutil.ReadAll(resp.Body) - derr.ServiceError = b - resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - err = derr - } - return err - }) - } -} - -// WithErrorUnlessOK returns a RespondDecorator that emits an error if the response StatusCode is -// anything other than HTTP 200. -func WithErrorUnlessOK() RespondDecorator { - return WithErrorUnlessStatusCode(http.StatusOK) -} - -// ExtractHeader extracts all values of the specified header from the http.Response. It returns an -// empty string slice if the passed http.Response is nil or the header does not exist. -func ExtractHeader(header string, resp *http.Response) []string { - if resp != nil && resp.Header != nil { - return resp.Header[http.CanonicalHeaderKey(header)] - } - return nil -} - -// ExtractHeaderValue extracts the first value of the specified header from the http.Response. It -// returns an empty string if the passed http.Response is nil or the header does not exist. -func ExtractHeaderValue(header string, resp *http.Response) string { - h := ExtractHeader(header, resp) - if len(h) > 0 { - return h[0] - } - return "" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go deleted file mode 100644 index fa11dbe..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go +++ /dev/null @@ -1,52 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// NewRetriableRequest returns a wrapper around an HTTP request that support retry logic. -func NewRetriableRequest(req *http.Request) *RetriableRequest { - return &RetriableRequest{req: req} -} - -// Request returns the wrapped HTTP request. -func (rr *RetriableRequest) Request() *http.Request { - return rr.req -} - -func (rr *RetriableRequest) prepareFromByteReader() (err error) { - // fall back to making a copy (only do this once) - b := []byte{} - if rr.req.ContentLength > 0 { - b = make([]byte, rr.req.ContentLength) - _, err = io.ReadFull(rr.req.Body, b) - if err != nil { - return err - } - } else { - b, err = ioutil.ReadAll(rr.req.Body) - if err != nil { - return err - } - } - rr.br = bytes.NewReader(b) - rr.req.Body = ioutil.NopCloser(rr.br) - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go deleted file mode 100644 index 7143cc6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go +++ /dev/null @@ -1,54 +0,0 @@ -// +build !go1.8 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 autorest - -import ( - "bytes" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.br != nil { - _, err = rr.br.Seek(0, 0 /*io.SeekStart*/) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go deleted file mode 100644 index ae15c6b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build go1.8 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 autorest - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - rc io.ReadCloser - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.rc != nil { - rr.req.Body = rr.rc - } else if rr.br != nil { - _, err = rr.br.Seek(0, io.SeekStart) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.req.GetBody != nil { - // this will allow us to preserve the body without having to - // make a copy. note we need to do this on each iteration - rr.rc, err = rr.req.GetBody() - if err != nil { - return err - } - } else if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.GetBody = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/sender.go deleted file mode 100644 index cacbd81..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ /dev/null @@ -1,325 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "log" - "math" - "net/http" - "strconv" - "time" -) - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(&http.Client{}, decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} - -// Send sends, by means of the default http.Client, the passed http.Request, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// Send is a convenience method and not recommended for production. Advanced users should use -// SendWithSender, passing and sharing their own Sender (e.g., instance of http.Client). -// -// Send will not poll or retry requests. -func Send(r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return SendWithSender(&http.Client{}, r, decorators...) -} - -// SendWithSender sends the passed http.Request, through the provided Sender, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// SendWithSender will not poll or retry requests. -func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return DecorateSender(s, decorators...).Do(r) -} - -// AfterDelay returns a SendDecorator that delays for the passed time.Duration before -// invoking the Sender. The delay may be terminated by closing the optional channel on the -// http.Request. If canceled, no further Senders are invoked. -func AfterDelay(d time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if !DelayForBackoff(d, 0, r.Context().Done()) { - return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") - } - return s.Do(r) - }) - } -} - -// AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request. -func AsIs() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return s.Do(r) - }) - } -} - -// DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which -// it closes the response if the passed Sender returns an error and the response body exists. -func DoCloseIfError() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - Respond(resp, ByDiscardingBody(), ByClosing()) - } - return resp, err - }) - } -} - -// DoErrorIfStatusCode returns a SendDecorator that emits an error if the response StatusCode is -// among the set passed. Since these are artificial errors, the response body may still require -// closing. -func DoErrorIfStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorIfStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response -// StatusCode is among the set passed. Since these are artificial errors, the response body -// may still require closing. -func DoErrorUnlessStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoPollForStatusCodes returns a SendDecorator that polls if the http.Response contains one of the -// passed status codes. It expects the http.Response to contain a Location header providing the -// URL at which to poll (using GET) and will poll until the time passed is equal to or greater than -// the supplied duration. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by -// closing the optional channel on the http.Request. -func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - resp, err = s.Do(r) - - if err == nil && ResponseHasStatusCode(resp, codes...) { - r, err = NewPollingRequestWithContext(r.Context(), resp) - - for err == nil && ResponseHasStatusCode(resp, codes...) { - Respond(resp, - ByDiscardingBody(), - ByClosing()) - resp, err = SendWithSender(s, r, - AfterDelay(GetRetryAfter(resp, delay))) - } - } - - return resp, err - }) - } -} - -// DoRetryForAttempts returns a SendDecorator that retries a failed request for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. -func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - for attempt := 0; attempt < attempts; attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// DoRetryForStatusCodes returns a SendDecorator that retries for specified statusCodes for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. -func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - // Increment to add the first call (attempts denotes number of retries) - attempts++ - for attempt := 0; attempt < attempts; { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - // if the error isn't temporary don't bother retrying - if err != nil && !IsTemporaryNetworkError(err) { - return nil, err - } - // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication - // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. - if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { - return resp, err - } - delayed := DelayWithRetryAfter(resp, r.Context().Done()) - if !delayed && !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - // don't count a 429 against the number of attempts - // so that we continue to retry until it succeeds - if resp == nil || resp.StatusCode != http.StatusTooManyRequests { - attempt++ - } - } - return resp, err - }) - } -} - -// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header in -// responses with status code 429 -func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { - if resp == nil { - return false - } - retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After")) - if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 { - select { - case <-time.After(time.Duration(retryAfter) * time.Second): - return true - case <-cancel: - return false - } - } - return false -} - -// DoRetryForDuration returns a SendDecorator that retries the request until the total time is equal -// to or greater than the specified duration, exponentially backing off between requests using the -// supplied backoff time.Duration (which may be zero). Retrying may be canceled by closing the -// optional channel on the http.Request. -func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - end := time.Now().Add(d) - for attempt := 0; time.Now().Before(end); attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// WithLogging returns a SendDecorator that implements simple before and after logging of the -// request. -func WithLogging(logger *log.Logger) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - logger.Printf("Sending %s %s", r.Method, r.URL) - resp, err := s.Do(r) - if err != nil { - logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) - } else { - logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) - } - return resp, err - }) - } -} - -// DelayForBackoff invokes time.After for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set -// to zero for no delay. The delay may be canceled by closing the passed channel. If terminated early, -// returns false. -// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt -// count. -func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { - select { - case <-time.After(time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second): - return true - case <-cancel: - return false - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/to/convert.go deleted file mode 100644 index fdda2ce..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/to/convert.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Package to provides helpers to ease working with pointer values of marshalled structures. -*/ -package to - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// String returns a string value for the passed string pointer. It returns the empty string if the -// pointer is nil. -func String(s *string) string { - if s != nil { - return *s - } - return "" -} - -// StringPtr returns a pointer to the passed string. -func StringPtr(s string) *string { - return &s -} - -// StringSlice returns a string slice value for the passed string slice pointer. It returns a nil -// slice if the pointer is nil. -func StringSlice(s *[]string) []string { - if s != nil { - return *s - } - return nil -} - -// StringSlicePtr returns a pointer to the passed string slice. -func StringSlicePtr(s []string) *[]string { - return &s -} - -// StringMap returns a map of strings built from the map of string pointers. The empty string is -// used for nil pointers. -func StringMap(msp map[string]*string) map[string]string { - ms := make(map[string]string, len(msp)) - for k, sp := range msp { - if sp != nil { - ms[k] = *sp - } else { - ms[k] = "" - } - } - return ms -} - -// StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. -func StringMapPtr(ms map[string]string) *map[string]*string { - msp := make(map[string]*string, len(ms)) - for k, s := range ms { - msp[k] = StringPtr(s) - } - return &msp -} - -// Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil. -func Bool(b *bool) bool { - if b != nil { - return *b - } - return false -} - -// BoolPtr returns a pointer to the passed bool. -func BoolPtr(b bool) *bool { - return &b -} - -// Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int(i *int) int { - if i != nil { - return *i - } - return 0 -} - -// IntPtr returns a pointer to the passed int. -func IntPtr(i int) *int { - return &i -} - -// Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int32(i *int32) int32 { - if i != nil { - return *i - } - return 0 -} - -// Int32Ptr returns a pointer to the passed int32. -func Int32Ptr(i int32) *int32 { - return &i -} - -// Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int64(i *int64) int64 { - if i != nil { - return *i - } - return 0 -} - -// Int64Ptr returns a pointer to the passed int64. -func Int64Ptr(i int64) *int64 { - return &i -} - -// Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float32(i *float32) float32 { - if i != nil { - return *i - } - return 0.0 -} - -// Float32Ptr returns a pointer to the passed float32. -func Float32Ptr(i float32) *float32 { - return &i -} - -// Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float64(i *float64) float64 { - if i != nil { - return *i - } - return 0.0 -} - -// Float64Ptr returns a pointer to the passed float64. -func Float64Ptr(i float64) *float64 { - return &i -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/utility.go deleted file mode 100644 index bfddd90..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ /dev/null @@ -1,228 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "net" - "net/http" - "net/url" - "reflect" - "strings" - - "github.com/Azure/go-autorest/autorest/adal" -) - -// EncodedAs is a series of constants specifying various data encodings -type EncodedAs string - -const ( - // EncodedAsJSON states that data is encoded as JSON - EncodedAsJSON EncodedAs = "JSON" - - // EncodedAsXML states that data is encoded as Xml - EncodedAsXML EncodedAs = "XML" -) - -// Decoder defines the decoding method json.Decoder and xml.Decoder share -type Decoder interface { - Decode(v interface{}) error -} - -// NewDecoder creates a new decoder appropriate to the passed encoding. -// encodedAs specifies the type of encoding and r supplies the io.Reader containing the -// encoded data. -func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { - if encodedAs == EncodedAsJSON { - return json.NewDecoder(r) - } else if encodedAs == EncodedAsXML { - return xml.NewDecoder(r) - } - return nil -} - -// CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy -// is especially useful if there is a chance the data will fail to decode. -// encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v -// is the decoding destination. -func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { - b := bytes.Buffer{} - return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) -} - -// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. -// It utilizes io.TeeReader to copy the data read and has the same behavior when reading. -// Further, when it is closed, it ensures that rc is closed as well. -func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { - return &teeReadCloser{rc, io.TeeReader(rc, w)} -} - -type teeReadCloser struct { - rc io.ReadCloser - r io.Reader -} - -func (t *teeReadCloser) Read(p []byte) (int, error) { - return t.r.Read(p) -} - -func (t *teeReadCloser) Close() error { - return t.rc.Close() -} - -func containsInt(ints []int, n int) bool { - for _, i := range ints { - if i == n { - return true - } - } - return false -} - -func escapeValueStrings(m map[string]string) map[string]string { - for key, value := range m { - m[key] = url.QueryEscape(value) - } - return m -} - -func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string { - mapOfStrings := make(map[string]string) - for key, value := range mapOfInterface { - mapOfStrings[key] = ensureValueString(value) - } - return mapOfStrings -} - -func ensureValueString(value interface{}) string { - if value == nil { - return "" - } - switch v := value.(type) { - case string: - return v - case []byte: - return string(v) - default: - return fmt.Sprintf("%v", v) - } -} - -// MapToValues method converts map[string]interface{} to url.Values. -func MapToValues(m map[string]interface{}) url.Values { - v := url.Values{} - for key, value := range m { - x := reflect.ValueOf(value) - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - for i := 0; i < x.Len(); i++ { - v.Add(key, ensureValueString(x.Index(i))) - } - } else { - v.Add(key, ensureValueString(value)) - } - } - return v -} - -// AsStringSlice method converts interface{} to []string. This expects a -//that the parameter passed to be a slice or array of a type that has the underlying -//type a string. -func AsStringSlice(s interface{}) ([]string, error) { - v := reflect.ValueOf(s) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return nil, NewError("autorest", "AsStringSlice", "the value's type is not an array.") - } - stringSlice := make([]string, 0, v.Len()) - - for i := 0; i < v.Len(); i++ { - stringSlice = append(stringSlice, v.Index(i).String()) - } - return stringSlice, nil -} - -// String method converts interface v to string. If interface is a list, it -// joins list elements using the seperator. Note that only sep[0] will be used for -// joining if any separator is specified. -func String(v interface{}, sep ...string) string { - if len(sep) == 0 { - return ensureValueString(v) - } - stringSlice, ok := v.([]string) - if ok == false { - var err error - stringSlice, err = AsStringSlice(v) - if err != nil { - panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err)) - } - } - return ensureValueString(strings.Join(stringSlice, sep[0])) -} - -// Encode method encodes url path and query parameters. -func Encode(location string, v interface{}, sep ...string) string { - s := String(v, sep...) - switch strings.ToLower(location) { - case "path": - return pathEscape(s) - case "query": - return queryEscape(s) - default: - return s - } -} - -func pathEscape(s string) string { - return strings.Replace(url.QueryEscape(s), "+", "%20", -1) -} - -func queryEscape(s string) string { - return url.QueryEscape(s) -} - -// ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't). -// This is mainly useful for long-running operations that use the Azure-AsyncOperation -// header, so we change the initial PUT into a GET to retrieve the final result. -func ChangeToGet(req *http.Request) *http.Request { - req.Method = "GET" - req.Body = nil - req.ContentLength = 0 - req.Header.Del("Content-Length") - return req -} - -// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError -// interface. If err is a DetailedError it will walk the chain of Original errors. -func IsTokenRefreshError(err error) bool { - if _, ok := err.(adal.TokenRefreshError); ok { - return true - } - if de, ok := err.(DetailedError); ok { - return IsTokenRefreshError(de.Original) - } - return false -} - -// IsTemporaryNetworkError returns true if the specified error is a temporary network error or false -// if it's not. If the error doesn't implement the net.Error interface the return value is true. -func IsTemporaryNetworkError(err error) bool { - if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { - return true - } - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/validation/error.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/validation/error.go deleted file mode 100644 index fed156d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/validation/error.go +++ /dev/null @@ -1,48 +0,0 @@ -package validation - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" -) - -// Error is the type that's returned when the validation of an APIs arguments constraints fails. -type Error struct { - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // Message is the error message. - Message string -} - -// Error returns a string containing the details of the validation failure. -func (e Error) Error() string { - return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message) -} - -// NewError creates a new Error object with the specified parameters. -// message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) Error { - return Error{ - PackageType: packageType, - Method: method, - Message: fmt.Sprintf(message, args...), - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go deleted file mode 100644 index ae987f8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go +++ /dev/null @@ -1,408 +0,0 @@ -/* -Package validation provides methods for validating parameter value using reflection. -*/ -package validation - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "reflect" - "regexp" - "strings" -) - -// Constraint stores constraint name, target field name -// Rule and chain validations. -type Constraint struct { - - // Target field name for validation. - Target string - - // Constraint name e.g. minLength, MaxLength, Pattern, etc. - Name string - - // Rule for constraint e.g. greater than 10, less than 5 etc. - Rule interface{} - - // Chain Validations for struct type - Chain []Constraint -} - -// Validation stores parameter-wise validation. -type Validation struct { - TargetValue interface{} - Constraints []Constraint -} - -// Constraint list -const ( - Empty = "Empty" - Null = "Null" - ReadOnly = "ReadOnly" - Pattern = "Pattern" - MaxLength = "MaxLength" - MinLength = "MinLength" - MaxItems = "MaxItems" - MinItems = "MinItems" - MultipleOf = "MultipleOf" - UniqueItems = "UniqueItems" - InclusiveMaximum = "InclusiveMaximum" - ExclusiveMaximum = "ExclusiveMaximum" - ExclusiveMinimum = "ExclusiveMinimum" - InclusiveMinimum = "InclusiveMinimum" -) - -// Validate method validates constraints on parameter -// passed in validation array. -func Validate(m []Validation) error { - for _, item := range m { - v := reflect.ValueOf(item.TargetValue) - for _, constraint := range item.Constraints { - var err error - switch v.Kind() { - case reflect.Ptr: - err = validatePtr(v, constraint) - case reflect.String: - err = validateString(v, constraint) - case reflect.Struct: - err = validateStruct(v, constraint) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - err = validateInt(v, constraint) - case reflect.Float32, reflect.Float64: - err = validateFloat(v, constraint) - case reflect.Array, reflect.Slice, reflect.Map: - err = validateArrayMap(v, constraint) - default: - err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) - } - - if err != nil { - return err - } - } - } - return nil -} - -func validateStruct(x reflect.Value, v Constraint, name ...string) error { - //Get field name from target name which is in format a.b.c - s := strings.Split(v.Target, ".") - f := x.FieldByName(s[len(s)-1]) - if isZero(f) { - return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.Target)) - } - - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(f), - Constraints: []Constraint{v}, - }, - }) -} - -func validatePtr(x reflect.Value, v Constraint) error { - if v.Name == ReadOnly { - if !x.IsNil() { - return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") - } - return nil - } - if x.IsNil() { - return checkNil(x, v) - } - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x.Elem()), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func validateInt(x reflect.Value, v Constraint) error { - i := x.Int() - r, ok := toInt64(v.Rule) - if !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - switch v.Name { - case MultipleOf: - if i%r != 0 { - return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) - } - case ExclusiveMinimum: - if i <= r { - return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) - } - case ExclusiveMaximum: - if i >= r { - return createError(x, v, fmt.Sprintf("value must be less than %v", r)) - } - case InclusiveMinimum: - if i < r { - return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) - } - case InclusiveMaximum: - if i > r { - return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) - } - default: - return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.Name)) - } - return nil -} - -func validateFloat(x reflect.Value, v Constraint) error { - f := x.Float() - r, ok := v.Rule.(float64) - if !ok { - return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.Name, v.Rule)) - } - switch v.Name { - case ExclusiveMinimum: - if f <= r { - return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) - } - case ExclusiveMaximum: - if f >= r { - return createError(x, v, fmt.Sprintf("value must be less than %v", r)) - } - case InclusiveMinimum: - if f < r { - return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) - } - case InclusiveMaximum: - if f > r { - return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) - } - default: - return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.Name)) - } - return nil -} - -func validateString(x reflect.Value, v Constraint) error { - s := x.String() - switch v.Name { - case Empty: - if len(s) == 0 { - return checkEmpty(x, v) - } - case Pattern: - reg, err := regexp.Compile(v.Rule.(string)) - if err != nil { - return createError(x, v, err.Error()) - } - if !reg.MatchString(s) { - return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.Rule)) - } - case MaxLength: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - if len(s) > v.Rule.(int) { - return createError(x, v, fmt.Sprintf("value length must be less than or equal to %v", v.Rule)) - } - case MinLength: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - if len(s) < v.Rule.(int) { - return createError(x, v, fmt.Sprintf("value length must be greater than or equal to %v", v.Rule)) - } - case ReadOnly: - if len(s) > 0 { - return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") - } - default: - return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.Name)) - } - - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func validateArrayMap(x reflect.Value, v Constraint) error { - switch v.Name { - case Null: - if x.IsNil() { - return checkNil(x, v) - } - case Empty: - if x.IsNil() || x.Len() == 0 { - return checkEmpty(x, v) - } - case MaxItems: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) - } - if x.Len() > v.Rule.(int) { - return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.Rule, x.Len())) - } - case MinItems: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) - } - if x.Len() < v.Rule.(int) { - return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.Rule, x.Len())) - } - case UniqueItems: - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - if !checkForUniqueInArray(x) { - return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) - } - } else if x.Kind() == reflect.Map { - if !checkForUniqueInMap(x) { - return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) - } - } else { - return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.Name, x.Kind())) - } - case ReadOnly: - if x.Len() != 0 { - return createError(x, v, "readonly parameter; must send as nil or empty in request") - } - case Pattern: - reg, err := regexp.Compile(v.Rule.(string)) - if err != nil { - return createError(x, v, err.Error()) - } - keys := x.MapKeys() - for _, k := range keys { - if !reg.MatchString(k.String()) { - return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.Rule)) - } - } - default: - return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.Name)) - } - - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func checkNil(x reflect.Value, v Constraint) error { - if _, ok := v.Rule.(bool); !ok { - return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - } - if v.Rule.(bool) { - return createError(x, v, "value can not be null; required parameter") - } - return nil -} - -func checkEmpty(x reflect.Value, v Constraint) error { - if _, ok := v.Rule.(bool); !ok { - return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - } - - if v.Rule.(bool) { - return createError(x, v, "value can not be null or empty; required parameter") - } - return nil -} - -func checkForUniqueInArray(x reflect.Value) bool { - if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { - return false - } - arrOfInterface := make([]interface{}, x.Len()) - - for i := 0; i < x.Len(); i++ { - arrOfInterface[i] = x.Index(i).Interface() - } - - m := make(map[interface{}]bool) - for _, val := range arrOfInterface { - if m[val] { - return false - } - m[val] = true - } - return true -} - -func checkForUniqueInMap(x reflect.Value) bool { - if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { - return false - } - mapOfInterface := make(map[interface{}]interface{}, x.Len()) - - keys := x.MapKeys() - for _, k := range keys { - mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() - } - - m := make(map[interface{}]bool) - for _, val := range mapOfInterface { - if m[val] { - return false - } - m[val] = true - } - return true -} - -func getInterfaceValue(x reflect.Value) interface{} { - if x.Kind() == reflect.Invalid { - return nil - } - return x.Interface() -} - -func isZero(x interface{}) bool { - return x == reflect.Zero(reflect.TypeOf(x)).Interface() -} - -func createError(x reflect.Value, v Constraint, err string) error { - return fmt.Errorf("autorest/validation: validation failed: parameter=%s constraint=%s value=%#v details: %s", - v.Target, v.Name, getInterfaceValue(x), err) -} - -func toInt64(v interface{}) (int64, bool) { - if i64, ok := v.(int64); ok { - return i64, true - } - // older generators emit max constants as int, so if int64 fails fall back to int - if i32, ok := v.(int); ok { - return int64(i32), true - } - return 0, false -} - -// NewErrorWithValidationError appends package type and method name in -// validation error. -// -// Deprecated: Please use validation.NewError() instead. -func NewErrorWithValidationError(err error, packageType, method string) error { - return NewError(packageType, method, err.Error()) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/version.go deleted file mode 100644 index 3c64515..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/autorest/version.go +++ /dev/null @@ -1,22 +0,0 @@ -package autorest - -import "github.com/Azure/go-autorest/version" - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Version returns the semantic version (see http://semver.org). -func Version() string { - return version.Number -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/logger/logger.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/logger/logger.go deleted file mode 100644 index 756fd80..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/logger/logger.go +++ /dev/null @@ -1,328 +0,0 @@ -package logger - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - "sync" - "time" -) - -// LevelType tells a logger the minimum level to log. When code reports a log entry, -// the LogLevel indicates the level of the log entry. The logger only records entries -// whose level is at least the level it was told to log. See the Log* constants. -// For example, if a logger is configured with LogError, then LogError, LogPanic, -// and LogFatal entries will be logged; lower level entries are ignored. -type LevelType uint32 - -const ( - // LogNone tells a logger not to log any entries passed to it. - LogNone LevelType = iota - - // LogFatal tells a logger to log all LogFatal entries passed to it. - LogFatal - - // LogPanic tells a logger to log all LogPanic and LogFatal entries passed to it. - LogPanic - - // LogError tells a logger to log all LogError, LogPanic and LogFatal entries passed to it. - LogError - - // LogWarning tells a logger to log all LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogWarning - - // LogInfo tells a logger to log all LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogInfo - - // LogDebug tells a logger to log all LogDebug, LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogDebug -) - -const ( - logNone = "NONE" - logFatal = "FATAL" - logPanic = "PANIC" - logError = "ERROR" - logWarning = "WARNING" - logInfo = "INFO" - logDebug = "DEBUG" - logUnknown = "UNKNOWN" -) - -// ParseLevel converts the specified string into the corresponding LevelType. -func ParseLevel(s string) (lt LevelType, err error) { - switch strings.ToUpper(s) { - case logFatal: - lt = LogFatal - case logPanic: - lt = LogPanic - case logError: - lt = LogError - case logWarning: - lt = LogWarning - case logInfo: - lt = LogInfo - case logDebug: - lt = LogDebug - default: - err = fmt.Errorf("bad log level '%s'", s) - } - return -} - -// String implements the stringer interface for LevelType. -func (lt LevelType) String() string { - switch lt { - case LogNone: - return logNone - case LogFatal: - return logFatal - case LogPanic: - return logPanic - case LogError: - return logError - case LogWarning: - return logWarning - case LogInfo: - return logInfo - case LogDebug: - return logDebug - default: - return logUnknown - } -} - -// Filter defines functions for filtering HTTP request/response content. -type Filter struct { - // URL returns a potentially modified string representation of a request URL. - URL func(u *url.URL) string - - // Header returns a potentially modified set of values for the specified key. - // To completely exclude the header key/values return false. - Header func(key string, val []string) (bool, []string) - - // Body returns a potentially modified request/response body. - Body func(b []byte) []byte -} - -func (f Filter) processURL(u *url.URL) string { - if f.URL == nil { - return u.String() - } - return f.URL(u) -} - -func (f Filter) processHeader(k string, val []string) (bool, []string) { - if f.Header == nil { - return true, val - } - return f.Header(k, val) -} - -func (f Filter) processBody(b []byte) []byte { - if f.Body == nil { - return b - } - return f.Body(b) -} - -// Writer defines methods for writing to a logging facility. -type Writer interface { - // Writeln writes the specified message with the standard log entry header and new-line character. - Writeln(level LevelType, message string) - - // Writef writes the specified format specifier with the standard log entry header and no new-line character. - Writef(level LevelType, format string, a ...interface{}) - - // WriteRequest writes the specified HTTP request to the logger if the log level is greater than - // or equal to LogInfo. The request body, if set, is logged at level LogDebug or higher. - // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no request content is excluded. - WriteRequest(req *http.Request, filter Filter) - - // WriteResponse writes the specified HTTP response to the logger if the log level is greater than - // or equal to LogInfo. The response body, if set, is logged at level LogDebug or higher. - // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no respone content is excluded. - WriteResponse(resp *http.Response, filter Filter) -} - -// Instance is the default log writer initialized during package init. -// This can be replaced with a custom implementation as required. -var Instance Writer - -// default log level -var logLevel = LogNone - -// Level returns the value specified in AZURE_GO_AUTOREST_LOG_LEVEL. -// If no value was specified the default value is LogNone. -// Custom loggers can call this to retrieve the configured log level. -func Level() LevelType { - return logLevel -} - -func init() { - // separated for testing purposes - initDefaultLogger() -} - -func initDefaultLogger() { - // init with nilLogger so callers don't have to do a nil check on Default - Instance = nilLogger{} - llStr := strings.ToLower(os.Getenv("AZURE_GO_SDK_LOG_LEVEL")) - if llStr == "" { - return - } - var err error - logLevel, err = ParseLevel(llStr) - if err != nil { - fmt.Fprintf(os.Stderr, "go-autorest: failed to parse log level: %s\n", err.Error()) - return - } - if logLevel == LogNone { - return - } - // default to stderr - dest := os.Stderr - lfStr := os.Getenv("AZURE_GO_SDK_LOG_FILE") - if strings.EqualFold(lfStr, "stdout") { - dest = os.Stdout - } else if lfStr != "" { - lf, err := os.Create(lfStr) - if err == nil { - dest = lf - } else { - fmt.Fprintf(os.Stderr, "go-autorest: failed to create log file, using stderr: %s\n", err.Error()) - } - } - Instance = fileLogger{ - logLevel: logLevel, - mu: &sync.Mutex{}, - logFile: dest, - } -} - -// the nil logger does nothing -type nilLogger struct{} - -func (nilLogger) Writeln(LevelType, string) {} - -func (nilLogger) Writef(LevelType, string, ...interface{}) {} - -func (nilLogger) WriteRequest(*http.Request, Filter) {} - -func (nilLogger) WriteResponse(*http.Response, Filter) {} - -// A File is used instead of a Logger so the stream can be flushed after every write. -type fileLogger struct { - logLevel LevelType - mu *sync.Mutex // for synchronizing writes to logFile - logFile *os.File -} - -func (fl fileLogger) Writeln(level LevelType, message string) { - fl.Writef(level, "%s\n", message) -} - -func (fl fileLogger) Writef(level LevelType, format string, a ...interface{}) { - if fl.logLevel >= level { - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprintf(fl.logFile, "%s %s", entryHeader(level), fmt.Sprintf(format, a...)) - fl.logFile.Sync() - } -} - -func (fl fileLogger) WriteRequest(req *http.Request, filter Filter) { - if req == nil || fl.logLevel < LogInfo { - return - } - b := &bytes.Buffer{} - fmt.Fprintf(b, "%s REQUEST: %s %s\n", entryHeader(LogInfo), req.Method, filter.processURL(req.URL)) - // dump headers - for k, v := range req.Header { - if ok, mv := filter.processHeader(k, v); ok { - fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ",")) - } - } - if fl.shouldLogBody(req.Header, req.Body) { - // dump body - body, err := ioutil.ReadAll(req.Body) - if err == nil { - fmt.Fprintln(b, string(filter.processBody(body))) - if nc, ok := req.Body.(io.Seeker); ok { - // rewind to the beginning - nc.Seek(0, io.SeekStart) - } else { - // recreate the body - req.Body = ioutil.NopCloser(bytes.NewReader(body)) - } - } else { - fmt.Fprintf(b, "failed to read body: %v\n", err) - } - } - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprint(fl.logFile, b.String()) - fl.logFile.Sync() -} - -func (fl fileLogger) WriteResponse(resp *http.Response, filter Filter) { - if resp == nil || fl.logLevel < LogInfo { - return - } - b := &bytes.Buffer{} - fmt.Fprintf(b, "%s RESPONSE: %d %s\n", entryHeader(LogInfo), resp.StatusCode, filter.processURL(resp.Request.URL)) - // dump headers - for k, v := range resp.Header { - if ok, mv := filter.processHeader(k, v); ok { - fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ",")) - } - } - if fl.shouldLogBody(resp.Header, resp.Body) { - // dump body - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err == nil { - fmt.Fprintln(b, string(filter.processBody(body))) - resp.Body = ioutil.NopCloser(bytes.NewReader(body)) - } else { - fmt.Fprintf(b, "failed to read body: %v\n", err) - } - } - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprint(fl.logFile, b.String()) - fl.logFile.Sync() -} - -// returns true if the provided body should be included in the log -func (fl fileLogger) shouldLogBody(header http.Header, body io.ReadCloser) bool { - ct := header.Get("Content-Type") - return fl.logLevel >= LogDebug && body != nil && strings.Index(ct, "application/octet-stream") == -1 -} - -// creates standard header for log entries, it contains a timestamp and the log level -func entryHeader(level LevelType) string { - // this format provides a fixed number of digits so the size of the timestamp is constant - return fmt.Sprintf("(%s) %s:", time.Now().Format("2006-01-02T15:04:05.0000000Z07:00"), level.String()) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/version/version.go b/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/version/version.go deleted file mode 100644 index 8e1e7e1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/Azure/go-autorest/version/version.go +++ /dev/null @@ -1,37 +0,0 @@ -package version - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "runtime" -) - -// Number contains the semantic version of this SDK. -const Number = "v10.15.2" - -var ( - userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", - runtime.Version(), - runtime.GOARCH, - runtime.GOOS, - Number, - ) -) - -// UserAgent returns a string containing the Go version, system archityecture and OS, and the go-autorest version. -func UserAgent() string { - return userAgent -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/COPYING b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/COPYING deleted file mode 100644 index 01b5743..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 TOML authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING deleted file mode 100644 index 01b5743..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 TOML authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING deleted file mode 100644 index 01b5743..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 TOML authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING deleted file mode 100644 index 01b5743..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 TOML authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/decode.go deleted file mode 100644 index b0fd51d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/decode.go +++ /dev/null @@ -1,509 +0,0 @@ -package toml - -import ( - "fmt" - "io" - "io/ioutil" - "math" - "reflect" - "strings" - "time" -) - -func e(format string, args ...interface{}) error { - return fmt.Errorf("toml: "+format, args...) -} - -// Unmarshaler is the interface implemented by objects that can unmarshal a -// TOML description of themselves. -type Unmarshaler interface { - UnmarshalTOML(interface{}) error -} - -// Unmarshal decodes the contents of `p` in TOML format into a pointer `v`. -func Unmarshal(p []byte, v interface{}) error { - _, err := Decode(string(p), v) - return err -} - -// Primitive is a TOML value that hasn't been decoded into a Go value. -// When using the various `Decode*` functions, the type `Primitive` may -// be given to any value, and its decoding will be delayed. -// -// A `Primitive` value can be decoded using the `PrimitiveDecode` function. -// -// The underlying representation of a `Primitive` value is subject to change. -// Do not rely on it. -// -// N.B. Primitive values are still parsed, so using them will only avoid -// the overhead of reflection. They can be useful when you don't know the -// exact type of TOML data until run time. -type Primitive struct { - undecoded interface{} - context Key -} - -// DEPRECATED! -// -// Use MetaData.PrimitiveDecode instead. -func PrimitiveDecode(primValue Primitive, v interface{}) error { - md := MetaData{decoded: make(map[string]bool)} - return md.unify(primValue.undecoded, rvalue(v)) -} - -// PrimitiveDecode is just like the other `Decode*` functions, except it -// decodes a TOML value that has already been parsed. Valid primitive values -// can *only* be obtained from values filled by the decoder functions, -// including this method. (i.e., `v` may contain more `Primitive` -// values.) -// -// Meta data for primitive values is included in the meta data returned by -// the `Decode*` functions with one exception: keys returned by the Undecoded -// method will only reflect keys that were decoded. Namely, any keys hidden -// behind a Primitive will be considered undecoded. Executing this method will -// update the undecoded keys in the meta data. (See the example.) -func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { - md.context = primValue.context - defer func() { md.context = nil }() - return md.unify(primValue.undecoded, rvalue(v)) -} - -// Decode will decode the contents of `data` in TOML format into a pointer -// `v`. -// -// TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be -// used interchangeably.) -// -// TOML arrays of tables correspond to either a slice of structs or a slice -// of maps. -// -// TOML datetimes correspond to Go `time.Time` values. -// -// All other TOML types (float, string, int, bool and array) correspond -// to the obvious Go types. -// -// An exception to the above rules is if a type implements the -// encoding.TextUnmarshaler interface. In this case, any primitive TOML value -// (floats, strings, integers, booleans and datetimes) will be converted to -// a byte string and given to the value's UnmarshalText method. See the -// Unmarshaler example for a demonstration with time duration strings. -// -// Key mapping -// -// TOML keys can map to either keys in a Go map or field names in a Go -// struct. The special `toml` struct tag may be used to map TOML keys to -// struct fields that don't match the key name exactly. (See the example.) -// A case insensitive match to struct names will be tried if an exact match -// can't be found. -// -// The mapping between TOML values and Go values is loose. That is, there -// may exist TOML values that cannot be placed into your representation, and -// there may be parts of your representation that do not correspond to -// TOML values. This loose mapping can be made stricter by using the IsDefined -// and/or Undecoded methods on the MetaData returned. -// -// This decoder will not handle cyclic types. If a cyclic type is passed, -// `Decode` will not terminate. -func Decode(data string, v interface{}) (MetaData, error) { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr { - return MetaData{}, e("Decode of non-pointer %s", reflect.TypeOf(v)) - } - if rv.IsNil() { - return MetaData{}, e("Decode of nil %s", reflect.TypeOf(v)) - } - p, err := parse(data) - if err != nil { - return MetaData{}, err - } - md := MetaData{ - p.mapping, p.types, p.ordered, - make(map[string]bool, len(p.ordered)), nil, - } - return md, md.unify(p.mapping, indirect(rv)) -} - -// DecodeFile is just like Decode, except it will automatically read the -// contents of the file at `fpath` and decode it for you. -func DecodeFile(fpath string, v interface{}) (MetaData, error) { - bs, err := ioutil.ReadFile(fpath) - if err != nil { - return MetaData{}, err - } - return Decode(string(bs), v) -} - -// DecodeReader is just like Decode, except it will consume all bytes -// from the reader and decode it for you. -func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { - bs, err := ioutil.ReadAll(r) - if err != nil { - return MetaData{}, err - } - return Decode(string(bs), v) -} - -// unify performs a sort of type unification based on the structure of `rv`, -// which is the client representation. -// -// Any type mismatch produces an error. Finding a type that we don't know -// how to handle produces an unsupported type error. -func (md *MetaData) unify(data interface{}, rv reflect.Value) error { - - // Special case. Look for a `Primitive` value. - if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { - // Save the undecoded data and the key context into the primitive - // value. - context := make(Key, len(md.context)) - copy(context, md.context) - rv.Set(reflect.ValueOf(Primitive{ - undecoded: data, - context: context, - })) - return nil - } - - // Special case. Unmarshaler Interface support. - if rv.CanAddr() { - if v, ok := rv.Addr().Interface().(Unmarshaler); ok { - return v.UnmarshalTOML(data) - } - } - - // Special case. Handle time.Time values specifically. - // TODO: Remove this code when we decide to drop support for Go 1.1. - // This isn't necessary in Go 1.2 because time.Time satisfies the encoding - // interfaces. - if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) { - return md.unifyDatetime(data, rv) - } - - // Special case. Look for a value satisfying the TextUnmarshaler interface. - if v, ok := rv.Interface().(TextUnmarshaler); ok { - return md.unifyText(data, v) - } - // BUG(burntsushi) - // The behavior here is incorrect whenever a Go type satisfies the - // encoding.TextUnmarshaler interface but also corresponds to a TOML - // hash or array. In particular, the unmarshaler should only be applied - // to primitive TOML values. But at this point, it will be applied to - // all kinds of values and produce an incorrect error whenever those values - // are hashes or arrays (including arrays of tables). - - k := rv.Kind() - - // laziness - if k >= reflect.Int && k <= reflect.Uint64 { - return md.unifyInt(data, rv) - } - switch k { - case reflect.Ptr: - elem := reflect.New(rv.Type().Elem()) - err := md.unify(data, reflect.Indirect(elem)) - if err != nil { - return err - } - rv.Set(elem) - return nil - case reflect.Struct: - return md.unifyStruct(data, rv) - case reflect.Map: - return md.unifyMap(data, rv) - case reflect.Array: - return md.unifyArray(data, rv) - case reflect.Slice: - return md.unifySlice(data, rv) - case reflect.String: - return md.unifyString(data, rv) - case reflect.Bool: - return md.unifyBool(data, rv) - case reflect.Interface: - // we only support empty interfaces. - if rv.NumMethod() > 0 { - return e("unsupported type %s", rv.Type()) - } - return md.unifyAnything(data, rv) - case reflect.Float32: - fallthrough - case reflect.Float64: - return md.unifyFloat64(data, rv) - } - return e("unsupported type %s", rv.Kind()) -} - -func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) - if !ok { - if mapping == nil { - return nil - } - return e("type mismatch for %s: expected table but found %T", - rv.Type().String(), mapping) - } - - for key, datum := range tmap { - var f *field - fields := cachedTypeFields(rv.Type()) - for i := range fields { - ff := &fields[i] - if ff.name == key { - f = ff - break - } - if f == nil && strings.EqualFold(ff.name, key) { - f = ff - } - } - if f != nil { - subv := rv - for _, i := range f.index { - subv = indirect(subv.Field(i)) - } - if isUnifiable(subv) { - md.decoded[md.context.add(key).String()] = true - md.context = append(md.context, key) - if err := md.unify(datum, subv); err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - } else if f.name != "" { - // Bad user! No soup for you! - return e("cannot write unexported field %s.%s", - rv.Type().String(), f.name) - } - } - } - return nil -} - -func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) - if !ok { - if tmap == nil { - return nil - } - return badtype("map", mapping) - } - if rv.IsNil() { - rv.Set(reflect.MakeMap(rv.Type())) - } - for k, v := range tmap { - md.decoded[md.context.add(k).String()] = true - md.context = append(md.context, k) - - rvkey := indirect(reflect.New(rv.Type().Key())) - rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) - if err := md.unify(v, rvval); err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - - rvkey.SetString(k) - rv.SetMapIndex(rvkey, rvval) - } - return nil -} - -func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - if !datav.IsValid() { - return nil - } - return badtype("slice", data) - } - sliceLen := datav.Len() - if sliceLen != rv.Len() { - return e("expected array length %d; got TOML array of length %d", - rv.Len(), sliceLen) - } - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - if !datav.IsValid() { - return nil - } - return badtype("slice", data) - } - n := datav.Len() - if rv.IsNil() || rv.Cap() < n { - rv.Set(reflect.MakeSlice(rv.Type(), n, n)) - } - rv.SetLen(n) - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { - sliceLen := data.Len() - for i := 0; i < sliceLen; i++ { - v := data.Index(i).Interface() - sliceval := indirect(rv.Index(i)) - if err := md.unify(v, sliceval); err != nil { - return err - } - } - return nil -} - -func (md *MetaData) unifyDatetime(data interface{}, rv reflect.Value) error { - if _, ok := data.(time.Time); ok { - rv.Set(reflect.ValueOf(data)) - return nil - } - return badtype("time.Time", data) -} - -func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { - if s, ok := data.(string); ok { - rv.SetString(s) - return nil - } - return badtype("string", data) -} - -func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { - if num, ok := data.(float64); ok { - switch rv.Kind() { - case reflect.Float32: - fallthrough - case reflect.Float64: - rv.SetFloat(num) - default: - panic("bug") - } - return nil - } - return badtype("float", data) -} - -func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { - if num, ok := data.(int64); ok { - if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 { - switch rv.Kind() { - case reflect.Int, reflect.Int64: - // No bounds checking necessary. - case reflect.Int8: - if num < math.MinInt8 || num > math.MaxInt8 { - return e("value %d is out of range for int8", num) - } - case reflect.Int16: - if num < math.MinInt16 || num > math.MaxInt16 { - return e("value %d is out of range for int16", num) - } - case reflect.Int32: - if num < math.MinInt32 || num > math.MaxInt32 { - return e("value %d is out of range for int32", num) - } - } - rv.SetInt(num) - } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 { - unum := uint64(num) - switch rv.Kind() { - case reflect.Uint, reflect.Uint64: - // No bounds checking necessary. - case reflect.Uint8: - if num < 0 || unum > math.MaxUint8 { - return e("value %d is out of range for uint8", num) - } - case reflect.Uint16: - if num < 0 || unum > math.MaxUint16 { - return e("value %d is out of range for uint16", num) - } - case reflect.Uint32: - if num < 0 || unum > math.MaxUint32 { - return e("value %d is out of range for uint32", num) - } - } - rv.SetUint(unum) - } else { - panic("unreachable") - } - return nil - } - return badtype("integer", data) -} - -func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { - if b, ok := data.(bool); ok { - rv.SetBool(b) - return nil - } - return badtype("boolean", data) -} - -func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error { - rv.Set(reflect.ValueOf(data)) - return nil -} - -func (md *MetaData) unifyText(data interface{}, v TextUnmarshaler) error { - var s string - switch sdata := data.(type) { - case TextMarshaler: - text, err := sdata.MarshalText() - if err != nil { - return err - } - s = string(text) - case fmt.Stringer: - s = sdata.String() - case string: - s = sdata - case bool: - s = fmt.Sprintf("%v", sdata) - case int64: - s = fmt.Sprintf("%d", sdata) - case float64: - s = fmt.Sprintf("%f", sdata) - default: - return badtype("primitive (string-like)", data) - } - if err := v.UnmarshalText([]byte(s)); err != nil { - return err - } - return nil -} - -// rvalue returns a reflect.Value of `v`. All pointers are resolved. -func rvalue(v interface{}) reflect.Value { - return indirect(reflect.ValueOf(v)) -} - -// indirect returns the value pointed to by a pointer. -// Pointers are followed until the value is not a pointer. -// New values are allocated for each nil pointer. -// -// An exception to this rule is if the value satisfies an interface of -// interest to us (like encoding.TextUnmarshaler). -func indirect(v reflect.Value) reflect.Value { - if v.Kind() != reflect.Ptr { - if v.CanSet() { - pv := v.Addr() - if _, ok := pv.Interface().(TextUnmarshaler); ok { - return pv - } - } - return v - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - return indirect(reflect.Indirect(v)) -} - -func isUnifiable(rv reflect.Value) bool { - if rv.CanSet() { - return true - } - if _, ok := rv.Interface().(TextUnmarshaler); ok { - return true - } - return false -} - -func badtype(expected string, data interface{}) error { - return e("cannot load TOML value of type %T into a Go %s", data, expected) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/decode_meta.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/decode_meta.go deleted file mode 100644 index b9914a6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/decode_meta.go +++ /dev/null @@ -1,121 +0,0 @@ -package toml - -import "strings" - -// MetaData allows access to meta information about TOML data that may not -// be inferrable via reflection. In particular, whether a key has been defined -// and the TOML type of a key. -type MetaData struct { - mapping map[string]interface{} - types map[string]tomlType - keys []Key - decoded map[string]bool - context Key // Used only during decoding. -} - -// IsDefined returns true if the key given exists in the TOML data. The key -// should be specified hierarchially. e.g., -// -// // access the TOML key 'a.b.c' -// IsDefined("a", "b", "c") -// -// IsDefined will return false if an empty key given. Keys are case sensitive. -func (md *MetaData) IsDefined(key ...string) bool { - if len(key) == 0 { - return false - } - - var hash map[string]interface{} - var ok bool - var hashOrVal interface{} = md.mapping - for _, k := range key { - if hash, ok = hashOrVal.(map[string]interface{}); !ok { - return false - } - if hashOrVal, ok = hash[k]; !ok { - return false - } - } - return true -} - -// Type returns a string representation of the type of the key specified. -// -// Type will return the empty string if given an empty key or a key that -// does not exist. Keys are case sensitive. -func (md *MetaData) Type(key ...string) string { - fullkey := strings.Join(key, ".") - if typ, ok := md.types[fullkey]; ok { - return typ.typeString() - } - return "" -} - -// Key is the type of any TOML key, including key groups. Use (MetaData).Keys -// to get values of this type. -type Key []string - -func (k Key) String() string { - return strings.Join(k, ".") -} - -func (k Key) maybeQuotedAll() string { - var ss []string - for i := range k { - ss = append(ss, k.maybeQuoted(i)) - } - return strings.Join(ss, ".") -} - -func (k Key) maybeQuoted(i int) string { - quote := false - for _, c := range k[i] { - if !isBareKeyChar(c) { - quote = true - break - } - } - if quote { - return "\"" + strings.Replace(k[i], "\"", "\\\"", -1) + "\"" - } - return k[i] -} - -func (k Key) add(piece string) Key { - newKey := make(Key, len(k)+1) - copy(newKey, k) - newKey[len(k)] = piece - return newKey -} - -// Keys returns a slice of every key in the TOML data, including key groups. -// Each key is itself a slice, where the first element is the top of the -// hierarchy and the last is the most specific. -// -// The list will have the same order as the keys appeared in the TOML data. -// -// All keys returned are non-empty. -func (md *MetaData) Keys() []Key { - return md.keys -} - -// Undecoded returns all keys that have not been decoded in the order in which -// they appear in the original TOML document. -// -// This includes keys that haven't been decoded because of a Primitive value. -// Once the Primitive value is decoded, the keys will be considered decoded. -// -// Also note that decoding into an empty interface will result in no decoding, -// and so no keys will be considered decoded. -// -// In this sense, the Undecoded keys correspond to keys in the TOML document -// that do not have a concrete type in your representation. -func (md *MetaData) Undecoded() []Key { - undecoded := make([]Key, 0, len(md.keys)) - for _, key := range md.keys { - if !md.decoded[key.String()] { - undecoded = append(undecoded, key) - } - } - return undecoded -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/doc.go deleted file mode 100644 index b371f39..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/doc.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Package toml provides facilities for decoding and encoding TOML configuration -files via reflection. There is also support for delaying decoding with -the Primitive type, and querying the set of keys in a TOML document with the -MetaData type. - -The specification implemented: https://github.com/toml-lang/toml - -The sub-command github.com/BurntSushi/toml/cmd/tomlv can be used to verify -whether a file is a valid TOML document. It can also be used to print the -type of each key in a TOML document. - -Testing - -There are two important types of tests used for this package. The first is -contained inside '*_test.go' files and uses the standard Go unit testing -framework. These tests are primarily devoted to holistically testing the -decoder and encoder. - -The second type of testing is used to verify the implementation's adherence -to the TOML specification. These tests have been factored into their own -project: https://github.com/BurntSushi/toml-test - -The reason the tests are in a separate project is so that they can be used by -any implementation of TOML. Namely, it is language agnostic. -*/ -package toml diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encode.go deleted file mode 100644 index d905c21..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encode.go +++ /dev/null @@ -1,568 +0,0 @@ -package toml - -import ( - "bufio" - "errors" - "fmt" - "io" - "reflect" - "sort" - "strconv" - "strings" - "time" -) - -type tomlEncodeError struct{ error } - -var ( - errArrayMixedElementTypes = errors.New( - "toml: cannot encode array with mixed element types") - errArrayNilElement = errors.New( - "toml: cannot encode array with nil element") - errNonString = errors.New( - "toml: cannot encode a map with non-string key type") - errAnonNonStruct = errors.New( - "toml: cannot encode an anonymous field that is not a struct") - errArrayNoTable = errors.New( - "toml: TOML array element cannot contain a table") - errNoKey = errors.New( - "toml: top-level values must be Go maps or structs") - errAnything = errors.New("") // used in testing -) - -var quotedReplacer = strings.NewReplacer( - "\t", "\\t", - "\n", "\\n", - "\r", "\\r", - "\"", "\\\"", - "\\", "\\\\", -) - -// Encoder controls the encoding of Go values to a TOML document to some -// io.Writer. -// -// The indentation level can be controlled with the Indent field. -type Encoder struct { - // A single indentation level. By default it is two spaces. - Indent string - - // hasWritten is whether we have written any output to w yet. - hasWritten bool - w *bufio.Writer -} - -// NewEncoder returns a TOML encoder that encodes Go values to the io.Writer -// given. By default, a single indentation level is 2 spaces. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - w: bufio.NewWriter(w), - Indent: " ", - } -} - -// Encode writes a TOML representation of the Go value to the underlying -// io.Writer. If the value given cannot be encoded to a valid TOML document, -// then an error is returned. -// -// The mapping between Go values and TOML values should be precisely the same -// as for the Decode* functions. Similarly, the TextMarshaler interface is -// supported by encoding the resulting bytes as strings. (If you want to write -// arbitrary binary data then you will need to use something like base64 since -// TOML does not have any binary types.) -// -// When encoding TOML hashes (i.e., Go maps or structs), keys without any -// sub-hashes are encoded first. -// -// If a Go map is encoded, then its keys are sorted alphabetically for -// deterministic output. More control over this behavior may be provided if -// there is demand for it. -// -// Encoding Go values without a corresponding TOML representation---like map -// types with non-string keys---will cause an error to be returned. Similarly -// for mixed arrays/slices, arrays/slices with nil elements, embedded -// non-struct types and nested slices containing maps or structs. -// (e.g., [][]map[string]string is not allowed but []map[string]string is OK -// and so is []map[string][]string.) -func (enc *Encoder) Encode(v interface{}) error { - rv := eindirect(reflect.ValueOf(v)) - if err := enc.safeEncode(Key([]string{}), rv); err != nil { - return err - } - return enc.w.Flush() -} - -func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { - defer func() { - if r := recover(); r != nil { - if terr, ok := r.(tomlEncodeError); ok { - err = terr.error - return - } - panic(r) - } - }() - enc.encode(key, rv) - return nil -} - -func (enc *Encoder) encode(key Key, rv reflect.Value) { - // Special case. Time needs to be in ISO8601 format. - // Special case. If we can marshal the type to text, then we used that. - // Basically, this prevents the encoder for handling these types as - // generic structs (or whatever the underlying type of a TextMarshaler is). - switch rv.Interface().(type) { - case time.Time, TextMarshaler: - enc.keyEqElement(key, rv) - return - } - - k := rv.Kind() - switch k { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64, - reflect.Float32, reflect.Float64, reflect.String, reflect.Bool: - enc.keyEqElement(key, rv) - case reflect.Array, reflect.Slice: - if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) { - enc.eArrayOfTables(key, rv) - } else { - enc.keyEqElement(key, rv) - } - case reflect.Interface: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Map: - if rv.IsNil() { - return - } - enc.eTable(key, rv) - case reflect.Ptr: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Struct: - enc.eTable(key, rv) - default: - panic(e("unsupported type for key '%s': %s", key, k)) - } -} - -// eElement encodes any value that can be an array element (primitives and -// arrays). -func (enc *Encoder) eElement(rv reflect.Value) { - switch v := rv.Interface().(type) { - case time.Time: - // Special case time.Time as a primitive. Has to come before - // TextMarshaler below because time.Time implements - // encoding.TextMarshaler, but we need to always use UTC. - enc.wf(v.UTC().Format("2006-01-02T15:04:05Z")) - return - case TextMarshaler: - // Special case. Use text marshaler if it's available for this value. - if s, err := v.MarshalText(); err != nil { - encPanic(err) - } else { - enc.writeQuoted(string(s)) - } - return - } - switch rv.Kind() { - case reflect.Bool: - enc.wf(strconv.FormatBool(rv.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64: - enc.wf(strconv.FormatInt(rv.Int(), 10)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, - reflect.Uint32, reflect.Uint64: - enc.wf(strconv.FormatUint(rv.Uint(), 10)) - case reflect.Float32: - enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 32))) - case reflect.Float64: - enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 64))) - case reflect.Array, reflect.Slice: - enc.eArrayOrSliceElement(rv) - case reflect.Interface: - enc.eElement(rv.Elem()) - case reflect.String: - enc.writeQuoted(rv.String()) - default: - panic(e("unexpected primitive type: %s", rv.Kind())) - } -} - -// By the TOML spec, all floats must have a decimal with at least one -// number on either side. -func floatAddDecimal(fstr string) string { - if !strings.Contains(fstr, ".") { - return fstr + ".0" - } - return fstr -} - -func (enc *Encoder) writeQuoted(s string) { - enc.wf("\"%s\"", quotedReplacer.Replace(s)) -} - -func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { - length := rv.Len() - enc.wf("[") - for i := 0; i < length; i++ { - elem := rv.Index(i) - enc.eElement(elem) - if i != length-1 { - enc.wf(", ") - } - } - enc.wf("]") -} - -func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - for i := 0; i < rv.Len(); i++ { - trv := rv.Index(i) - if isNil(trv) { - continue - } - panicIfInvalidKey(key) - enc.newline() - enc.wf("%s[[%s]]", enc.indentStr(key), key.maybeQuotedAll()) - enc.newline() - enc.eMapOrStruct(key, trv) - } -} - -func (enc *Encoder) eTable(key Key, rv reflect.Value) { - panicIfInvalidKey(key) - if len(key) == 1 { - // Output an extra newline between top-level tables. - // (The newline isn't written if nothing else has been written though.) - enc.newline() - } - if len(key) > 0 { - enc.wf("%s[%s]", enc.indentStr(key), key.maybeQuotedAll()) - enc.newline() - } - enc.eMapOrStruct(key, rv) -} - -func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value) { - switch rv := eindirect(rv); rv.Kind() { - case reflect.Map: - enc.eMap(key, rv) - case reflect.Struct: - enc.eStruct(key, rv) - default: - panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String()) - } -} - -func (enc *Encoder) eMap(key Key, rv reflect.Value) { - rt := rv.Type() - if rt.Key().Kind() != reflect.String { - encPanic(errNonString) - } - - // Sort keys so that we have deterministic output. And write keys directly - // underneath this key first, before writing sub-structs or sub-maps. - var mapKeysDirect, mapKeysSub []string - for _, mapKey := range rv.MapKeys() { - k := mapKey.String() - if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) { - mapKeysSub = append(mapKeysSub, k) - } else { - mapKeysDirect = append(mapKeysDirect, k) - } - } - - var writeMapKeys = func(mapKeys []string) { - sort.Strings(mapKeys) - for _, mapKey := range mapKeys { - mrv := rv.MapIndex(reflect.ValueOf(mapKey)) - if isNil(mrv) { - // Don't write anything for nil fields. - continue - } - enc.encode(key.add(mapKey), mrv) - } - } - writeMapKeys(mapKeysDirect) - writeMapKeys(mapKeysSub) -} - -func (enc *Encoder) eStruct(key Key, rv reflect.Value) { - // Write keys for fields directly under this key first, because if we write - // a field that creates a new table, then all keys under it will be in that - // table (not the one we're writing here). - rt := rv.Type() - var fieldsDirect, fieldsSub [][]int - var addFields func(rt reflect.Type, rv reflect.Value, start []int) - addFields = func(rt reflect.Type, rv reflect.Value, start []int) { - for i := 0; i < rt.NumField(); i++ { - f := rt.Field(i) - // skip unexported fields - if f.PkgPath != "" && !f.Anonymous { - continue - } - frv := rv.Field(i) - if f.Anonymous { - t := f.Type - switch t.Kind() { - case reflect.Struct: - // Treat anonymous struct fields with - // tag names as though they are not - // anonymous, like encoding/json does. - if getOptions(f.Tag).name == "" { - addFields(t, frv, f.Index) - continue - } - case reflect.Ptr: - if t.Elem().Kind() == reflect.Struct && - getOptions(f.Tag).name == "" { - if !frv.IsNil() { - addFields(t.Elem(), frv.Elem(), f.Index) - } - continue - } - // Fall through to the normal field encoding logic below - // for non-struct anonymous fields. - } - } - - if typeIsHash(tomlTypeOfGo(frv)) { - fieldsSub = append(fieldsSub, append(start, f.Index...)) - } else { - fieldsDirect = append(fieldsDirect, append(start, f.Index...)) - } - } - } - addFields(rt, rv, nil) - - var writeFields = func(fields [][]int) { - for _, fieldIndex := range fields { - sft := rt.FieldByIndex(fieldIndex) - sf := rv.FieldByIndex(fieldIndex) - if isNil(sf) { - // Don't write anything for nil fields. - continue - } - - opts := getOptions(sft.Tag) - if opts.skip { - continue - } - keyName := sft.Name - if opts.name != "" { - keyName = opts.name - } - if opts.omitempty && isEmpty(sf) { - continue - } - if opts.omitzero && isZero(sf) { - continue - } - - enc.encode(key.add(keyName), sf) - } - } - writeFields(fieldsDirect) - writeFields(fieldsSub) -} - -// tomlTypeName returns the TOML type name of the Go value's type. It is -// used to determine whether the types of array elements are mixed (which is -// forbidden). If the Go value is nil, then it is illegal for it to be an array -// element, and valueIsNil is returned as true. - -// Returns the TOML type of a Go value. The type may be `nil`, which means -// no concrete TOML type could be found. -func tomlTypeOfGo(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() { - return nil - } - switch rv.Kind() { - case reflect.Bool: - return tomlBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64: - return tomlInteger - case reflect.Float32, reflect.Float64: - return tomlFloat - case reflect.Array, reflect.Slice: - if typeEqual(tomlHash, tomlArrayType(rv)) { - return tomlArrayHash - } - return tomlArray - case reflect.Ptr, reflect.Interface: - return tomlTypeOfGo(rv.Elem()) - case reflect.String: - return tomlString - case reflect.Map: - return tomlHash - case reflect.Struct: - switch rv.Interface().(type) { - case time.Time: - return tomlDatetime - case TextMarshaler: - return tomlString - default: - return tomlHash - } - default: - panic("unexpected reflect.Kind: " + rv.Kind().String()) - } -} - -// tomlArrayType returns the element type of a TOML array. The type returned -// may be nil if it cannot be determined (e.g., a nil slice or a zero length -// slize). This function may also panic if it finds a type that cannot be -// expressed in TOML (such as nil elements, heterogeneous arrays or directly -// nested arrays of tables). -func tomlArrayType(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() || rv.Len() == 0 { - return nil - } - firstType := tomlTypeOfGo(rv.Index(0)) - if firstType == nil { - encPanic(errArrayNilElement) - } - - rvlen := rv.Len() - for i := 1; i < rvlen; i++ { - elem := rv.Index(i) - switch elemType := tomlTypeOfGo(elem); { - case elemType == nil: - encPanic(errArrayNilElement) - case !typeEqual(firstType, elemType): - encPanic(errArrayMixedElementTypes) - } - } - // If we have a nested array, then we must make sure that the nested - // array contains ONLY primitives. - // This checks arbitrarily nested arrays. - if typeEqual(firstType, tomlArray) || typeEqual(firstType, tomlArrayHash) { - nest := tomlArrayType(eindirect(rv.Index(0))) - if typeEqual(nest, tomlHash) || typeEqual(nest, tomlArrayHash) { - encPanic(errArrayNoTable) - } - } - return firstType -} - -type tagOptions struct { - skip bool // "-" - name string - omitempty bool - omitzero bool -} - -func getOptions(tag reflect.StructTag) tagOptions { - t := tag.Get("toml") - if t == "-" { - return tagOptions{skip: true} - } - var opts tagOptions - parts := strings.Split(t, ",") - opts.name = parts[0] - for _, s := range parts[1:] { - switch s { - case "omitempty": - opts.omitempty = true - case "omitzero": - opts.omitzero = true - } - } - return opts -} - -func isZero(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return rv.Uint() == 0 - case reflect.Float32, reflect.Float64: - return rv.Float() == 0.0 - } - return false -} - -func isEmpty(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Array, reflect.Slice, reflect.Map, reflect.String: - return rv.Len() == 0 - case reflect.Bool: - return !rv.Bool() - } - return false -} - -func (enc *Encoder) newline() { - if enc.hasWritten { - enc.wf("\n") - } -} - -func (enc *Encoder) keyEqElement(key Key, val reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - panicIfInvalidKey(key) - enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) - enc.eElement(val) - enc.newline() -} - -func (enc *Encoder) wf(format string, v ...interface{}) { - if _, err := fmt.Fprintf(enc.w, format, v...); err != nil { - encPanic(err) - } - enc.hasWritten = true -} - -func (enc *Encoder) indentStr(key Key) string { - return strings.Repeat(enc.Indent, len(key)-1) -} - -func encPanic(err error) { - panic(tomlEncodeError{err}) -} - -func eindirect(v reflect.Value) reflect.Value { - switch v.Kind() { - case reflect.Ptr, reflect.Interface: - return eindirect(v.Elem()) - default: - return v - } -} - -func isNil(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return rv.IsNil() - default: - return false - } -} - -func panicIfInvalidKey(key Key) { - for _, k := range key { - if len(k) == 0 { - encPanic(e("Key '%s' is not a valid table name. Key names "+ - "cannot be empty.", key.maybeQuotedAll())) - } - } -} - -func isValidKeyName(s string) bool { - return len(s) != 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encoding_types.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encoding_types.go deleted file mode 100644 index d36e1dd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encoding_types.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build go1.2 - -package toml - -// In order to support Go 1.1, we define our own TextMarshaler and -// TextUnmarshaler types. For Go 1.2+, we just alias them with the -// standard library interfaces. - -import ( - "encoding" -) - -// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here -// so that Go 1.1 can be supported. -type TextMarshaler encoding.TextMarshaler - -// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined -// here so that Go 1.1 can be supported. -type TextUnmarshaler encoding.TextUnmarshaler diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go deleted file mode 100644 index e8d503d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build !go1.2 - -package toml - -// These interfaces were introduced in Go 1.2, so we add them manually when -// compiling for Go 1.1. - -// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here -// so that Go 1.1 can be supported. -type TextMarshaler interface { - MarshalText() (text []byte, err error) -} - -// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined -// here so that Go 1.1 can be supported. -type TextUnmarshaler interface { - UnmarshalText(text []byte) error -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/lex.go deleted file mode 100644 index e0a742a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/lex.go +++ /dev/null @@ -1,953 +0,0 @@ -package toml - -import ( - "fmt" - "strings" - "unicode" - "unicode/utf8" -) - -type itemType int - -const ( - itemError itemType = iota - itemNIL // used in the parser to indicate no type - itemEOF - itemText - itemString - itemRawString - itemMultilineString - itemRawMultilineString - itemBool - itemInteger - itemFloat - itemDatetime - itemArray // the start of an array - itemArrayEnd - itemTableStart - itemTableEnd - itemArrayTableStart - itemArrayTableEnd - itemKeyStart - itemCommentStart - itemInlineTableStart - itemInlineTableEnd -) - -const ( - eof = 0 - comma = ',' - tableStart = '[' - tableEnd = ']' - arrayTableStart = '[' - arrayTableEnd = ']' - tableSep = '.' - keySep = '=' - arrayStart = '[' - arrayEnd = ']' - commentStart = '#' - stringStart = '"' - stringEnd = '"' - rawStringStart = '\'' - rawStringEnd = '\'' - inlineTableStart = '{' - inlineTableEnd = '}' -) - -type stateFn func(lx *lexer) stateFn - -type lexer struct { - input string - start int - pos int - line int - state stateFn - items chan item - - // Allow for backing up up to three runes. - // This is necessary because TOML contains 3-rune tokens (""" and '''). - prevWidths [3]int - nprev int // how many of prevWidths are in use - // If we emit an eof, we can still back up, but it is not OK to call - // next again. - atEOF bool - - // A stack of state functions used to maintain context. - // The idea is to reuse parts of the state machine in various places. - // For example, values can appear at the top level or within arbitrarily - // nested arrays. The last state on the stack is used after a value has - // been lexed. Similarly for comments. - stack []stateFn -} - -type item struct { - typ itemType - val string - line int -} - -func (lx *lexer) nextItem() item { - for { - select { - case item := <-lx.items: - return item - default: - lx.state = lx.state(lx) - } - } -} - -func lex(input string) *lexer { - lx := &lexer{ - input: input, - state: lexTop, - line: 1, - items: make(chan item, 10), - stack: make([]stateFn, 0, 10), - } - return lx -} - -func (lx *lexer) push(state stateFn) { - lx.stack = append(lx.stack, state) -} - -func (lx *lexer) pop() stateFn { - if len(lx.stack) == 0 { - return lx.errorf("BUG in lexer: no states to pop") - } - last := lx.stack[len(lx.stack)-1] - lx.stack = lx.stack[0 : len(lx.stack)-1] - return last -} - -func (lx *lexer) current() string { - return lx.input[lx.start:lx.pos] -} - -func (lx *lexer) emit(typ itemType) { - lx.items <- item{typ, lx.current(), lx.line} - lx.start = lx.pos -} - -func (lx *lexer) emitTrim(typ itemType) { - lx.items <- item{typ, strings.TrimSpace(lx.current()), lx.line} - lx.start = lx.pos -} - -func (lx *lexer) next() (r rune) { - if lx.atEOF { - panic("next called after EOF") - } - if lx.pos >= len(lx.input) { - lx.atEOF = true - return eof - } - - if lx.input[lx.pos] == '\n' { - lx.line++ - } - lx.prevWidths[2] = lx.prevWidths[1] - lx.prevWidths[1] = lx.prevWidths[0] - if lx.nprev < 3 { - lx.nprev++ - } - r, w := utf8.DecodeRuneInString(lx.input[lx.pos:]) - lx.prevWidths[0] = w - lx.pos += w - return r -} - -// ignore skips over the pending input before this point. -func (lx *lexer) ignore() { - lx.start = lx.pos -} - -// backup steps back one rune. Can be called only twice between calls to next. -func (lx *lexer) backup() { - if lx.atEOF { - lx.atEOF = false - return - } - if lx.nprev < 1 { - panic("backed up too far") - } - w := lx.prevWidths[0] - lx.prevWidths[0] = lx.prevWidths[1] - lx.prevWidths[1] = lx.prevWidths[2] - lx.nprev-- - lx.pos -= w - if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { - lx.line-- - } -} - -// accept consumes the next rune if it's equal to `valid`. -func (lx *lexer) accept(valid rune) bool { - if lx.next() == valid { - return true - } - lx.backup() - return false -} - -// peek returns but does not consume the next rune in the input. -func (lx *lexer) peek() rune { - r := lx.next() - lx.backup() - return r -} - -// skip ignores all input that matches the given predicate. -func (lx *lexer) skip(pred func(rune) bool) { - for { - r := lx.next() - if pred(r) { - continue - } - lx.backup() - lx.ignore() - return - } -} - -// errorf stops all lexing by emitting an error and returning `nil`. -// Note that any value that is a character is escaped if it's a special -// character (newlines, tabs, etc.). -func (lx *lexer) errorf(format string, values ...interface{}) stateFn { - lx.items <- item{ - itemError, - fmt.Sprintf(format, values...), - lx.line, - } - return nil -} - -// lexTop consumes elements at the top level of TOML data. -func lexTop(lx *lexer) stateFn { - r := lx.next() - if isWhitespace(r) || isNL(r) { - return lexSkip(lx, lexTop) - } - switch r { - case commentStart: - lx.push(lexTop) - return lexCommentStart - case tableStart: - return lexTableStart - case eof: - if lx.pos > lx.start { - return lx.errorf("unexpected EOF") - } - lx.emit(itemEOF) - return nil - } - - // At this point, the only valid item can be a key, so we back up - // and let the key lexer do the rest. - lx.backup() - lx.push(lexTopEnd) - return lexKeyStart -} - -// lexTopEnd is entered whenever a top-level item has been consumed. (A value -// or a table.) It must see only whitespace, and will turn back to lexTop -// upon a newline. If it sees EOF, it will quit the lexer successfully. -func lexTopEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case r == commentStart: - // a comment will read to a newline for us. - lx.push(lexTop) - return lexCommentStart - case isWhitespace(r): - return lexTopEnd - case isNL(r): - lx.ignore() - return lexTop - case r == eof: - lx.emit(itemEOF) - return nil - } - return lx.errorf("expected a top-level item to end with a newline, "+ - "comment, or EOF, but got %q instead", r) -} - -// lexTable lexes the beginning of a table. Namely, it makes sure that -// it starts with a character other than '.' and ']'. -// It assumes that '[' has already been consumed. -// It also handles the case that this is an item in an array of tables. -// e.g., '[[name]]'. -func lexTableStart(lx *lexer) stateFn { - if lx.peek() == arrayTableStart { - lx.next() - lx.emit(itemArrayTableStart) - lx.push(lexArrayTableEnd) - } else { - lx.emit(itemTableStart) - lx.push(lexTableEnd) - } - return lexTableNameStart -} - -func lexTableEnd(lx *lexer) stateFn { - lx.emit(itemTableEnd) - return lexTopEnd -} - -func lexArrayTableEnd(lx *lexer) stateFn { - if r := lx.next(); r != arrayTableEnd { - return lx.errorf("expected end of table array name delimiter %q, "+ - "but got %q instead", arrayTableEnd, r) - } - lx.emit(itemArrayTableEnd) - return lexTopEnd -} - -func lexTableNameStart(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.peek(); { - case r == tableEnd || r == eof: - return lx.errorf("unexpected end of table name " + - "(table names cannot be empty)") - case r == tableSep: - return lx.errorf("unexpected table separator " + - "(table names cannot be empty)") - case r == stringStart || r == rawStringStart: - lx.ignore() - lx.push(lexTableNameEnd) - return lexValue // reuse string lexing - default: - return lexBareTableName - } -} - -// lexBareTableName lexes the name of a table. It assumes that at least one -// valid character for the table has already been read. -func lexBareTableName(lx *lexer) stateFn { - r := lx.next() - if isBareKeyChar(r) { - return lexBareTableName - } - lx.backup() - lx.emit(itemText) - return lexTableNameEnd -} - -// lexTableNameEnd reads the end of a piece of a table name, optionally -// consuming whitespace. -func lexTableNameEnd(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.next(); { - case isWhitespace(r): - return lexTableNameEnd - case r == tableSep: - lx.ignore() - return lexTableNameStart - case r == tableEnd: - return lx.pop() - default: - return lx.errorf("expected '.' or ']' to end table name, "+ - "but got %q instead", r) - } -} - -// lexKeyStart consumes a key name up until the first non-whitespace character. -// lexKeyStart will ignore whitespace. -func lexKeyStart(lx *lexer) stateFn { - r := lx.peek() - switch { - case r == keySep: - return lx.errorf("unexpected key separator %q", keySep) - case isWhitespace(r) || isNL(r): - lx.next() - return lexSkip(lx, lexKeyStart) - case r == stringStart || r == rawStringStart: - lx.ignore() - lx.emit(itemKeyStart) - lx.push(lexKeyEnd) - return lexValue // reuse string lexing - default: - lx.ignore() - lx.emit(itemKeyStart) - return lexBareKey - } -} - -// lexBareKey consumes the text of a bare key. Assumes that the first character -// (which is not whitespace) has not yet been consumed. -func lexBareKey(lx *lexer) stateFn { - switch r := lx.next(); { - case isBareKeyChar(r): - return lexBareKey - case isWhitespace(r): - lx.backup() - lx.emit(itemText) - return lexKeyEnd - case r == keySep: - lx.backup() - lx.emit(itemText) - return lexKeyEnd - default: - return lx.errorf("bare keys cannot contain %q", r) - } -} - -// lexKeyEnd consumes the end of a key and trims whitespace (up to the key -// separator). -func lexKeyEnd(lx *lexer) stateFn { - switch r := lx.next(); { - case r == keySep: - return lexSkip(lx, lexValue) - case isWhitespace(r): - return lexSkip(lx, lexKeyEnd) - default: - return lx.errorf("expected key separator %q, but got %q instead", - keySep, r) - } -} - -// lexValue starts the consumption of a value anywhere a value is expected. -// lexValue will ignore whitespace. -// After a value is lexed, the last state on the next is popped and returned. -func lexValue(lx *lexer) stateFn { - // We allow whitespace to precede a value, but NOT newlines. - // In array syntax, the array states are responsible for ignoring newlines. - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexValue) - case isDigit(r): - lx.backup() // avoid an extra state and use the same as above - return lexNumberOrDateStart - } - switch r { - case arrayStart: - lx.ignore() - lx.emit(itemArray) - return lexArrayValue - case inlineTableStart: - lx.ignore() - lx.emit(itemInlineTableStart) - return lexInlineTableValue - case stringStart: - if lx.accept(stringStart) { - if lx.accept(stringStart) { - lx.ignore() // Ignore """ - return lexMultilineString - } - lx.backup() - } - lx.ignore() // ignore the '"' - return lexString - case rawStringStart: - if lx.accept(rawStringStart) { - if lx.accept(rawStringStart) { - lx.ignore() // Ignore """ - return lexMultilineRawString - } - lx.backup() - } - lx.ignore() // ignore the "'" - return lexRawString - case '+', '-': - return lexNumberStart - case '.': // special error case, be kind to users - return lx.errorf("floats must start with a digit, not '.'") - } - if unicode.IsLetter(r) { - // Be permissive here; lexBool will give a nice error if the - // user wrote something like - // x = foo - // (i.e. not 'true' or 'false' but is something else word-like.) - lx.backup() - return lexBool - } - return lx.errorf("expected value but found %q instead", r) -} - -// lexArrayValue consumes one value in an array. It assumes that '[' or ',' -// have already been consumed. All whitespace and newlines are ignored. -func lexArrayValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValue) - case r == commentStart: - lx.push(lexArrayValue) - return lexCommentStart - case r == comma: - return lx.errorf("unexpected comma") - case r == arrayEnd: - // NOTE(caleb): The spec isn't clear about whether you can have - // a trailing comma or not, so we'll allow it. - return lexArrayEnd - } - - lx.backup() - lx.push(lexArrayValueEnd) - return lexValue -} - -// lexArrayValueEnd consumes everything between the end of an array value and -// the next value (or the end of the array): it ignores whitespace and newlines -// and expects either a ',' or a ']'. -func lexArrayValueEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValueEnd) - case r == commentStart: - lx.push(lexArrayValueEnd) - return lexCommentStart - case r == comma: - lx.ignore() - return lexArrayValue // move on to the next value - case r == arrayEnd: - return lexArrayEnd - } - return lx.errorf( - "expected a comma or array terminator %q, but got %q instead", - arrayEnd, r, - ) -} - -// lexArrayEnd finishes the lexing of an array. -// It assumes that a ']' has just been consumed. -func lexArrayEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemArrayEnd) - return lx.pop() -} - -// lexInlineTableValue consumes one key/value pair in an inline table. -// It assumes that '{' or ',' have already been consumed. Whitespace is ignored. -func lexInlineTableValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexInlineTableValue) - case isNL(r): - return lx.errorf("newlines not allowed within inline tables") - case r == commentStart: - lx.push(lexInlineTableValue) - return lexCommentStart - case r == comma: - return lx.errorf("unexpected comma") - case r == inlineTableEnd: - return lexInlineTableEnd - } - lx.backup() - lx.push(lexInlineTableValueEnd) - return lexKeyStart -} - -// lexInlineTableValueEnd consumes everything between the end of an inline table -// key/value pair and the next pair (or the end of the table): -// it ignores whitespace and expects either a ',' or a '}'. -func lexInlineTableValueEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexInlineTableValueEnd) - case isNL(r): - return lx.errorf("newlines not allowed within inline tables") - case r == commentStart: - lx.push(lexInlineTableValueEnd) - return lexCommentStart - case r == comma: - lx.ignore() - return lexInlineTableValue - case r == inlineTableEnd: - return lexInlineTableEnd - } - return lx.errorf("expected a comma or an inline table terminator %q, "+ - "but got %q instead", inlineTableEnd, r) -} - -// lexInlineTableEnd finishes the lexing of an inline table. -// It assumes that a '}' has just been consumed. -func lexInlineTableEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemInlineTableEnd) - return lx.pop() -} - -// lexString consumes the inner contents of a string. It assumes that the -// beginning '"' has already been consumed and ignored. -func lexString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == eof: - return lx.errorf("unexpected EOF") - case isNL(r): - return lx.errorf("strings cannot contain newlines") - case r == '\\': - lx.push(lexString) - return lexStringEscape - case r == stringEnd: - lx.backup() - lx.emit(itemString) - lx.next() - lx.ignore() - return lx.pop() - } - return lexString -} - -// lexMultilineString consumes the inner contents of a string. It assumes that -// the beginning '"""' has already been consumed and ignored. -func lexMultilineString(lx *lexer) stateFn { - switch lx.next() { - case eof: - return lx.errorf("unexpected EOF") - case '\\': - return lexMultilineStringEscape - case stringEnd: - if lx.accept(stringEnd) { - if lx.accept(stringEnd) { - lx.backup() - lx.backup() - lx.backup() - lx.emit(itemMultilineString) - lx.next() - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - } - return lexMultilineString -} - -// lexRawString consumes a raw string. Nothing can be escaped in such a string. -// It assumes that the beginning "'" has already been consumed and ignored. -func lexRawString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == eof: - return lx.errorf("unexpected EOF") - case isNL(r): - return lx.errorf("strings cannot contain newlines") - case r == rawStringEnd: - lx.backup() - lx.emit(itemRawString) - lx.next() - lx.ignore() - return lx.pop() - } - return lexRawString -} - -// lexMultilineRawString consumes a raw string. Nothing can be escaped in such -// a string. It assumes that the beginning "'''" has already been consumed and -// ignored. -func lexMultilineRawString(lx *lexer) stateFn { - switch lx.next() { - case eof: - return lx.errorf("unexpected EOF") - case rawStringEnd: - if lx.accept(rawStringEnd) { - if lx.accept(rawStringEnd) { - lx.backup() - lx.backup() - lx.backup() - lx.emit(itemRawMultilineString) - lx.next() - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - } - return lexMultilineRawString -} - -// lexMultilineStringEscape consumes an escaped character. It assumes that the -// preceding '\\' has already been consumed. -func lexMultilineStringEscape(lx *lexer) stateFn { - // Handle the special case first: - if isNL(lx.next()) { - return lexMultilineString - } - lx.backup() - lx.push(lexMultilineString) - return lexStringEscape(lx) -} - -func lexStringEscape(lx *lexer) stateFn { - r := lx.next() - switch r { - case 'b': - fallthrough - case 't': - fallthrough - case 'n': - fallthrough - case 'f': - fallthrough - case 'r': - fallthrough - case '"': - fallthrough - case '\\': - return lx.pop() - case 'u': - return lexShortUnicodeEscape - case 'U': - return lexLongUnicodeEscape - } - return lx.errorf("invalid escape character %q; only the following "+ - "escape characters are allowed: "+ - `\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX`, r) -} - -func lexShortUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 4; i++ { - r = lx.next() - if !isHexadecimal(r) { - return lx.errorf(`expected four hexadecimal digits after '\u', `+ - "but got %q instead", lx.current()) - } - } - return lx.pop() -} - -func lexLongUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 8; i++ { - r = lx.next() - if !isHexadecimal(r) { - return lx.errorf(`expected eight hexadecimal digits after '\U', `+ - "but got %q instead", lx.current()) - } - } - return lx.pop() -} - -// lexNumberOrDateStart consumes either an integer, a float, or datetime. -func lexNumberOrDateStart(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumberOrDate - } - switch r { - case '_': - return lexNumber - case 'e', 'E': - return lexFloat - case '.': - return lx.errorf("floats must start with a digit, not '.'") - } - return lx.errorf("expected a digit but got %q", r) -} - -// lexNumberOrDate consumes either an integer, float or datetime. -func lexNumberOrDate(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumberOrDate - } - switch r { - case '-': - return lexDatetime - case '_': - return lexNumber - case '.', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexDatetime consumes a Datetime, to a first approximation. -// The parser validates that it matches one of the accepted formats. -func lexDatetime(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexDatetime - } - switch r { - case '-', 'T', ':', '.', 'Z', '+': - return lexDatetime - } - - lx.backup() - lx.emit(itemDatetime) - return lx.pop() -} - -// lexNumberStart consumes either an integer or a float. It assumes that a sign -// has already been read, but that *no* digits have been consumed. -// lexNumberStart will move to the appropriate integer or float states. -func lexNumberStart(lx *lexer) stateFn { - // We MUST see a digit. Even floats have to start with a digit. - r := lx.next() - if !isDigit(r) { - if r == '.' { - return lx.errorf("floats must start with a digit, not '.'") - } - return lx.errorf("expected a digit but got %q", r) - } - return lexNumber -} - -// lexNumber consumes an integer or a float after seeing the first digit. -func lexNumber(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumber - } - switch r { - case '_': - return lexNumber - case '.', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexFloat consumes the elements of a float. It allows any sequence of -// float-like characters, so floats emitted by the lexer are only a first -// approximation and must be validated by the parser. -func lexFloat(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexFloat - } - switch r { - case '_', '.', '-', '+', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemFloat) - return lx.pop() -} - -// lexBool consumes a bool string: 'true' or 'false. -func lexBool(lx *lexer) stateFn { - var rs []rune - for { - r := lx.next() - if !unicode.IsLetter(r) { - lx.backup() - break - } - rs = append(rs, r) - } - s := string(rs) - switch s { - case "true", "false": - lx.emit(itemBool) - return lx.pop() - } - return lx.errorf("expected value but found %q instead", s) -} - -// lexCommentStart begins the lexing of a comment. It will emit -// itemCommentStart and consume no characters, passing control to lexComment. -func lexCommentStart(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemCommentStart) - return lexComment -} - -// lexComment lexes an entire comment. It assumes that '#' has been consumed. -// It will consume *up to* the first newline character, and pass control -// back to the last state on the stack. -func lexComment(lx *lexer) stateFn { - r := lx.peek() - if isNL(r) || r == eof { - lx.emit(itemText) - return lx.pop() - } - lx.next() - return lexComment -} - -// lexSkip ignores all slurped input and moves on to the next state. -func lexSkip(lx *lexer, nextState stateFn) stateFn { - return func(lx *lexer) stateFn { - lx.ignore() - return nextState - } -} - -// isWhitespace returns true if `r` is a whitespace character according -// to the spec. -func isWhitespace(r rune) bool { - return r == '\t' || r == ' ' -} - -func isNL(r rune) bool { - return r == '\n' || r == '\r' -} - -func isDigit(r rune) bool { - return r >= '0' && r <= '9' -} - -func isHexadecimal(r rune) bool { - return (r >= '0' && r <= '9') || - (r >= 'a' && r <= 'f') || - (r >= 'A' && r <= 'F') -} - -func isBareKeyChar(r rune) bool { - return (r >= 'A' && r <= 'Z') || - (r >= 'a' && r <= 'z') || - (r >= '0' && r <= '9') || - r == '_' || - r == '-' -} - -func (itype itemType) String() string { - switch itype { - case itemError: - return "Error" - case itemNIL: - return "NIL" - case itemEOF: - return "EOF" - case itemText: - return "Text" - case itemString, itemRawString, itemMultilineString, itemRawMultilineString: - return "String" - case itemBool: - return "Bool" - case itemInteger: - return "Integer" - case itemFloat: - return "Float" - case itemDatetime: - return "DateTime" - case itemTableStart: - return "TableStart" - case itemTableEnd: - return "TableEnd" - case itemKeyStart: - return "KeyStart" - case itemArray: - return "Array" - case itemArrayEnd: - return "ArrayEnd" - case itemCommentStart: - return "CommentStart" - } - panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype))) -} - -func (item item) String() string { - return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/parse.go deleted file mode 100644 index 50869ef..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/parse.go +++ /dev/null @@ -1,592 +0,0 @@ -package toml - -import ( - "fmt" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" -) - -type parser struct { - mapping map[string]interface{} - types map[string]tomlType - lx *lexer - - // A list of keys in the order that they appear in the TOML data. - ordered []Key - - // the full key for the current hash in scope - context Key - - // the base key name for everything except hashes - currentKey string - - // rough approximation of line number - approxLine int - - // A map of 'key.group.names' to whether they were created implicitly. - implicits map[string]bool -} - -type parseError string - -func (pe parseError) Error() string { - return string(pe) -} - -func parse(data string) (p *parser, err error) { - defer func() { - if r := recover(); r != nil { - var ok bool - if err, ok = r.(parseError); ok { - return - } - panic(r) - } - }() - - p = &parser{ - mapping: make(map[string]interface{}), - types: make(map[string]tomlType), - lx: lex(data), - ordered: make([]Key, 0), - implicits: make(map[string]bool), - } - for { - item := p.next() - if item.typ == itemEOF { - break - } - p.topLevel(item) - } - - return p, nil -} - -func (p *parser) panicf(format string, v ...interface{}) { - msg := fmt.Sprintf("Near line %d (last key parsed '%s'): %s", - p.approxLine, p.current(), fmt.Sprintf(format, v...)) - panic(parseError(msg)) -} - -func (p *parser) next() item { - it := p.lx.nextItem() - if it.typ == itemError { - p.panicf("%s", it.val) - } - return it -} - -func (p *parser) bug(format string, v ...interface{}) { - panic(fmt.Sprintf("BUG: "+format+"\n\n", v...)) -} - -func (p *parser) expect(typ itemType) item { - it := p.next() - p.assertEqual(typ, it.typ) - return it -} - -func (p *parser) assertEqual(expected, got itemType) { - if expected != got { - p.bug("Expected '%s' but got '%s'.", expected, got) - } -} - -func (p *parser) topLevel(item item) { - switch item.typ { - case itemCommentStart: - p.approxLine = item.line - p.expect(itemText) - case itemTableStart: - kg := p.next() - p.approxLine = kg.line - - var key Key - for ; kg.typ != itemTableEnd && kg.typ != itemEOF; kg = p.next() { - key = append(key, p.keyString(kg)) - } - p.assertEqual(itemTableEnd, kg.typ) - - p.establishContext(key, false) - p.setType("", tomlHash) - p.ordered = append(p.ordered, key) - case itemArrayTableStart: - kg := p.next() - p.approxLine = kg.line - - var key Key - for ; kg.typ != itemArrayTableEnd && kg.typ != itemEOF; kg = p.next() { - key = append(key, p.keyString(kg)) - } - p.assertEqual(itemArrayTableEnd, kg.typ) - - p.establishContext(key, true) - p.setType("", tomlArrayHash) - p.ordered = append(p.ordered, key) - case itemKeyStart: - kname := p.next() - p.approxLine = kname.line - p.currentKey = p.keyString(kname) - - val, typ := p.value(p.next()) - p.setValue(p.currentKey, val) - p.setType(p.currentKey, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - p.currentKey = "" - default: - p.bug("Unexpected type at top level: %s", item.typ) - } -} - -// Gets a string for a key (or part of a key in a table name). -func (p *parser) keyString(it item) string { - switch it.typ { - case itemText: - return it.val - case itemString, itemMultilineString, - itemRawString, itemRawMultilineString: - s, _ := p.value(it) - return s.(string) - default: - p.bug("Unexpected key type: %s", it.typ) - panic("unreachable") - } -} - -// value translates an expected value from the lexer into a Go value wrapped -// as an empty interface. -func (p *parser) value(it item) (interface{}, tomlType) { - switch it.typ { - case itemString: - return p.replaceEscapes(it.val), p.typeOfPrimitive(it) - case itemMultilineString: - trimmed := stripFirstNewline(stripEscapedWhitespace(it.val)) - return p.replaceEscapes(trimmed), p.typeOfPrimitive(it) - case itemRawString: - return it.val, p.typeOfPrimitive(it) - case itemRawMultilineString: - return stripFirstNewline(it.val), p.typeOfPrimitive(it) - case itemBool: - switch it.val { - case "true": - return true, p.typeOfPrimitive(it) - case "false": - return false, p.typeOfPrimitive(it) - } - p.bug("Expected boolean value, but got '%s'.", it.val) - case itemInteger: - if !numUnderscoresOK(it.val) { - p.panicf("Invalid integer %q: underscores must be surrounded by digits", - it.val) - } - val := strings.Replace(it.val, "_", "", -1) - num, err := strconv.ParseInt(val, 10, 64) - if err != nil { - // Distinguish integer values. Normally, it'd be a bug if the lexer - // provides an invalid integer, but it's possible that the number is - // out of range of valid values (which the lexer cannot determine). - // So mark the former as a bug but the latter as a legitimate user - // error. - if e, ok := err.(*strconv.NumError); ok && - e.Err == strconv.ErrRange { - - p.panicf("Integer '%s' is out of the range of 64-bit "+ - "signed integers.", it.val) - } else { - p.bug("Expected integer value, but got '%s'.", it.val) - } - } - return num, p.typeOfPrimitive(it) - case itemFloat: - parts := strings.FieldsFunc(it.val, func(r rune) bool { - switch r { - case '.', 'e', 'E': - return true - } - return false - }) - for _, part := range parts { - if !numUnderscoresOK(part) { - p.panicf("Invalid float %q: underscores must be "+ - "surrounded by digits", it.val) - } - } - if !numPeriodsOK(it.val) { - // As a special case, numbers like '123.' or '1.e2', - // which are valid as far as Go/strconv are concerned, - // must be rejected because TOML says that a fractional - // part consists of '.' followed by 1+ digits. - p.panicf("Invalid float %q: '.' must be followed "+ - "by one or more digits", it.val) - } - val := strings.Replace(it.val, "_", "", -1) - num, err := strconv.ParseFloat(val, 64) - if err != nil { - if e, ok := err.(*strconv.NumError); ok && - e.Err == strconv.ErrRange { - - p.panicf("Float '%s' is out of the range of 64-bit "+ - "IEEE-754 floating-point numbers.", it.val) - } else { - p.panicf("Invalid float value: %q", it.val) - } - } - return num, p.typeOfPrimitive(it) - case itemDatetime: - var t time.Time - var ok bool - var err error - for _, format := range []string{ - "2006-01-02T15:04:05Z07:00", - "2006-01-02T15:04:05", - "2006-01-02", - } { - t, err = time.ParseInLocation(format, it.val, time.Local) - if err == nil { - ok = true - break - } - } - if !ok { - p.panicf("Invalid TOML Datetime: %q.", it.val) - } - return t, p.typeOfPrimitive(it) - case itemArray: - array := make([]interface{}, 0) - types := make([]tomlType, 0) - - for it = p.next(); it.typ != itemArrayEnd; it = p.next() { - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - val, typ := p.value(it) - array = append(array, val) - types = append(types, typ) - } - return array, p.typeOfArray(types) - case itemInlineTableStart: - var ( - hash = make(map[string]interface{}) - outerContext = p.context - outerKey = p.currentKey - ) - - p.context = append(p.context, p.currentKey) - p.currentKey = "" - for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() { - if it.typ != itemKeyStart { - p.bug("Expected key start but instead found %q, around line %d", - it.val, p.approxLine) - } - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - // retrieve key - k := p.next() - p.approxLine = k.line - kname := p.keyString(k) - - // retrieve value - p.currentKey = kname - val, typ := p.value(p.next()) - // make sure we keep metadata up to date - p.setType(kname, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - hash[kname] = val - } - p.context = outerContext - p.currentKey = outerKey - return hash, tomlHash - } - p.bug("Unexpected value type: %s", it.typ) - panic("unreachable") -} - -// numUnderscoresOK checks whether each underscore in s is surrounded by -// characters that are not underscores. -func numUnderscoresOK(s string) bool { - accept := false - for _, r := range s { - if r == '_' { - if !accept { - return false - } - accept = false - continue - } - accept = true - } - return accept -} - -// numPeriodsOK checks whether every period in s is followed by a digit. -func numPeriodsOK(s string) bool { - period := false - for _, r := range s { - if period && !isDigit(r) { - return false - } - period = r == '.' - } - return !period -} - -// establishContext sets the current context of the parser, -// where the context is either a hash or an array of hashes. Which one is -// set depends on the value of the `array` parameter. -// -// Establishing the context also makes sure that the key isn't a duplicate, and -// will create implicit hashes automatically. -func (p *parser) establishContext(key Key, array bool) { - var ok bool - - // Always start at the top level and drill down for our context. - hashContext := p.mapping - keyContext := make(Key, 0) - - // We only need implicit hashes for key[0:-1] - for _, k := range key[0 : len(key)-1] { - _, ok = hashContext[k] - keyContext = append(keyContext, k) - - // No key? Make an implicit hash and move on. - if !ok { - p.addImplicit(keyContext) - hashContext[k] = make(map[string]interface{}) - } - - // If the hash context is actually an array of tables, then set - // the hash context to the last element in that array. - // - // Otherwise, it better be a table, since this MUST be a key group (by - // virtue of it not being the last element in a key). - switch t := hashContext[k].(type) { - case []map[string]interface{}: - hashContext = t[len(t)-1] - case map[string]interface{}: - hashContext = t - default: - p.panicf("Key '%s' was already created as a hash.", keyContext) - } - } - - p.context = keyContext - if array { - // If this is the first element for this array, then allocate a new - // list of tables for it. - k := key[len(key)-1] - if _, ok := hashContext[k]; !ok { - hashContext[k] = make([]map[string]interface{}, 0, 5) - } - - // Add a new table. But make sure the key hasn't already been used - // for something else. - if hash, ok := hashContext[k].([]map[string]interface{}); ok { - hashContext[k] = append(hash, make(map[string]interface{})) - } else { - p.panicf("Key '%s' was already created and cannot be used as "+ - "an array.", keyContext) - } - } else { - p.setValue(key[len(key)-1], make(map[string]interface{})) - } - p.context = append(p.context, key[len(key)-1]) -} - -// setValue sets the given key to the given value in the current context. -// It will make sure that the key hasn't already been defined, account for -// implicit key groups. -func (p *parser) setValue(key string, value interface{}) { - var tmpHash interface{} - var ok bool - - hash := p.mapping - keyContext := make(Key, 0) - for _, k := range p.context { - keyContext = append(keyContext, k) - if tmpHash, ok = hash[k]; !ok { - p.bug("Context for key '%s' has not been established.", keyContext) - } - switch t := tmpHash.(type) { - case []map[string]interface{}: - // The context is a table of hashes. Pick the most recent table - // defined as the current hash. - hash = t[len(t)-1] - case map[string]interface{}: - hash = t - default: - p.bug("Expected hash to have type 'map[string]interface{}', but "+ - "it has '%T' instead.", tmpHash) - } - } - keyContext = append(keyContext, key) - - if _, ok := hash[key]; ok { - // Typically, if the given key has already been set, then we have - // to raise an error since duplicate keys are disallowed. However, - // it's possible that a key was previously defined implicitly. In this - // case, it is allowed to be redefined concretely. (See the - // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.) - // - // But we have to make sure to stop marking it as an implicit. (So that - // another redefinition provokes an error.) - // - // Note that since it has already been defined (as a hash), we don't - // want to overwrite it. So our business is done. - if p.isImplicit(keyContext) { - p.removeImplicit(keyContext) - return - } - - // Otherwise, we have a concrete key trying to override a previous - // key, which is *always* wrong. - p.panicf("Key '%s' has already been defined.", keyContext) - } - hash[key] = value -} - -// setType sets the type of a particular value at a given key. -// It should be called immediately AFTER setValue. -// -// Note that if `key` is empty, then the type given will be applied to the -// current context (which is either a table or an array of tables). -func (p *parser) setType(key string, typ tomlType) { - keyContext := make(Key, 0, len(p.context)+1) - for _, k := range p.context { - keyContext = append(keyContext, k) - } - if len(key) > 0 { // allow type setting for hashes - keyContext = append(keyContext, key) - } - p.types[keyContext.String()] = typ -} - -// addImplicit sets the given Key as having been created implicitly. -func (p *parser) addImplicit(key Key) { - p.implicits[key.String()] = true -} - -// removeImplicit stops tagging the given key as having been implicitly -// created. -func (p *parser) removeImplicit(key Key) { - p.implicits[key.String()] = false -} - -// isImplicit returns true if the key group pointed to by the key was created -// implicitly. -func (p *parser) isImplicit(key Key) bool { - return p.implicits[key.String()] -} - -// current returns the full key name of the current context. -func (p *parser) current() string { - if len(p.currentKey) == 0 { - return p.context.String() - } - if len(p.context) == 0 { - return p.currentKey - } - return fmt.Sprintf("%s.%s", p.context, p.currentKey) -} - -func stripFirstNewline(s string) string { - if len(s) == 0 || s[0] != '\n' { - return s - } - return s[1:] -} - -func stripEscapedWhitespace(s string) string { - esc := strings.Split(s, "\\\n") - if len(esc) > 1 { - for i := 1; i < len(esc); i++ { - esc[i] = strings.TrimLeftFunc(esc[i], unicode.IsSpace) - } - } - return strings.Join(esc, "") -} - -func (p *parser) replaceEscapes(str string) string { - var replaced []rune - s := []byte(str) - r := 0 - for r < len(s) { - if s[r] != '\\' { - c, size := utf8.DecodeRune(s[r:]) - r += size - replaced = append(replaced, c) - continue - } - r += 1 - if r >= len(s) { - p.bug("Escape sequence at end of string.") - return "" - } - switch s[r] { - default: - p.bug("Expected valid escape code after \\, but got %q.", s[r]) - return "" - case 'b': - replaced = append(replaced, rune(0x0008)) - r += 1 - case 't': - replaced = append(replaced, rune(0x0009)) - r += 1 - case 'n': - replaced = append(replaced, rune(0x000A)) - r += 1 - case 'f': - replaced = append(replaced, rune(0x000C)) - r += 1 - case 'r': - replaced = append(replaced, rune(0x000D)) - r += 1 - case '"': - replaced = append(replaced, rune(0x0022)) - r += 1 - case '\\': - replaced = append(replaced, rune(0x005C)) - r += 1 - case 'u': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+5). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(s[r+1 : r+5]) - replaced = append(replaced, escaped) - r += 5 - case 'U': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+9). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(s[r+1 : r+9]) - replaced = append(replaced, escaped) - r += 9 - } - } - return string(replaced) -} - -func (p *parser) asciiEscapeToUnicode(bs []byte) rune { - s := string(bs) - hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) - if err != nil { - p.bug("Could not parse '%s' as a hexadecimal number, but the "+ - "lexer claims it's OK: %s", s, err) - } - if !utf8.ValidRune(rune(hex)) { - p.panicf("Escaped character '\\u%s' is not valid UTF-8.", s) - } - return rune(hex) -} - -func isStringType(ty itemType) bool { - return ty == itemString || ty == itemMultilineString || - ty == itemRawString || ty == itemRawMultilineString -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/type_check.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/type_check.go deleted file mode 100644 index c73f8af..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/type_check.go +++ /dev/null @@ -1,91 +0,0 @@ -package toml - -// tomlType represents any Go type that corresponds to a TOML type. -// While the first draft of the TOML spec has a simplistic type system that -// probably doesn't need this level of sophistication, we seem to be militating -// toward adding real composite types. -type tomlType interface { - typeString() string -} - -// typeEqual accepts any two types and returns true if they are equal. -func typeEqual(t1, t2 tomlType) bool { - if t1 == nil || t2 == nil { - return false - } - return t1.typeString() == t2.typeString() -} - -func typeIsHash(t tomlType) bool { - return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash) -} - -type tomlBaseType string - -func (btype tomlBaseType) typeString() string { - return string(btype) -} - -func (btype tomlBaseType) String() string { - return btype.typeString() -} - -var ( - tomlInteger tomlBaseType = "Integer" - tomlFloat tomlBaseType = "Float" - tomlDatetime tomlBaseType = "Datetime" - tomlString tomlBaseType = "String" - tomlBool tomlBaseType = "Bool" - tomlArray tomlBaseType = "Array" - tomlHash tomlBaseType = "Hash" - tomlArrayHash tomlBaseType = "ArrayHash" -) - -// typeOfPrimitive returns a tomlType of any primitive value in TOML. -// Primitive values are: Integer, Float, Datetime, String and Bool. -// -// Passing a lexer item other than the following will cause a BUG message -// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime. -func (p *parser) typeOfPrimitive(lexItem item) tomlType { - switch lexItem.typ { - case itemInteger: - return tomlInteger - case itemFloat: - return tomlFloat - case itemDatetime: - return tomlDatetime - case itemString: - return tomlString - case itemMultilineString: - return tomlString - case itemRawString: - return tomlString - case itemRawMultilineString: - return tomlString - case itemBool: - return tomlBool - } - p.bug("Cannot infer primitive type of lex item '%s'.", lexItem) - panic("unreachable") -} - -// typeOfArray returns a tomlType for an array given a list of types of its -// values. -// -// In the current spec, if an array is homogeneous, then its type is always -// "Array". If the array is not homogeneous, an error is generated. -func (p *parser) typeOfArray(types []tomlType) tomlType { - // Empty arrays are cool. - if len(types) == 0 { - return tomlArray - } - - theType := types[0] - for _, t := range types[1:] { - if !typeEqual(theType, t) { - p.panicf("Array contains values of type '%s' and '%s', but "+ - "arrays must be homogeneous.", theType, t) - } - } - return tomlArray -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/type_fields.go b/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/type_fields.go deleted file mode 100644 index 608997c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/BurntSushi/toml/type_fields.go +++ /dev/null @@ -1,242 +0,0 @@ -package toml - -// Struct field handling is adapted from code in encoding/json: -// -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the Go distribution. - -import ( - "reflect" - "sort" - "sync" -) - -// A field represents a single field found in a struct. -type field struct { - name string // the name of the field (`toml` tag included) - tag bool // whether field has a `toml` tag - index []int // represents the depth of an anonymous field - typ reflect.Type // the type of the field -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from toml tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that TOML should recognize for the given -// type. The algorithm is breadth-first search over the set of structs to -// include - the top struct and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - opts := getOptions(sf.Tag) - if opts.skip { - continue - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := opts.name != "" - name := opts.name - if name == "" { - name = sf.Name - } - fields = append(fields, field{name, tagged, index, ft}) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - f := field{name: ft.Name(), index: index, typ: ft} - next = append(next, f) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with TOML tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// TOML tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/LICENSE deleted file mode 100644 index be20a12..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Fabio Berchtold - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/account_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/account_info.go deleted file mode 100644 index f994f92..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/account_info.go +++ /dev/null @@ -1,71 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "strconv" -) - -// AccountInfo of Vultr account -type AccountInfo struct { - Balance float64 `json:"balance"` - PendingCharges float64 `json:"pending_charges"` - LastPaymentDate string `json:"last_payment_date"` - LastPaymentAmount float64 `json:"last_payment_amount"` -} - -// GetAccountInfo retrieves the Vultr account information about current balance, pending charges, etc.. -func (c *Client) GetAccountInfo() (info AccountInfo, err error) { - if err := c.get(`account/info`, &info); err != nil { - return AccountInfo{}, err - } - return -} - -// UnmarshalJSON implements json.Unmarshaller on AccountInfo. -// This is needed because the Vultr API is inconsistent in it's JSON responses for account info. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) { - if a == nil { - *a = AccountInfo{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["balance"]) - if len(value) == 0 || value == "" { - value = "0" - } - b, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - a.Balance = b - - value = fmt.Sprintf("%v", fields["pending_charges"]) - if len(value) == 0 || value == "" { - value = "0" - } - pc, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - a.PendingCharges = pc - - value = fmt.Sprintf("%v", fields["last_payment_amount"]) - if len(value) == 0 || value == "" { - value = "0" - } - lpa, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - a.LastPaymentAmount = lpa - - a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"]) - - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/applications.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/applications.go deleted file mode 100644 index f44d8c8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/applications.go +++ /dev/null @@ -1,38 +0,0 @@ -package lib - -import ( - "sort" - "strings" -) - -// Application on Vultr -type Application struct { - ID string `json:"APPID"` - Name string `json:"name"` - ShortName string `json:"short_name"` - DeployName string `json:"deploy_name"` - Surcharge float64 `json:"surcharge"` -} - -type applications []Application - -func (s applications) Len() int { return len(s) } -func (s applications) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s applications) Less(i, j int) bool { - return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) -} - -// GetApplications returns a list of all available applications on Vultr -func (c *Client) GetApplications() ([]Application, error) { - var appMap map[string]Application - if err := c.get(`app/list`, &appMap); err != nil { - return nil, err - } - - var appList []Application - for _, app := range appMap { - appList = append(appList, app) - } - sort.Sort(applications(appList)) - return appList, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/block_storage.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/block_storage.go deleted file mode 100644 index e9e8e11..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/block_storage.go +++ /dev/null @@ -1,210 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net/url" - "sort" - "strconv" - "strings" -) - -// BlockStorage on Vultr account -type BlockStorage struct { - ID string `json:"SUBID,string"` - Name string `json:"label"` - RegionID int `json:"DCID,string"` - SizeGB int `json:"size_gb,string"` - Created string `json:"date_created"` - Cost string `json:"cost_per_month"` - Status string `json:"status"` - AttachedTo string `json:"attached_to_SUBID"` -} - -type blockstorages []BlockStorage - -func (b blockstorages) Len() int { return len(b) } -func (b blockstorages) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b blockstorages) Less(i, j int) bool { - // sort order: name, size, status - if strings.ToLower(b[i].Name) < strings.ToLower(b[j].Name) { - return true - } else if strings.ToLower(b[i].Name) > strings.ToLower(b[j].Name) { - return false - } - if b[i].SizeGB < b[j].SizeGB { - return true - } else if b[i].SizeGB > b[j].SizeGB { - return false - } - return b[i].Status < b[j].Status -} - -// UnmarshalJSON implements json.Unmarshaller on BlockStorage. -// This is needed because the Vultr API is inconsistent in it's JSON responses. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (b *BlockStorage) UnmarshalJSON(data []byte) (err error) { - if b == nil { - *b = BlockStorage{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["SUBID"]) - if len(value) == 0 || value == "" || value == "0" { - b.ID = "" - } else { - id, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - b.ID = strconv.FormatFloat(id, 'f', -1, 64) - } - - value = fmt.Sprintf("%v", fields["DCID"]) - if len(value) == 0 || value == "" { - value = "0" - } - region, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - b.RegionID = int(region) - - value = fmt.Sprintf("%v", fields["size_gb"]) - if len(value) == 0 || value == "" { - value = "0" - } - size, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - b.SizeGB = int(size) - - value = fmt.Sprintf("%v", fields["attached_to_SUBID"]) - if len(value) == 0 || value == "" || value == "0" { - b.AttachedTo = "" - } else { - attached, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - b.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64) - } - - b.Name = fmt.Sprintf("%v", fields["label"]) - b.Created = fmt.Sprintf("%v", fields["date_created"]) - b.Status = fmt.Sprintf("%v", fields["status"]) - b.Cost = fmt.Sprintf("%v", fields["cost_per_month"]) - - return -} - -// GetBlockStorages returns a list of all active block storages on Vultr account -func (c *Client) GetBlockStorages() (storages []BlockStorage, err error) { - if err := c.get(`block/list`, &storages); err != nil { - return nil, err - } - sort.Sort(blockstorages(storages)) - return storages, nil -} - -// GetBlockStorage returns block storage with given ID -func (c *Client) GetBlockStorage(id string) (BlockStorage, error) { - storages, err := c.GetBlockStorages() - if err != nil { - return BlockStorage{}, err - } - - for _, s := range storages { - if s.ID == id { - return s, nil - } - } - return BlockStorage{}, fmt.Errorf("BlockStorage with ID %v not found", id) -} - -// CreateBlockStorage creates a new block storage on Vultr account -func (c *Client) CreateBlockStorage(name string, regionID, size int) (BlockStorage, error) { - values := url.Values{ - "label": {name}, - "DCID": {fmt.Sprintf("%v", regionID)}, - "size_gb": {fmt.Sprintf("%v", size)}, - } - - var storage BlockStorage - if err := c.post(`block/create`, values, &storage); err != nil { - return BlockStorage{}, err - } - storage.RegionID = regionID - storage.Name = name - storage.SizeGB = size - - return storage, nil -} - -// ResizeBlockStorage resizes an existing block storage -func (c *Client) ResizeBlockStorage(id string, size int) error { - values := url.Values{ - "SUBID": {id}, - "size_gb": {fmt.Sprintf("%v", size)}, - } - - if err := c.post(`block/resize`, values, nil); err != nil { - return err - } - return nil -} - -// LabelBlockStorage changes the label on an existing block storage -func (c *Client) LabelBlockStorage(id, name string) error { - values := url.Values{ - "SUBID": {id}, - "label": {name}, - } - - if err := c.post(`block/label_set`, values, nil); err != nil { - return err - } - return nil -} - -// AttachBlockStorage attaches block storage to an existing virtual machine -func (c *Client) AttachBlockStorage(id, serverID string) error { - values := url.Values{ - "SUBID": {id}, - "attach_to_SUBID": {serverID}, - } - - if err := c.post(`block/attach`, values, nil); err != nil { - return err - } - return nil -} - -// DetachBlockStorage detaches block storage from virtual machine -func (c *Client) DetachBlockStorage(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`block/detach`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteBlockStorage deletes an existing block storage -func (c *Client) DeleteBlockStorage(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`block/delete`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/client.go deleted file mode 100644 index 6d565ab..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/client.go +++ /dev/null @@ -1,258 +0,0 @@ -package lib - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "math/rand" - "net/http" - "net/url" - "strings" - "time" - - "github.com/juju/ratelimit" -) - -const ( - // Version of this libary - Version = "1.15.0" - - // APIVersion of Vultr - APIVersion = "v1" - - // DefaultEndpoint to be used - DefaultEndpoint = "https://api.vultr.com/" - - mediaType = "application/json" -) - -// retryableStatusCodes are API response status codes that indicate that -// the failed request can be retried without further actions. -var retryableStatusCodes = map[int]struct{}{ - 503: {}, // Rate limit hit - 500: {}, // Internal server error. Try again at a later time. -} - -// Client represents the Vultr API client -type Client struct { - // HTTP client for communication with the Vultr API - client *http.Client - - // User agent for HTTP client - UserAgent string - - // Endpoint URL for API requests - Endpoint *url.URL - - // API key for accessing the Vultr API - APIKey string - - // Max. number of request attempts - MaxAttempts int - - // Throttling struct - bucket *ratelimit.Bucket - - // Optional function called after every successful request made to the API - onRequestCompleted RequestCompletionCallback -} - -// RequestCompletionCallback defines the type of the request callback function -type RequestCompletionCallback func(*http.Request, *http.Response) - -// Options represents optional settings and flags that can be passed to NewClient -type Options struct { - // HTTP client for communication with the Vultr API - HTTPClient *http.Client - - // User agent for HTTP client - UserAgent string - - // Endpoint URL for API requests - Endpoint string - - // API rate limitation, calls per duration - RateLimitation time.Duration - - // Max. number of times to retry API calls - MaxRetries int -} - -// NewClient creates new Vultr API client. Options are optional and can be nil. -func NewClient(apiKey string, options *Options) *Client { - userAgent := "vultr-go/" + Version - transport := &http.Transport{ - TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), - } - client := http.DefaultClient - client.Transport = transport - endpoint, _ := url.Parse(DefaultEndpoint) - rate := 505 * time.Millisecond - attempts := 1 - - if options != nil { - if options.HTTPClient != nil { - client = options.HTTPClient - } - if options.UserAgent != "" { - userAgent = options.UserAgent - } - if options.Endpoint != "" { - endpoint, _ = url.Parse(options.Endpoint) - } - if options.RateLimitation != 0 { - rate = options.RateLimitation - } - if options.MaxRetries != 0 { - attempts = options.MaxRetries + 1 - } - } - - return &Client{ - UserAgent: userAgent, - client: client, - Endpoint: endpoint, - APIKey: apiKey, - MaxAttempts: attempts, - bucket: ratelimit.NewBucket(rate, 1), - } -} - -func apiPath(path string) string { - return fmt.Sprintf("/%s/%s", APIVersion, path) -} - -func (c *Client) get(path string, data interface{}) error { - req, err := c.newRequest("GET", apiPath(path), nil) - if err != nil { - return err - } - return c.do(req, data) -} - -func (c *Client) post(path string, values url.Values, data interface{}) error { - req, err := c.newRequest("POST", apiPath(path), strings.NewReader(values.Encode())) - if err != nil { - return err - } - return c.do(req, data) -} - -// OnRequestCompleted sets the API request completion callback -func (c *Client) OnRequestCompleted(rc RequestCompletionCallback) { - c.onRequestCompleted = rc -} - -func (c *Client) newRequest(method string, path string, body io.Reader) (*http.Request, error) { - relPath, err := url.Parse(path) - if err != nil { - return nil, err - } - - url := c.Endpoint.ResolveReference(relPath) - - req, err := http.NewRequest(method, url.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("API-Key", c.APIKey) - req.Header.Add("User-Agent", c.UserAgent) - req.Header.Add("Accept", mediaType) - - if req.Method == "POST" { - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - } - return req, nil -} - -func (c *Client) do(req *http.Request, data interface{}) error { - // Throttle http requests to avoid hitting Vultr's API rate-limit - c.bucket.Wait(1) - - // Request body gets drained on each read so we - // need to save it's content for retrying requests - var err error - var requestBody []byte - if req.Body != nil { - requestBody, err = ioutil.ReadAll(req.Body) - if err != nil { - return fmt.Errorf("Error reading request body: %v", err) - } - req.Body.Close() - } - - var apiError error - for tryCount := 1; tryCount <= c.MaxAttempts; tryCount++ { - // Restore request body to the original state - if requestBody != nil { - req.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody)) - } - - resp, err := c.client.Do(req) - if err != nil { - return err - } - - if c.onRequestCompleted != nil { - c.onRequestCompleted(req, resp) - } - - body, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - if err != nil { - return err - } - - if resp.StatusCode == http.StatusOK { - if data != nil { - // avoid unmarshalling problem because Vultr API returns - // empty array instead of empty map when it shouldn't! - if string(body) == `[]` { - data = nil - } else { - if err := json.Unmarshal(body, data); err != nil { - return err - } - } - } - return nil - } - - apiError = errors.New(string(body)) - if !isCodeRetryable(resp.StatusCode) { - break - } - - delay := backoffDuration(tryCount) - time.Sleep(delay) - } - - return apiError -} - -// backoffDuration returns the duration to wait before retrying the request. -// Duration is an exponential function of the retry count with a jitter of ~0-30%. -func backoffDuration(retryCount int) time.Duration { - // Upper limit of delay at ~1 minute - if retryCount > 7 { - retryCount = 7 - } - - rand.Seed(time.Now().UnixNano()) - delay := (1 << uint(retryCount)) * (rand.Intn(150) + 500) - return time.Duration(delay) * time.Millisecond -} - -// isCodeRetryable returns true if the given status code means that we should retry. -func isCodeRetryable(statusCode int) bool { - if _, ok := retryableStatusCodes[statusCode]; ok { - return true - } - - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/dns.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/dns.go deleted file mode 100644 index e66275b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/dns.go +++ /dev/null @@ -1,150 +0,0 @@ -package lib - -import ( - "fmt" - "net/url" - "sort" - "strings" -) - -// DNSDomain represents a DNS domain on Vultr -type DNSDomain struct { - Domain string `json:"domain"` - Created string `json:"date_created"` -} - -type dnsdomains []DNSDomain - -func (d dnsdomains) Len() int { return len(d) } -func (d dnsdomains) Swap(i, j int) { d[i], d[j] = d[j], d[i] } -func (d dnsdomains) Less(i, j int) bool { - return strings.ToLower(d[i].Domain) < strings.ToLower(d[j].Domain) -} - -// DNSRecord represents a DNS record on Vultr -type DNSRecord struct { - RecordID int `json:"RECORDID"` - Type string `json:"type"` - Name string `json:"name"` - Data string `json:"data"` - Priority int `json:"priority"` - TTL int `json:"ttl"` -} - -type dnsrecords []DNSRecord - -func (d dnsrecords) Len() int { return len(d) } -func (d dnsrecords) Swap(i, j int) { d[i], d[j] = d[j], d[i] } -func (d dnsrecords) Less(i, j int) bool { - // sort order: type, data, name - if d[i].Type < d[j].Type { - return true - } else if d[i].Type > d[j].Type { - return false - } - if d[i].Data < d[j].Data { - return true - } else if d[i].Data > d[j].Data { - return false - } - return strings.ToLower(d[i].Name) < strings.ToLower(d[j].Name) -} - -// GetDNSDomains returns a list of available domains on Vultr account -func (c *Client) GetDNSDomains() (domains []DNSDomain, err error) { - if err := c.get(`dns/list`, &domains); err != nil { - return nil, err - } - sort.Sort(dnsdomains(domains)) - return domains, nil -} - -// GetDNSRecords returns a list of all DNS records of a particular domain -func (c *Client) GetDNSRecords(domain string) (records []DNSRecord, err error) { - if err := c.get(`dns/records?domain=`+domain, &records); err != nil { - return nil, err - } - sort.Sort(dnsrecords(records)) - return records, nil -} - -// CreateDNSDomain creates a new DNS domain name on Vultr -func (c *Client) CreateDNSDomain(domain, serverIP string) error { - values := url.Values{ - "domain": {domain}, - "serverip": {serverIP}, - } - - if err := c.post(`dns/create_domain`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteDNSDomain deletes an existing DNS domain name -func (c *Client) DeleteDNSDomain(domain string) error { - values := url.Values{ - "domain": {domain}, - } - - if err := c.post(`dns/delete_domain`, values, nil); err != nil { - return err - } - return nil -} - -// CreateDNSRecord creates a new DNS record -func (c *Client) CreateDNSRecord(domain, name, rtype, data string, priority, ttl int) error { - values := url.Values{ - "domain": {domain}, - "name": {name}, - "type": {rtype}, - "data": {data}, - "priority": {fmt.Sprintf("%v", priority)}, - "ttl": {fmt.Sprintf("%v", ttl)}, - } - - if err := c.post(`dns/create_record`, values, nil); err != nil { - return err - } - return nil -} - -// UpdateDNSRecord updates an existing DNS record -func (c *Client) UpdateDNSRecord(domain string, dnsrecord DNSRecord) error { - values := url.Values{ - "domain": {domain}, - "RECORDID": {fmt.Sprintf("%v", dnsrecord.RecordID)}, - } - - if dnsrecord.Name != "" { - values.Add("name", dnsrecord.Name) - } - if dnsrecord.Data != "" { - values.Add("data", dnsrecord.Data) - } - if dnsrecord.Priority != 0 { - values.Add("priority", fmt.Sprintf("%v", dnsrecord.Priority)) - } - if dnsrecord.TTL != 0 { - values.Add("ttl", fmt.Sprintf("%v", dnsrecord.TTL)) - } - - if err := c.post(`dns/update_record`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteDNSRecord deletes an existing DNS record -func (c *Client) DeleteDNSRecord(domain string, recordID int) error { - values := url.Values{ - "domain": {domain}, - "RECORDID": {fmt.Sprintf("%v", recordID)}, - } - - if err := c.post(`dns/delete_record`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/firewall.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/firewall.go deleted file mode 100644 index 08a11d1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/firewall.go +++ /dev/null @@ -1,252 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net" - "net/url" - "sort" - "strconv" - "strings" -) - -// FirewallGroup represents a firewall group on Vultr -type FirewallGroup struct { - ID string `json:"FIREWALLGROUPID"` - Description string `json:"description"` - Created string `json:"date_created"` - Modified string `json:"date_modified"` - InstanceCount int `json:"instance_count"` - RuleCount int `json:"rule_count"` - MaxRuleCount int `json:"max_rule_count"` -} - -// FirewallRule represents a firewall rule on Vultr -type FirewallRule struct { - RuleNumber int `json:"rulenumber"` - Action string `json:"action"` - Protocol string `json:"protocol"` - Port string `json:"port"` - Network *net.IPNet -} - -type firewallGroups []FirewallGroup - -func (f firewallGroups) Len() int { return len(f) } -func (f firewallGroups) Swap(i, j int) { f[i], f[j] = f[j], f[i] } -func (f firewallGroups) Less(i, j int) bool { - // sort order: description - return strings.ToLower(f[i].Description) < strings.ToLower(f[j].Description) -} - -type firewallRules []FirewallRule - -func (r firewallRules) Len() int { return len(r) } -func (r firewallRules) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r firewallRules) Less(i, j int) bool { - // sort order: rule number - return r[i].RuleNumber < r[j].RuleNumber -} - -// UnmarshalJSON implements json.Unmarshaller on FirewallRule. -// This is needed because the Vultr API is inconsistent in it's JSON responses. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (r *FirewallRule) UnmarshalJSON(data []byte) (err error) { - if r == nil { - *r = FirewallRule{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["rulenumber"]) - if len(value) == 0 || value == "" { - value = "0" - } - number, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - r.RuleNumber = int(number) - - value = fmt.Sprintf("%v", fields["subnet_size"]) - if len(value) == 0 || value == "" { - value = "0" - } - subnetSize, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - - r.Action = fmt.Sprintf("%v", fields["action"]) - r.Protocol = fmt.Sprintf("%v", fields["protocol"]) - r.Port = fmt.Sprintf("%v", fields["port"]) - subnet := fmt.Sprintf("%v", fields["subnet"]) - if subnet == "" { - subnet = "" - } - - if len(subnet) > 0 { - _, r.Network, err = net.ParseCIDR(fmt.Sprintf("%s/%d", subnet, subnetSize)) - if err != nil { - return fmt.Errorf("Failed to parse subnet from Vultr API") - } - } else { - // This case is used to create a valid default CIDR when the Vultr API does not return a subnet/subnet size at all, e.g. the response after creating a new rule. - _, r.Network, _ = net.ParseCIDR("0.0.0.0/0") - } - - return -} - -// GetFirewallGroups returns a list of all available firewall groups on Vultr -func (c *Client) GetFirewallGroups() ([]FirewallGroup, error) { - var groupMap map[string]FirewallGroup - if err := c.get(`firewall/group_list`, &groupMap); err != nil { - return nil, err - } - - var groupList []FirewallGroup - for _, g := range groupMap { - groupList = append(groupList, g) - } - sort.Sort(firewallGroups(groupList)) - return groupList, nil -} - -// GetFirewallGroup returns the firewall group with given ID -func (c *Client) GetFirewallGroup(id string) (FirewallGroup, error) { - groups, err := c.GetFirewallGroups() - if err != nil { - return FirewallGroup{}, err - } - - for _, g := range groups { - if g.ID == id { - return g, nil - } - } - return FirewallGroup{}, fmt.Errorf("Firewall group with ID %v not found", id) -} - -// CreateFirewallGroup creates a new firewall group in Vultr account -func (c *Client) CreateFirewallGroup(description string) (string, error) { - values := url.Values{} - - // Optional description - if len(description) > 0 { - values.Add("description", description) - } - - var result FirewallGroup - err := c.post(`firewall/group_create`, values, &result) - if err != nil { - return "", err - } - return result.ID, nil -} - -// DeleteFirewallGroup deletes an existing firewall group -func (c *Client) DeleteFirewallGroup(groupID string) error { - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - } - - if err := c.post(`firewall/group_delete`, values, nil); err != nil { - return err - } - return nil -} - -// SetFirewallGroupDescription sets the description of an existing firewall group -func (c *Client) SetFirewallGroupDescription(groupID, description string) error { - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - "description": {description}, - } - - if err := c.post(`firewall/group_set_description`, values, nil); err != nil { - return err - } - return nil -} - -// GetFirewallRules returns a list of rules for the given firewall group -func (c *Client) GetFirewallRules(groupID string) ([]FirewallRule, error) { - var ruleMap map[string]FirewallRule - ipTypes := []string{"v4", "v6"} - for _, ipType := range ipTypes { - args := fmt.Sprintf("direction=in&FIREWALLGROUPID=%s&ip_type=%s", - groupID, ipType) - if err := c.get(`firewall/rule_list?`+args, &ruleMap); err != nil { - return nil, err - } - } - - var ruleList []FirewallRule - for _, r := range ruleMap { - ruleList = append(ruleList, r) - } - sort.Sort(firewallRules(ruleList)) - return ruleList, nil -} - -// CreateFirewallRule creates a new firewall rule in Vultr account. -// groupID is the ID of the firewall group to create the rule in -// protocol must be one of: "icmp", "tcp", "udp", "gre" -// port can be a port number or colon separated port range (TCP/UDP only) -func (c *Client) CreateFirewallRule(groupID, protocol, port string, - network *net.IPNet) (int, error) { - ip := network.IP.String() - maskBits, _ := network.Mask.Size() - if ip == "" { - return 0, fmt.Errorf("Invalid network") - } - - var ipType string - if network.IP.To4() != nil { - ipType = "v4" - } else { - ipType = "v6" - } - - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - // possible values: "in" - "direction": {"in"}, - // possible values: "icmp", "tcp", "udp", "gre" - "protocol": {protocol}, - // possible values: "v4", "v6" - "ip_type": {ipType}, - // IP address representing a subnet - "subnet": {ip}, - // IP prefix size in bits - "subnet_size": {fmt.Sprintf("%v", maskBits)}, - } - - if len(port) > 0 { - values.Add("port", port) - } - - var result FirewallRule - err := c.post(`firewall/rule_create`, values, &result) - if err != nil { - return 0, err - } - return result.RuleNumber, nil -} - -// DeleteFirewallRule deletes an existing firewall rule -func (c *Client) DeleteFirewallRule(ruleNumber int, groupID string) error { - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - "rulenumber": {fmt.Sprintf("%v", ruleNumber)}, - } - - if err := c.post(`firewall/rule_delete`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/ip.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/ip.go deleted file mode 100644 index 4d169cb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/ip.go +++ /dev/null @@ -1,192 +0,0 @@ -package lib - -import ( - "fmt" - "net/url" - "sort" -) - -// IPv4 information of a virtual machine -type IPv4 struct { - IP string `json:"ip"` - Netmask string `json:"netmask"` - Gateway string `json:"gateway"` - Type string `json:"type"` - ReverseDNS string `json:"reverse"` -} - -type ipv4s []IPv4 - -func (s ipv4s) Len() int { return len(s) } -func (s ipv4s) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s ipv4s) Less(i, j int) bool { - // sort order: type, ip - if s[i].Type < s[j].Type { - return true - } else if s[i].Type > s[j].Type { - return false - } - return s[i].IP < s[j].IP -} - -// IPv6 information of a virtual machine -type IPv6 struct { - IP string `json:"ip"` - Network string `json:"network"` - NetworkSize string `json:"network_size"` - Type string `json:"type"` -} - -type ipv6s []IPv6 - -func (s ipv6s) Len() int { return len(s) } -func (s ipv6s) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s ipv6s) Less(i, j int) bool { - // sort order: type, ip - if s[i].Type < s[j].Type { - return true - } else if s[i].Type > s[j].Type { - return false - } - return s[i].IP < s[j].IP -} - -// ReverseDNSIPv6 information of a virtual machine -type ReverseDNSIPv6 struct { - IP string `json:"ip"` - ReverseDNS string `json:"reverse"` -} - -type reverseDNSIPv6s []ReverseDNSIPv6 - -func (s reverseDNSIPv6s) Len() int { return len(s) } -func (s reverseDNSIPv6s) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s reverseDNSIPv6s) Less(i, j int) bool { return s[i].IP < s[j].IP } - -// ListIPv4 lists the IPv4 information of a virtual machine -func (c *Client) ListIPv4(id string) (list []IPv4, err error) { - var ipMap map[string][]IPv4 - if err := c.get(`server/list_ipv4?SUBID=`+id, &ipMap); err != nil { - return nil, err - } - - for _, iplist := range ipMap { - for _, ip := range iplist { - list = append(list, ip) - } - } - sort.Sort(ipv4s(list)) - return list, nil -} - -// CreateIPv4 creates an IPv4 address and attaches it to a virtual machine -func (c *Client) CreateIPv4(id string, reboot bool) error { - values := url.Values{ - "SUBID": {id}, - "reboot": {fmt.Sprintf("%t", reboot)}, - } - - if err := c.post(`server/create_ipv4`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteIPv4 deletes an IPv4 address and detaches it from a virtual machine -func (c *Client) DeleteIPv4(id, ip string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - } - - if err := c.post(`server/destroy_ipv4`, values, nil); err != nil { - return err - } - return nil -} - -// ListIPv6 lists the IPv4 information of a virtual machine -func (c *Client) ListIPv6(id string) (list []IPv6, err error) { - var ipMap map[string][]IPv6 - if err := c.get(`server/list_ipv6?SUBID=`+id, &ipMap); err != nil { - return nil, err - } - - for _, iplist := range ipMap { - for _, ip := range iplist { - list = append(list, ip) - } - } - sort.Sort(ipv6s(list)) - return list, nil -} - -// ListIPv6ReverseDNS lists the IPv6 reverse DNS entries of a virtual machine -func (c *Client) ListIPv6ReverseDNS(id string) (list []ReverseDNSIPv6, err error) { - var ipMap map[string][]ReverseDNSIPv6 - if err := c.get(`server/reverse_list_ipv6?SUBID=`+id, &ipMap); err != nil { - return nil, err - } - - for _, iplist := range ipMap { - for _, ip := range iplist { - list = append(list, ip) - } - } - sort.Sort(reverseDNSIPv6s(list)) - return list, nil -} - -// DeleteIPv6ReverseDNS removes a reverse DNS entry for an IPv6 address of a virtual machine -func (c *Client) DeleteIPv6ReverseDNS(id string, ip string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - } - - if err := c.post(`server/reverse_delete_ipv6`, values, nil); err != nil { - return err - } - return nil -} - -// SetIPv6ReverseDNS sets a reverse DNS entry for an IPv6 address of a virtual machine -func (c *Client) SetIPv6ReverseDNS(id, ip, entry string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - "entry": {entry}, - } - - if err := c.post(`server/reverse_set_ipv6`, values, nil); err != nil { - return err - } - return nil -} - -// DefaultIPv4ReverseDNS sets a reverse DNS entry for an IPv4 address of a virtual machine to the original setting -func (c *Client) DefaultIPv4ReverseDNS(id, ip string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - } - - if err := c.post(`server/reverse_default_ipv4`, values, nil); err != nil { - return err - } - return nil -} - -// SetIPv4ReverseDNS sets a reverse DNS entry for an IPv4 address of a virtual machine -func (c *Client) SetIPv4ReverseDNS(id, ip, entry string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - "entry": {entry}, - } - - if err := c.post(`server/reverse_set_ipv4`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/iso.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/iso.go deleted file mode 100644 index a9e1880..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/iso.go +++ /dev/null @@ -1,44 +0,0 @@ -package lib - -import ( - "sort" - "strings" -) - -// ISO image on Vultr -type ISO struct { - ID int `json:"ISOID"` - Created string `json:"date_created"` - Filename string `json:"filename"` - Size int `json:"size"` - MD5sum string `json:"md5sum"` -} - -type isos []ISO - -func (s isos) Len() int { return len(s) } -func (s isos) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s isos) Less(i, j int) bool { - // sort order: filename, created - if strings.ToLower(s[i].Filename) < strings.ToLower(s[j].Filename) { - return true - } else if strings.ToLower(s[i].Filename) > strings.ToLower(s[j].Filename) { - return false - } - return s[i].Created < s[j].Created -} - -// GetISO returns a list of all ISO images on Vultr account -func (c *Client) GetISO() ([]ISO, error) { - var isoMap map[string]ISO - if err := c.get(`iso/list`, &isoMap); err != nil { - return nil, err - } - - var isoList []ISO - for _, iso := range isoMap { - isoList = append(isoList, iso) - } - sort.Sort(isos(isoList)) - return isoList, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/os.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/os.go deleted file mode 100644 index 647d253..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/os.go +++ /dev/null @@ -1,37 +0,0 @@ -package lib - -import ( - "sort" - "strings" -) - -// OS image on Vultr -type OS struct { - ID int `json:"OSID"` - Name string `json:"name"` - Arch string `json:"arch"` - Family string `json:"family"` - Windows bool `json:"windows"` - Surcharge string `json:"surcharge"` -} - -type oses []OS - -func (s oses) Len() int { return len(s) } -func (s oses) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s oses) Less(i, j int) bool { return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) } - -// GetOS returns a list of all available operating systems on Vultr -func (c *Client) GetOS() ([]OS, error) { - var osMap map[string]OS - if err := c.get(`os/list`, &osMap); err != nil { - return nil, err - } - - var osList []OS - for _, os := range osMap { - osList = append(osList, os) - } - sort.Sort(oses(osList)) - return osList, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/plans.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/plans.go deleted file mode 100644 index b3bef4e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/plans.go +++ /dev/null @@ -1,78 +0,0 @@ -package lib - -import ( - "fmt" - "sort" - "strconv" - "strings" -) - -// Plan on Vultr -type Plan struct { - ID int `json:"VPSPLANID,string"` - Name string `json:"name"` - VCpus int `json:"vcpu_count,string"` - RAM string `json:"ram"` - Disk string `json:"disk"` - Bandwidth string `json:"bandwidth"` - Price string `json:"price_per_month"` - Regions []int `json:"available_locations"` -} - -type plans []Plan - -func (p plans) Len() int { return len(p) } -func (p plans) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p plans) Less(i, j int) bool { - pa, _ := strconv.ParseFloat(strings.TrimSpace(p[i].Price), 64) - pb, _ := strconv.ParseFloat(strings.TrimSpace(p[j].Price), 64) - ra, _ := strconv.ParseInt(strings.TrimSpace(p[i].RAM), 10, 64) - rb, _ := strconv.ParseInt(strings.TrimSpace(p[j].RAM), 10, 64) - da, _ := strconv.ParseInt(strings.TrimSpace(p[i].Disk), 10, 64) - db, _ := strconv.ParseInt(strings.TrimSpace(p[j].Disk), 10, 64) - - // sort order: price, vcpu, ram, disk - if pa < pb { - return true - } else if pa > pb { - return false - } - - if p[i].VCpus < p[j].VCpus { - return true - } else if p[i].VCpus > p[j].VCpus { - return false - } - - if ra < rb { - return true - } else if ra > rb { - return false - } - - return da < db -} - -// GetPlans returns a list of all available plans on Vultr account -func (c *Client) GetPlans() ([]Plan, error) { - var planMap map[string]Plan - if err := c.get(`plans/list`, &planMap); err != nil { - return nil, err - } - - var p plans - for _, plan := range planMap { - p = append(p, plan) - } - - sort.Sort(plans(p)) - return p, nil -} - -// GetAvailablePlansForRegion returns available plans for specified region -func (c *Client) GetAvailablePlansForRegion(id int) (planIDs []int, err error) { - if err := c.get(fmt.Sprintf(`regions/availability?DCID=%v`, id), &planIDs); err != nil { - return nil, err - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/regions.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/regions.go deleted file mode 100644 index 70ceb2e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/regions.go +++ /dev/null @@ -1,44 +0,0 @@ -package lib - -import "sort" - -// Region on Vultr -type Region struct { - ID int `json:"DCID,string"` - Name string `json:"name"` - Country string `json:"country"` - Continent string `json:"continent"` - State string `json:"state"` - Ddos bool `json:"ddos_protection"` - BlockStorage bool `json:"block_storage"` - Code string `json:"regioncode"` -} - -type regions []Region - -func (s regions) Len() int { return len(s) } -func (s regions) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s regions) Less(i, j int) bool { - // sort order: continent, name - if s[i].Continent < s[j].Continent { - return true - } else if s[i].Continent > s[j].Continent { - return false - } - return s[i].Name < s[j].Name -} - -// GetRegions returns a list of all available Vultr regions -func (c *Client) GetRegions() ([]Region, error) { - var regionMap map[string]Region - if err := c.get(`regions/list`, ®ionMap); err != nil { - return nil, err - } - - var regionList []Region - for _, os := range regionMap { - regionList = append(regionList, os) - } - sort.Sort(regions(regionList)) - return regionList, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/reservedip.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/reservedip.go deleted file mode 100644 index 22097cf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/reservedip.go +++ /dev/null @@ -1,192 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net/url" - "sort" - "strconv" - "strings" -) - -// IP on Vultr -type IP struct { - ID string `json:"SUBID,string"` - RegionID int `json:"DCID,string"` - IPType string `json:"ip_type"` - Subnet string `json:"subnet"` - SubnetSize int `json:"subnet_size"` - Label string `json:"label"` - AttachedTo string `json:"attached_SUBID,string"` -} - -type ips []IP - -func (s ips) Len() int { return len(s) } -func (s ips) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s ips) Less(i, j int) bool { - // sort order: label, iptype, subnet - if strings.ToLower(s[i].Label) < strings.ToLower(s[j].Label) { - return true - } else if strings.ToLower(s[i].Label) > strings.ToLower(s[j].Label) { - return false - } - if s[i].IPType < s[j].IPType { - return true - } else if s[i].IPType > s[j].IPType { - return false - } - return s[i].Subnet < s[j].Subnet -} - -// UnmarshalJSON implements json.Unmarshaller on IP. -// This is needed because the Vultr API is inconsistent in it's JSON responses. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (i *IP) UnmarshalJSON(data []byte) (err error) { - if i == nil { - *i = IP{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["SUBID"]) - if len(value) == 0 || value == "" || value == "0" { - i.ID = "" - } else { - id, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - i.ID = strconv.FormatFloat(id, 'f', -1, 64) - } - - value = fmt.Sprintf("%v", fields["DCID"]) - if len(value) == 0 || value == "" { - value = "0" - } - region, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - i.RegionID = int(region) - - value = fmt.Sprintf("%v", fields["attached_SUBID"]) - if len(value) == 0 || value == "" || value == "0" || value == "false" { - i.AttachedTo = "" - } else { - attached, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - i.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64) - } - - value = fmt.Sprintf("%v", fields["subnet_size"]) - if len(value) == 0 || value == "" { - value = "0" - } - size, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - i.SubnetSize = int(size) - - i.IPType = fmt.Sprintf("%v", fields["ip_type"]) - i.Subnet = fmt.Sprintf("%v", fields["subnet"]) - i.Label = fmt.Sprintf("%v", fields["label"]) - - return -} - -// ListReservedIP returns a list of all available reserved IPs on Vultr account -func (c *Client) ListReservedIP() ([]IP, error) { - var ipMap map[string]IP - - err := c.get(`reservedip/list`, &ipMap) - if err != nil { - return nil, err - } - - ipList := make([]IP, 0) - for _, ip := range ipMap { - ipList = append(ipList, ip) - } - sort.Sort(ips(ipList)) - return ipList, nil -} - -// GetReservedIP returns reserved IP with given ID -func (c *Client) GetReservedIP(id string) (IP, error) { - var ipMap map[string]IP - - err := c.get(`reservedip/list`, &ipMap) - if err != nil { - return IP{}, err - } - if ip, ok := ipMap[id]; ok { - return ip, nil - } - return IP{}, fmt.Errorf("IP with ID %v not found", id) -} - -// CreateReservedIP creates a new reserved IP on Vultr account -func (c *Client) CreateReservedIP(regionID int, ipType string, label string) (string, error) { - values := url.Values{ - "DCID": {fmt.Sprintf("%v", regionID)}, - "ip_type": {ipType}, - } - if len(label) > 0 { - values.Add("label", label) - } - - result := IP{} - err := c.post(`reservedip/create`, values, &result) - if err != nil { - return "", err - } - return result.ID, nil -} - -// DestroyReservedIP deletes an existing reserved IP -func (c *Client) DestroyReservedIP(id string) error { - values := url.Values{ - "SUBID": {id}, - } - return c.post(`reservedip/destroy`, values, nil) -} - -// AttachReservedIP attaches a reserved IP to a virtual machine -func (c *Client) AttachReservedIP(ip string, serverID string) error { - values := url.Values{ - "ip_address": {ip}, - "attach_SUBID": {serverID}, - } - return c.post(`reservedip/attach`, values, nil) -} - -// DetachReservedIP detaches a reserved IP from an existing virtual machine -func (c *Client) DetachReservedIP(serverID string, ip string) error { - values := url.Values{ - "ip_address": {ip}, - "detach_SUBID": {serverID}, - } - return c.post(`reservedip/detach`, values, nil) -} - -// ConvertReservedIP converts an existing virtual machines IP to a reserved IP -func (c *Client) ConvertReservedIP(serverID string, ip string) (string, error) { - values := url.Values{ - "SUBID": {serverID}, - "ip_address": {ip}, - } - - result := IP{} - err := c.post(`reservedip/convert`, values, &result) - if err != nil { - return "", err - } - return result.ID, err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/scripts.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/scripts.go deleted file mode 100644 index d6639cf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/scripts.go +++ /dev/null @@ -1,126 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net/url" - "sort" - "strings" -) - -// StartupScript on Vultr account -type StartupScript struct { - ID string `json:"SCRIPTID"` - Name string `json:"name"` - Type string `json:"type"` - Content string `json:"script"` -} - -type startupscripts []StartupScript - -func (s startupscripts) Len() int { return len(s) } -func (s startupscripts) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s startupscripts) Less(i, j int) bool { - return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) -} - -// UnmarshalJSON implements json.Unmarshaller on StartupScript. -// Necessary because the SCRIPTID field has inconsistent types. -func (s *StartupScript) UnmarshalJSON(data []byte) (err error) { - if s == nil { - *s = StartupScript{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - s.ID = fmt.Sprintf("%v", fields["SCRIPTID"]) - s.Name = fmt.Sprintf("%v", fields["name"]) - s.Type = fmt.Sprintf("%v", fields["type"]) - s.Content = fmt.Sprintf("%v", fields["script"]) - - return -} - -// GetStartupScripts returns a list of all startup scripts on the current Vultr account -func (c *Client) GetStartupScripts() (scripts []StartupScript, err error) { - var scriptMap map[string]StartupScript - if err := c.get(`startupscript/list`, &scriptMap); err != nil { - return nil, err - } - - for _, script := range scriptMap { - if script.Type == "" { - script.Type = "boot" // set default script type - } - scripts = append(scripts, script) - } - sort.Sort(startupscripts(scripts)) - return scripts, nil -} - -// GetStartupScript returns the startup script with the given ID -func (c *Client) GetStartupScript(id string) (StartupScript, error) { - scripts, err := c.GetStartupScripts() - if err != nil { - return StartupScript{}, err - } - - for _, s := range scripts { - if s.ID == id { - return s, nil - } - } - return StartupScript{}, nil -} - -// CreateStartupScript creates a new startup script -func (c *Client) CreateStartupScript(name, content, scriptType string) (StartupScript, error) { - values := url.Values{ - "name": {name}, - "script": {content}, - "type": {scriptType}, - } - - var script StartupScript - if err := c.post(`startupscript/create`, values, &script); err != nil { - return StartupScript{}, err - } - script.Name = name - script.Content = content - script.Type = scriptType - - return script, nil -} - -// UpdateStartupScript updates an existing startup script -func (c *Client) UpdateStartupScript(script StartupScript) error { - values := url.Values{ - "SCRIPTID": {script.ID}, - } - if script.Name != "" { - values.Add("name", script.Name) - } - if script.Content != "" { - values.Add("script", script.Content) - } - - if err := c.post(`startupscript/update`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteStartupScript deletes an existing startup script from Vultr account -func (c *Client) DeleteStartupScript(id string) error { - values := url.Values{ - "SCRIPTID": {id}, - } - - if err := c.post(`startupscript/destroy`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/servers.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/servers.go deleted file mode 100644 index 418198a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/servers.go +++ /dev/null @@ -1,561 +0,0 @@ -package lib - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "net/url" - "sort" - "strconv" - "strings" -) - -// Server (virtual machine) on Vultr account -type Server struct { - ID string `json:"SUBID"` - Name string `json:"label"` - OS string `json:"os"` - RAM string `json:"ram"` - Disk string `json:"disk"` - MainIP string `json:"main_ip"` - VCpus int `json:"vcpu_count,string"` - Location string `json:"location"` - RegionID int `json:"DCID,string"` - DefaultPassword string `json:"default_password"` - Created string `json:"date_created"` - PendingCharges float64 `json:"pending_charges"` - Status string `json:"status"` - Cost string `json:"cost_per_month"` - CurrentBandwidth float64 `json:"current_bandwidth_gb"` - AllowedBandwidth float64 `json:"allowed_bandwidth_gb,string"` - NetmaskV4 string `json:"netmask_v4"` - GatewayV4 string `json:"gateway_v4"` - PowerStatus string `json:"power_status"` - ServerState string `json:"server_state"` - PlanID int `json:"VPSPLANID,string"` - V6Networks []V6Network `json:"v6_networks"` - InternalIP string `json:"internal_ip"` - KVMUrl string `json:"kvm_url"` - AutoBackups string `json:"auto_backups"` - Tag string `json:"tag"` - OSID string `json:"OSID"` - AppID string `json:"APPID"` - FirewallGroupID string `json:"FIREWALLGROUPID"` -} - -// ServerOptions are optional parameters to be used during server creation -type ServerOptions struct { - IPXEChainURL string - ISO int - Script int - UserData string - Snapshot string - SSHKey string - ReservedIP string - IPV6 bool - PrivateNetworking bool - AutoBackups bool - DontNotifyOnActivate bool - Hostname string - Tag string - AppID string - FirewallGroupID string -} - -type servers []Server - -func (s servers) Len() int { return len(s) } -func (s servers) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s servers) Less(i, j int) bool { - // sort order: name, ip - if strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) { - return true - } else if strings.ToLower(s[i].Name) > strings.ToLower(s[j].Name) { - return false - } - return s[i].MainIP < s[j].MainIP -} - -// V6Network represents a IPv6 network of a Vultr server -type V6Network struct { - Network string `json:"v6_network"` - MainIP string `json:"v6_main_ip"` - NetworkSize string `json:"v6_network_size"` -} - -// ISOStatus represents an ISO image attached to a Vultr server -type ISOStatus struct { - State string `json:"state"` - ISOID string `json:"ISOID"` -} - -// UnmarshalJSON implements json.Unmarshaller on Server. -// This is needed because the Vultr API is inconsistent in it's JSON responses for servers. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (s *Server) UnmarshalJSON(data []byte) (err error) { - if s == nil { - *s = Server{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["vcpu_count"]) - if len(value) == 0 || value == "" { - value = "0" - } - vcpu, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - s.VCpus = int(vcpu) - - value = fmt.Sprintf("%v", fields["DCID"]) - if len(value) == 0 || value == "" { - value = "0" - } - region, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - s.RegionID = int(region) - - value = fmt.Sprintf("%v", fields["VPSPLANID"]) - if len(value) == 0 || value == "" { - value = "0" - } - plan, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - s.PlanID = int(plan) - - value = fmt.Sprintf("%v", fields["pending_charges"]) - if len(value) == 0 || value == "" { - value = "0" - } - pc, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - s.PendingCharges = pc - - value = fmt.Sprintf("%v", fields["current_bandwidth_gb"]) - if len(value) == 0 || value == "" { - value = "0" - } - cb, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - s.CurrentBandwidth = cb - - value = fmt.Sprintf("%v", fields["allowed_bandwidth_gb"]) - if len(value) == 0 || value == "" { - value = "0" - } - ab, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - s.AllowedBandwidth = ab - - value = fmt.Sprintf("%v", fields["OSID"]) - if value == "" { - value = "" - } - s.OSID = value - - value = fmt.Sprintf("%v", fields["APPID"]) - if value == "" || value == "0" { - value = "" - } - s.AppID = value - - value = fmt.Sprintf("%v", fields["FIREWALLGROUPID"]) - if value == "" || value == "0" { - value = "" - } - s.FirewallGroupID = value - - s.ID = fmt.Sprintf("%v", fields["SUBID"]) - s.Name = fmt.Sprintf("%v", fields["label"]) - s.OS = fmt.Sprintf("%v", fields["os"]) - s.RAM = fmt.Sprintf("%v", fields["ram"]) - s.Disk = fmt.Sprintf("%v", fields["disk"]) - s.MainIP = fmt.Sprintf("%v", fields["main_ip"]) - s.Location = fmt.Sprintf("%v", fields["location"]) - s.DefaultPassword = fmt.Sprintf("%v", fields["default_password"]) - s.Created = fmt.Sprintf("%v", fields["date_created"]) - s.Status = fmt.Sprintf("%v", fields["status"]) - s.Cost = fmt.Sprintf("%v", fields["cost_per_month"]) - s.NetmaskV4 = fmt.Sprintf("%v", fields["netmask_v4"]) - s.GatewayV4 = fmt.Sprintf("%v", fields["gateway_v4"]) - s.PowerStatus = fmt.Sprintf("%v", fields["power_status"]) - s.ServerState = fmt.Sprintf("%v", fields["server_state"]) - - v6networks := make([]V6Network, 0) - if networks, ok := fields["v6_networks"].([]interface{}); ok { - for _, network := range networks { - if network, ok := network.(map[string]interface{}); ok { - v6network := V6Network{ - Network: fmt.Sprintf("%v", network["v6_network"]), - MainIP: fmt.Sprintf("%v", network["v6_main_ip"]), - NetworkSize: fmt.Sprintf("%v", network["v6_network_size"]), - } - v6networks = append(v6networks, v6network) - } - } - s.V6Networks = v6networks - } - - s.InternalIP = fmt.Sprintf("%v", fields["internal_ip"]) - s.KVMUrl = fmt.Sprintf("%v", fields["kvm_url"]) - s.AutoBackups = fmt.Sprintf("%v", fields["auto_backups"]) - s.Tag = fmt.Sprintf("%v", fields["tag"]) - - return -} - -// GetServers returns a list of current virtual machines on Vultr account -func (c *Client) GetServers() (serverList []Server, err error) { - var serverMap map[string]Server - if err := c.get(`server/list`, &serverMap); err != nil { - return nil, err - } - - for _, server := range serverMap { - serverList = append(serverList, server) - } - sort.Sort(servers(serverList)) - return serverList, nil -} - -// GetServersByTag returns a list of all virtual machines matching by tag -func (c *Client) GetServersByTag(tag string) (serverList []Server, err error) { - var serverMap map[string]Server - if err := c.get(`server/list?tag=`+tag, &serverMap); err != nil { - return nil, err - } - - for _, server := range serverMap { - serverList = append(serverList, server) - } - sort.Sort(servers(serverList)) - return serverList, nil -} - -// GetServer returns the virtual machine with the given ID -func (c *Client) GetServer(id string) (server Server, err error) { - if err := c.get(`server/list?SUBID=`+id, &server); err != nil { - return Server{}, err - } - return server, nil -} - -// CreateServer creates a new virtual machine on Vultr. ServerOptions are optional settings. -func (c *Client) CreateServer(name string, regionID, planID, osID int, options *ServerOptions) (Server, error) { - values := url.Values{ - "label": {name}, - "DCID": {fmt.Sprintf("%v", regionID)}, - "VPSPLANID": {fmt.Sprintf("%v", planID)}, - "OSID": {fmt.Sprintf("%v", osID)}, - } - - if options != nil { - if options.IPXEChainURL != "" { - values.Add("ipxe_chain_url", options.IPXEChainURL) - } - - if options.ISO != 0 { - values.Add("ISOID", fmt.Sprintf("%v", options.ISO)) - } - - if options.Script != 0 { - values.Add("SCRIPTID", fmt.Sprintf("%v", options.Script)) - } - - if options.UserData != "" { - values.Add("userdata", base64.StdEncoding.EncodeToString([]byte(options.UserData))) - } - - if options.Snapshot != "" { - values.Add("SNAPSHOTID", options.Snapshot) - } - - if options.SSHKey != "" { - values.Add("SSHKEYID", options.SSHKey) - } - - if options.ReservedIP != "" { - values.Add("reserved_ip_v4", options.ReservedIP) - } - - values.Add("enable_ipv6", "no") - if options.IPV6 { - values.Set("enable_ipv6", "yes") - } - - values.Add("enable_private_network", "no") - if options.PrivateNetworking { - values.Set("enable_private_network", "yes") - } - - values.Add("auto_backups", "no") - if options.AutoBackups { - values.Set("auto_backups", "yes") - } - - values.Add("notify_activate", "yes") - if options.DontNotifyOnActivate { - values.Set("notify_activate", "no") - } - - if options.Hostname != "" { - values.Add("hostname", options.Hostname) - } - - if options.Tag != "" { - values.Add("tag", options.Tag) - } - - if options.AppID != "" { - values.Add("APPID", options.AppID) - } - - if options.FirewallGroupID != "" { - values.Add("FIREWALLGROUPID", options.FirewallGroupID) - } - } - - var server Server - if err := c.post(`server/create`, values, &server); err != nil { - return Server{}, err - } - server.Name = name - server.RegionID = regionID - server.PlanID = planID - - return server, nil -} - -// RenameServer renames an existing virtual machine -func (c *Client) RenameServer(id, name string) error { - values := url.Values{ - "SUBID": {id}, - "label": {name}, - } - - if err := c.post(`server/label_set`, values, nil); err != nil { - return err - } - return nil -} - -// TagServer replaces the tag on an existing virtual machine -func (c *Client) TagServer(id, tag string) error { - values := url.Values{ - "SUBID": {id}, - "tag": {tag}, - } - - if err := c.post(`server/tag_set`, values, nil); err != nil { - return err - } - return nil -} - -// StartServer starts an existing virtual machine -func (c *Client) StartServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/start`, values, nil); err != nil { - return err - } - return nil -} - -// HaltServer stops an existing virtual machine -func (c *Client) HaltServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/halt`, values, nil); err != nil { - return err - } - return nil -} - -// RebootServer reboots an existing virtual machine -func (c *Client) RebootServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/reboot`, values, nil); err != nil { - return err - } - return nil -} - -// ReinstallServer reinstalls the operating system on an existing virtual machine -func (c *Client) ReinstallServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/reinstall`, values, nil); err != nil { - return err - } - return nil -} - -// ChangeOSofServer changes the virtual machine to a different operating system -func (c *Client) ChangeOSofServer(id string, osID int) error { - values := url.Values{ - "SUBID": {id}, - "OSID": {fmt.Sprintf("%v", osID)}, - } - - if err := c.post(`server/os_change`, values, nil); err != nil { - return err - } - return nil -} - -// ListOSforServer lists all available operating systems to which an existing virtual machine can be changed -func (c *Client) ListOSforServer(id string) (os []OS, err error) { - var osMap map[string]OS - if err := c.get(`server/os_change_list?SUBID=`+id, &osMap); err != nil { - return nil, err - } - - for _, o := range osMap { - os = append(os, o) - } - sort.Sort(oses(os)) - return os, nil -} - -// AttachISOtoServer attaches an ISO image to an existing virtual machine and reboots it -func (c *Client) AttachISOtoServer(id string, isoID int) error { - values := url.Values{ - "SUBID": {id}, - "ISOID": {fmt.Sprintf("%v", isoID)}, - } - - if err := c.post(`server/iso_attach`, values, nil); err != nil { - return err - } - return nil -} - -// DetachISOfromServer detaches the currently mounted ISO image from the virtual machine and reboots it -func (c *Client) DetachISOfromServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/iso_detach`, values, nil); err != nil { - return err - } - return nil -} - -// GetISOStatusofServer retrieves the current ISO image state of an existing virtual machine -func (c *Client) GetISOStatusofServer(id string) (isoStatus ISOStatus, err error) { - if err := c.get(`server/iso_status?SUBID=`+id, &isoStatus); err != nil { - return ISOStatus{}, err - } - return isoStatus, nil -} - -// DeleteServer deletes an existing virtual machine -func (c *Client) DeleteServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/destroy`, values, nil); err != nil { - return err - } - return nil -} - -// SetFirewallGroup adds a virtual machine to a firewall group -func (c *Client) SetFirewallGroup(id, firewallgroup string) error { - values := url.Values{ - "SUBID": {id}, - "FIREWALLGROUPID": {firewallgroup}, - } - - if err := c.post(`server/firewall_group_set`, values, nil); err != nil { - return err - } - return nil -} - -// UnsetFirewallGroup removes a virtual machine from a firewall group -func (c *Client) UnsetFirewallGroup(id string) error { - return c.SetFirewallGroup(id, "0") -} - -// BandwidthOfServer retrieves the bandwidth used by a virtual machine -func (c *Client) BandwidthOfServer(id string) (bandwidth []map[string]string, err error) { - var bandwidthMap map[string][][]string - if err := c.get(`server/bandwidth?SUBID=`+id, &bandwidthMap); err != nil { - return nil, err - } - - // parse incoming bytes - for _, b := range bandwidthMap["incoming_bytes"] { - bMap := make(map[string]string) - bMap["date"] = b[0] - bMap["incoming"] = b[1] - bandwidth = append(bandwidth, bMap) - } - - // parse outgoing bytes (we'll assume that incoming and outgoing dates are always a match) - for _, b := range bandwidthMap["outgoing_bytes"] { - for i := range bandwidth { - if bandwidth[i]["date"] == b[0] { - bandwidth[i]["outgoing"] = b[1] - break - } - } - } - - return bandwidth, nil -} - -// ChangeApplicationofServer changes the virtual machine to a different application -func (c *Client) ChangeApplicationofServer(id string, appID string) error { - values := url.Values{ - "SUBID": {id}, - "APPID": {appID}, - } - - if err := c.post(`server/app_change`, values, nil); err != nil { - return err - } - return nil -} - -// ListApplicationsforServer lists all available operating systems to which an existing virtual machine can be changed -func (c *Client) ListApplicationsforServer(id string) (apps []Application, err error) { - var appMap map[string]Application - if err := c.get(`server/app_change_list?SUBID=`+id, &appMap); err != nil { - return nil, err - } - - for _, app := range appMap { - apps = append(apps, app) - } - sort.Sort(applications(apps)) - return apps, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/snapshots.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/snapshots.go deleted file mode 100644 index 7e99693..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/snapshots.go +++ /dev/null @@ -1,72 +0,0 @@ -package lib - -import ( - "net/url" - "sort" - "strings" -) - -// Snapshot of a virtual machine on Vultr account -type Snapshot struct { - ID string `json:"SNAPSHOTID"` - Description string `json:"description"` - Size string `json:"size"` - Status string `json:"status"` - Created string `json:"date_created"` -} - -type snapshots []Snapshot - -func (s snapshots) Len() int { return len(s) } -func (s snapshots) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s snapshots) Less(i, j int) bool { - // sort order: description, created - if strings.ToLower(s[i].Description) < strings.ToLower(s[j].Description) { - return true - } else if strings.ToLower(s[i].Description) > strings.ToLower(s[j].Description) { - return false - } - return s[i].Created < s[j].Created -} - -// GetSnapshots retrieves a list of all snapshots on Vultr account -func (c *Client) GetSnapshots() (snapshotList []Snapshot, err error) { - var snapshotMap map[string]Snapshot - if err := c.get(`snapshot/list`, &snapshotMap); err != nil { - return nil, err - } - - for _, snapshot := range snapshotMap { - snapshotList = append(snapshotList, snapshot) - } - sort.Sort(snapshots(snapshotList)) - return snapshotList, nil -} - -// CreateSnapshot creates a new virtual machine snapshot -func (c *Client) CreateSnapshot(id, description string) (Snapshot, error) { - values := url.Values{ - "SUBID": {id}, - "description": {description}, - } - - var snapshot Snapshot - if err := c.post(`snapshot/create`, values, &snapshot); err != nil { - return Snapshot{}, err - } - snapshot.Description = description - - return snapshot, nil -} - -// DeleteSnapshot deletes an existing virtual machine snapshot -func (c *Client) DeleteSnapshot(id string) error { - values := url.Values{ - "SNAPSHOTID": {id}, - } - - if err := c.post(`snapshot/destroy`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/sshkeys.go b/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/sshkeys.go deleted file mode 100644 index 006e16f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/JamesClonk/vultr/lib/sshkeys.go +++ /dev/null @@ -1,82 +0,0 @@ -package lib - -import ( - "net/url" - "sort" - "strings" -) - -// SSHKey on Vultr account -type SSHKey struct { - ID string `json:"SSHKEYID"` - Name string `json:"name"` - Key string `json:"ssh_key"` - Created string `json:"date_created"` -} - -type sshkeys []SSHKey - -func (s sshkeys) Len() int { return len(s) } -func (s sshkeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s sshkeys) Less(i, j int) bool { return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) } - -// GetSSHKeys returns a list of SSHKeys from Vultr account -func (c *Client) GetSSHKeys() (keys []SSHKey, err error) { - var keyMap map[string]SSHKey - if err := c.get(`sshkey/list`, &keyMap); err != nil { - return nil, err - } - - for _, key := range keyMap { - keys = append(keys, key) - } - sort.Sort(sshkeys(keys)) - return keys, nil -} - -// CreateSSHKey creates new SSHKey on Vultr -func (c *Client) CreateSSHKey(name, key string) (SSHKey, error) { - values := url.Values{ - "name": {name}, - "ssh_key": {key}, - } - - var sshKey SSHKey - if err := c.post(`sshkey/create`, values, &sshKey); err != nil { - return SSHKey{}, err - } - sshKey.Name = name - sshKey.Key = key - - return sshKey, nil -} - -// UpdateSSHKey updates an existing SSHKey entry -func (c *Client) UpdateSSHKey(key SSHKey) error { - values := url.Values{ - "SSHKEYID": {key.ID}, - } - if key.Name != "" { - values.Add("name", key.Name) - } - if key.Key != "" { - values.Add("ssh_key", key.Key) - } - - if err := c.post(`sshkey/update`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteSSHKey deletes an existing SSHKey from Vultr account -func (c *Client) DeleteSSHKey(id string) error { - values := url.Values{ - "SSHKEYID": {id}, - } - - if err := c.post(`sshkey/destroy`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/LICENSE deleted file mode 100644 index f9361e3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2018, Cisco Systems, Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/client.go deleted file mode 100644 index 2109656..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/client.go +++ /dev/null @@ -1,71 +0,0 @@ -package vegadns2client - -import ( - "fmt" - "net/http" - "net/url" - "strings" -) - -// VegaDNSClient - Struct for holding VegaDNSClient specific attributes -type VegaDNSClient struct { - client http.Client - baseurl string - version string - User string - Pass string - APIKey string - APISecret string - token Token -} - -// Send - Central place for sending requests -// Input: method, endpoint, params -// Output: *http.Response -func (vega *VegaDNSClient) Send(method string, endpoint string, params map[string]string) (*http.Response, error) { - vegaURL := vega.getURL(endpoint) - - p := url.Values{} - for k, v := range params { - p.Set(k, v) - } - - var err error - var req *http.Request - - if (method == "GET") || (method == "DELETE") { - vegaURL = fmt.Sprintf("%s?%s", vegaURL, p.Encode()) - req, err = http.NewRequest(method, vegaURL, nil) - } else { - req, err = http.NewRequest(method, vegaURL, strings.NewReader(p.Encode())) - } - - if err != nil { - return nil, fmt.Errorf("Error preparing request: %s", err) - } - - if vega.User != "" && vega.Pass != "" { - // Basic Auth - req.SetBasicAuth(vega.User, vega.Pass) - } else if vega.APIKey != "" && vega.APISecret != "" { - // OAuth - vega.getAuthToken() - err = vega.token.valid() - if err != nil { - return nil, err - } - req.Header.Set("Authorization", vega.getBearer()) - } - - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - return vega.client.Do(req) -} - -func (vega *VegaDNSClient) getURL(endpoint string) string { - return fmt.Sprintf("%s/%s/%s", vega.baseurl, vega.version, endpoint) -} - -func (vega *VegaDNSClient) stillAuthorized() error { - return vega.token.valid() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/domains.go deleted file mode 100644 index b9713f4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/domains.go +++ /dev/null @@ -1,80 +0,0 @@ -package vegadns2client - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "strings" -) - -// Domain - struct containing a domain object -type Domain struct { - Status string `json:"status"` - Domain string `json:"domain"` - DomainID int `json:"domain_id"` - OwnerID int `json:"owner_id"` -} - -// DomainResponse - api response of a domain list -type DomainResponse struct { - Status string `json:"status"` - Total int `json:"total_domains"` - Domains []Domain `json:"domains"` -} - -// GetDomainID - returns the id for a domain -// Input: domain -// Output: int, err -func (vega *VegaDNSClient) GetDomainID(domain string) (int, error) { - params := make(map[string]string) - params["search"] = domain - - resp, err := vega.Send("GET", "domains", params) - - if err != nil { - return -1, fmt.Errorf("Error sending GET to GetDomainID: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return -1, fmt.Errorf("Error reading response from GET to GetDomainID: %s", err) - } - if resp.StatusCode != http.StatusOK { - return -1, fmt.Errorf("Got bad answer from VegaDNS on GetDomainID. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - answer := DomainResponse{} - if err := json.Unmarshal(body, &answer); err != nil { - return -1, fmt.Errorf("Error unmarshalling body from GetDomainID: %s", err) - } - log.Println(answer) - for _, d := range answer.Domains { - if d.Domain == domain { - return d.DomainID, nil - } - } - - return -1, fmt.Errorf("Didnt find domain %s", domain) - -} - -// GetAuthZone retrieves the closest match to a given -// domain. Example: Given an argument "a.b.c.d.e", and a VegaDNS -// hosted domain of "c.d.e", GetClosestMatchingDomain will return -// "c.d.e". -func (vega *VegaDNSClient) GetAuthZone(fqdn string) (string, int, error) { - fqdn = strings.TrimSuffix(fqdn, ".") - numComponents := len(strings.Split(fqdn, ".")) - for i := 1; i < numComponents; i++ { - tmpHostname := strings.SplitN(fqdn, ".", i)[i-1] - log.Printf("tmpHostname for i = %d: %s\n", i, tmpHostname) - if domainID, err := vega.GetDomainID(tmpHostname); err == nil { - log.Printf("Found zone: %s\n\tShortened to %s\n", tmpHostname, strings.TrimSuffix(tmpHostname, ".")) - return strings.TrimSuffix(tmpHostname, "."), domainID, nil - } - } - log.Println("Unable to find hosted zone in vegadns") - return "", -1, fmt.Errorf("Unable to find auth zone for fqdn %s", fqdn) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/main.go b/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/main.go deleted file mode 100644 index 0d3e79a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/main.go +++ /dev/null @@ -1,19 +0,0 @@ -package vegadns2client - -import ( - "net/http" - "time" -) - -// NewVegaDNSClient - helper to instantiate a client -// Input: url string -// Output: VegaDNSClient -func NewVegaDNSClient(url string) VegaDNSClient { - httpClient := http.Client{Timeout: 15 * time.Second} - return VegaDNSClient{ - client: httpClient, - baseurl: url, - version: "1.0", - token: Token{}, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/records.go b/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/records.go deleted file mode 100644 index 36bd8d9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/records.go +++ /dev/null @@ -1,113 +0,0 @@ -package vegadns2client - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strings" -) - -// Record - struct representing a Record object -type Record struct { - Name string `json:"name"` - Value string `json:"value"` - RecordType string `json:"record_type"` - TTL int `json:"ttl"` - RecordID int `json:"record_id"` - LocationID string `json:"location_id"` - DomainID int `json:"domain_id"` -} - -// RecordsResponse - api response list of records -type RecordsResponse struct { - Status string `json:"status"` - Total int `json:"total_records"` - Domain Domain `json:"domain"` - Records []Record `json:"records"` -} - -// GetRecordID - helper to get the id of a record -// Input: domainID, record, recordType -// Output: int -func (vega *VegaDNSClient) GetRecordID(domainID int, record string, recordType string) (int, error) { - params := make(map[string]string) - params["domain_id"] = fmt.Sprintf("%d", domainID) - - resp, err := vega.Send("GET", "records", params) - - if err != nil { - return -1, fmt.Errorf("Error sending GET to GetRecordID: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return -1, fmt.Errorf("Error reading response from GetRecordID: %s", err) - } - if resp.StatusCode != http.StatusOK { - return -1, fmt.Errorf("Got bad answer from VegaDNS on GetRecordID. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - answer := RecordsResponse{} - if err := json.Unmarshal(body, &answer); err != nil { - return -1, fmt.Errorf("Error unmarshalling body from GetRecordID: %s", err) - } - - for _, r := range answer.Records { - if r.Name == record && r.RecordType == recordType { - return r.RecordID, nil - } - } - - return -1, errors.New("Couldnt find record") -} - -// CreateTXT - Creates a TXT record -// Input: domainID, fqdn, value, ttl -// Output: nil or error -func (vega *VegaDNSClient) CreateTXT(domainID int, fqdn string, value string, ttl int) error { - params := make(map[string]string) - - params["record_type"] = "TXT" - params["ttl"] = fmt.Sprintf("%d", ttl) - params["domain_id"] = fmt.Sprintf("%d", domainID) - params["name"] = strings.TrimSuffix(fqdn, ".") - params["value"] = value - - resp, err := vega.Send("POST", "records", params) - - if err != nil { - return fmt.Errorf("Send POST error in CreateTXT: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("Error reading POST response in CreateTXT: %s", err) - } - if resp.StatusCode != http.StatusCreated { - return fmt.Errorf("Got bad answer from VegaDNS on CreateTXT. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - return nil -} - -// DeleteRecord - deletes a record by id -// Input: recordID -// Output: nil or error -func (vega *VegaDNSClient) DeleteRecord(recordID int) error { - resp, err := vega.Send("DELETE", fmt.Sprintf("records/%d", recordID), nil) - if err != nil { - return fmt.Errorf("Send DELETE error in DeleteTXT: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("Error reading DELETE response in DeleteTXT: %s", err) - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Got bad answer from VegaDNS on DeleteTXT. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/tokens.go b/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/tokens.go deleted file mode 100644 index 9e7706b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/OpenDNS/vegadns2client/tokens.go +++ /dev/null @@ -1,74 +0,0 @@ -package vegadns2client - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/url" - "strings" - "time" -) - -// Token - struct to hold token information -type Token struct { - Token string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - ExpiresAt time.Time -} - -func (t Token) valid() error { - if time.Now().UTC().After(t.ExpiresAt) { - return errors.New("Token Expired") - } - return nil -} - -func (vega *VegaDNSClient) getBearer() string { - if vega.token.valid() != nil { - vega.getAuthToken() - } - return vega.token.formatBearer() -} - -func (t Token) formatBearer() string { - return fmt.Sprintf("Bearer %s", t.Token) -} - -func (vega *VegaDNSClient) getAuthToken() { - tokenEndpoint := vega.getURL("token") - v := url.Values{} - v.Set("grant_type", "client_credentials") - - req, err := http.NewRequest("POST", tokenEndpoint, strings.NewReader(v.Encode())) - if err != nil { - log.Fatalf("Error forming POST to getAuthToken: %s", err) - } - req.SetBasicAuth(vega.APIKey, vega.APISecret) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - issueTime := time.Now().UTC() - resp, err := vega.client.Do(req) - if err != nil { - log.Fatalf("Error sending POST to getAuthToken: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - log.Fatalf("Error reading response from POST to getAuthToken: %s", err) - } - if resp.StatusCode != http.StatusOK { - log.Fatalf("Got bad answer from VegaDNS on getAuthToken. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - if err := json.Unmarshal(body, &vega.token); err != nil { - log.Fatalf("Error unmarshalling body of POST to getAuthToken: %s", err) - } - - if vega.token.TokenType != "bearer" { - log.Fatal("We don't support anything except bearer tokens") - } - vega.token.ExpiresAt = issueTime.Add(time.Duration(vega.token.ExpiresIn) * time.Second) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/LICENSE deleted file mode 100644 index 8dada3e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/api.go deleted file mode 100644 index d20ce43..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/api.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" -) - -// Resource is the "base" type for all API resources -type Resource struct { - Complete chan bool `json:"-"` -} - -// Init initializes the Complete channel, if it is necessary -// need to create a resource specific Init(), make sure to -// initialize the channel. -func (resource *Resource) Init() { - resource.Complete = make(chan bool, 1) -} - -// PostUnmarshalJSON is a default implementation of the -// PostUnmarshalJSON hook that simply calls Init() and -// sends true to the Complete channel. This is overridden -// in many resources, in particular those that represent -// collections, and have to initialize sub-resources also. -func (resource *Resource) PostUnmarshalJSON() error { - resource.Init() - resource.Complete <- true - return nil -} - -// GetJSON returns the raw (indented) JSON (as []bytes) -func (resource *Resource) GetJSON() ([]byte, error) { - return json.MarshalIndent(resource, "", " ") -} - -// JSONBody is a generic struct for temporary JSON unmarshalling. -type JSONBody map[string]interface{} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/client.go deleted file mode 100644 index abbbcd4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/client.go +++ /dev/null @@ -1,152 +0,0 @@ -// Package client is a simple library for http.Client to sign Akamai OPEN Edgegrid API requests -package client - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1" -) - -var ( - libraryVersion = "0.6.2" - // UserAgent is the User-Agent value sent for all requests - UserAgent = "Akamai-Open-Edgegrid-golang/" + libraryVersion + " golang/" + strings.TrimPrefix(runtime.Version(), "go") - // Client is the *http.Client to use - Client = http.DefaultClient -) - -// NewRequest creates an HTTP request that can be sent to Akamai APIs. A relative URL can be provided in path, which will be resolved to the -// Host specified in Config. If body is specified, it will be sent as the request body. -func NewRequest(config edgegrid.Config, method, path string, body io.Reader) (*http.Request, error) { - var ( - baseURL *url.URL - err error - ) - - if strings.HasPrefix(config.Host, "https://") { - baseURL, err = url.Parse(config.Host) - } else { - baseURL, err = url.Parse("https://" + config.Host) - } - - if err != nil { - return nil, err - } - - rel, err := url.Parse(strings.TrimPrefix(path, "/")) - if err != nil { - return nil, err - } - - u := baseURL.ResolveReference(rel) - - req, err := http.NewRequest(method, u.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("User-Agent", UserAgent) - - return req, nil -} - -// NewJSONRequest creates an HTTP request that can be sent to the Akamai APIs with a JSON body -// The JSON body is encoded and the Content-Type/Accept headers are set automatically. -func NewJSONRequest(config edgegrid.Config, method, path string, body interface{}) (*http.Request, error) { - var req *http.Request - var err error - - if body != nil { - jsonBody, err := jsonhooks.Marshal(body) - if err != nil { - return nil, err - } - - buf := bytes.NewReader(jsonBody) - req, err = NewRequest(config, method, path, buf) - } else { - req, err = NewRequest(config, method, path, nil) - } - - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json,*/*") - - return req, nil -} - -// NewMultiPartFormDataRequest creates an HTTP request that uploads a file to the Akamai API -func NewMultiPartFormDataRequest(config edgegrid.Config, uriPath, filePath string, otherFormParams map[string]string) (*http.Request, error) { - file, err := os.Open(filePath) - if err != nil { - return nil, err - } - defer file.Close() - - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - // TODO: make this field name configurable - part, err := writer.CreateFormFile("importFile", filepath.Base(filePath)) - if err != nil { - return nil, err - } - _, err = io.Copy(part, file) - - for key, val := range otherFormParams { - _ = writer.WriteField(key, val) - } - err = writer.Close() - if err != nil { - return nil, err - } - - req, err := NewRequest(config, "POST", uriPath, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - return req, err -} - -// Do performs a given HTTP Request, signed with the Akamai OPEN Edgegrid -// Authorization header. An edgegrid.Response or an error is returned. -func Do(config edgegrid.Config, req *http.Request) (*http.Response, error) { - Client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - req = edgegrid.AddRequestHeader(config, req) - return nil - } - - req = edgegrid.AddRequestHeader(config, req) - res, err := Client.Do(req) - if err != nil { - return nil, err - } - - return res, nil -} - -// BodyJSON unmarshals the Response.Body into a given data structure -func BodyJSON(r *http.Response, data interface{}) error { - if data == nil { - return errors.New("You must pass in an interface{}") - } - - body, err := ioutil.ReadAll(r.Body) - if err != nil { - return err - } - err = jsonhooks.Unmarshal(body, data) - - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/errors.go deleted file mode 100644 index 05b8524..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/errors.go +++ /dev/null @@ -1,107 +0,0 @@ -package client - -import ( - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1" -) - -// APIError exposes an Akamai OPEN Edgegrid Error -type APIError struct { - error - Type string `json:"type"` - Title string `json:"title"` - Status int `json:"status"` - Detail string `json:"detail"` - Errors []APIErrorDetail `json:"errors"` - Problems []APIErrorDetail `json:"problems"` - Instance string `json:"instance"` - Method string `json:"method"` - ServerIP string `json:"serverIp"` - ClientIP string `json:"clientIp"` - RequestID string `json:"requestId"` - RequestTime string `json:"requestTime"` - Response *http.Response `json:"-"` - RawBody string `json:"-"` -} - -type APIErrorDetail struct { - Type string `json:"type"` - Title string `json:"title"` - Detail string `json:"detail"` - RejectedValue string `json:"rejectedValue"` -} - -func (error APIError) Error() string { - var errorDetails string - if len(error.Errors) > 0 { - for _, e := range error.Errors { - errorDetails = fmt.Sprintf("%s \n %s", errorDetails, e) - } - } - if len(error.Problems) > 0 { - for _, e := range error.Problems { - errorDetails = fmt.Sprintf("%s \n %s", errorDetails, e) - } - } - return strings.TrimSpace(fmt.Sprintf("API Error: %d %s %s More Info %s\n %s", error.Status, error.Title, error.Detail, error.Type, errorDetails)) -} - -// NewAPIError creates a new API error based on a Response, -// or http.Response-like. -func NewAPIError(response *http.Response) APIError { - // TODO: handle this error - body, _ := ioutil.ReadAll(response.Body) - - return NewAPIErrorFromBody(response, body) -} - -// NewAPIErrorFromBody creates a new API error, allowing you to pass in a body -// -// This function is intended to be used after the body has already been read for -// other purposes. -func NewAPIErrorFromBody(response *http.Response, body []byte) APIError { - error := APIError{} - if err := jsonhooks.Unmarshal(body, &error); err == nil { - error.Status = response.StatusCode - error.Title = response.Status - } - - error.Response = response - error.RawBody = string(body) - - return error -} - -// IsInformational determines if a response was informational (1XX status) -func IsInformational(r *http.Response) bool { - return r.StatusCode > 99 && r.StatusCode < 200 -} - -// IsSuccess determines if a response was successful (2XX status) -func IsSuccess(r *http.Response) bool { - return r.StatusCode > 199 && r.StatusCode < 300 -} - -// IsRedirection determines if a response was a redirect (3XX status) -func IsRedirection(r *http.Response) bool { - return r.StatusCode > 299 && r.StatusCode < 400 -} - -// IsClientError determines if a response was a client error (4XX status) -func IsClientError(r *http.Response) bool { - return r.StatusCode > 399 && r.StatusCode < 500 -} - -// IsServerError determines if a response was a server error (5XX status) -func IsServerError(r *http.Response) bool { - return r.StatusCode > 499 && r.StatusCode < 600 -} - -// IsError determines if the response was a client or server error (4XX or 5XX status) -func IsError(r *http.Response) bool { - return r.StatusCode > 399 && r.StatusCode < 600 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/errors.go deleted file mode 100644 index 06eed5d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/errors.go +++ /dev/null @@ -1,125 +0,0 @@ -package dns - -import ( - "fmt" -) - -type ConfigDNSError interface { - error - Network() bool - NotFound() bool - FailedToSave() bool - ValidationFailed() bool -} - -func IsConfigDNSError(e error) bool { - _, ok := e.(ConfigDNSError) - return ok -} - -type ZoneError struct { - zoneName string - httpErrorMessage string - apiErrorMessage string - err error -} - -func (e *ZoneError) Network() bool { - if e.httpErrorMessage != "" { - return true - } - return false -} - -func (e *ZoneError) NotFound() bool { - if e.err == nil && e.httpErrorMessage == "" && e.apiErrorMessage == "" { - return true - } - return false -} - -func (e *ZoneError) FailedToSave() bool { - return false -} - -func (e *ZoneError) ValidationFailed() bool { - if e.apiErrorMessage != "" { - return true - } - return false -} - -func (e *ZoneError) Error() string { - if e.Network() { - return fmt.Sprintf("Zone \"%s\" network error: [%s]", e.zoneName, e.httpErrorMessage) - } - - if e.NotFound() { - return fmt.Sprintf("Zone \"%s\" not found.", e.zoneName) - } - - if e.FailedToSave() { - return fmt.Sprintf("Zone \"%s\" failed to save: [%s]", e.zoneName, e.err.Error()) - } - - if e.ValidationFailed() { - return fmt.Sprintf("Zone \"%s\" validation failed: [%s]", e.zoneName, e.apiErrorMessage) - } - - if e.err != nil { - return e.err.Error() - } - - return "" -} - -type RecordError struct { - fieldName string - httpErrorMessage string - err error -} - -func (e *RecordError) Network() bool { - if e.httpErrorMessage != "" { - return true - } - return false -} - -func (e *RecordError) NotFound() bool { - return false -} - -func (e *RecordError) FailedToSave() bool { - if e.fieldName == "" { - return true - } - return false -} - -func (e *RecordError) ValidationFailed() bool { - if e.fieldName != "" { - return true - } - return false -} - -func (e *RecordError) Error() string { - if e.Network() { - return fmt.Sprintf("Record network error: [%s]", e.httpErrorMessage) - } - - if e.NotFound() { - return fmt.Sprintf("Record not found.") - } - - if e.FailedToSave() { - return fmt.Sprintf("Record failed to save: [%s]", e.err.Error()) - } - - if e.ValidationFailed() { - return fmt.Sprintf("Record validation failed for field [%s]", e.fieldName) - } - - return "" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/record.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/record.go deleted file mode 100644 index 7a32fe6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/record.go +++ /dev/null @@ -1,1739 +0,0 @@ -package dns - -import ( - "strings" - "time" -) - -// All record types (below) must implement the DNSRecord interface -// This allows the record to be used dynamically in slices - see the Zone struct definition in zone.go -// -// The record types implemented and their fields are as defined here -// https://developer.akamai.com/api/luna/config-dns/data.html -type DNSRecord interface { - // Get the list of allowed fields for this type - GetAllowedFields() []string - // Set a field on the struct, which check for valid fields - SetField(name string, value interface{}) error - // Translate struct properties to a map - ToMap() map[string]interface{} -} - -type ARecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewARecord() *ARecord { - return &ARecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *ARecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *ARecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *ARecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type AaaaRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewAaaaRecord() *AaaaRecord { - return &AaaaRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *AaaaRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *AaaaRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *AaaaRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type AfsdbRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` - Subtype int `json:"subtype,omitempty"` -} - -func NewAfsdbRecord() *AfsdbRecord { - return &AfsdbRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - "subtype", - }, - } -} - -func (record *AfsdbRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *AfsdbRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - case "subtype": - v, ok := value.(int) - if ok { - record.Subtype = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *AfsdbRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - "subtype": record.Subtype, - } -} - -type CnameRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewCnameRecord() *CnameRecord { - return &CnameRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *CnameRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *CnameRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *CnameRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type DnskeyRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Flags int `json:"flags,omitempty"` - Protocol int `json:"protocol,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - Key string `json:"key,omitempty"` -} - -func NewDnskeyRecord() *DnskeyRecord { - return &DnskeyRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "flags", - "protocol", - "algorithm", - "key", - }, - } -} - -func (record *DnskeyRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *DnskeyRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "flags": - v, ok := value.(int) - if ok { - record.Flags = v - return nil - } - case "protocol": - v, ok := value.(int) - if ok { - record.Protocol = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "key": - v, ok := value.(string) - if ok { - record.Key = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *DnskeyRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "flags": record.Flags, - "protocol": record.Protocol, - "algorithm": record.Algorithm, - "key": record.Key, - } -} - -type DsRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Keytag int `json:"keytag,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - DigestType int `json:"digest_type,omitempty"` - Digest string `json:"digest,omitempty"` -} - -func NewDsRecord() *DsRecord { - return &DsRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "keytag", - "algorithm", - "digesttype", - "digest", - }, - } -} - -func (record *DsRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *DsRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "keytag": - v, ok := value.(int) - if ok { - record.Keytag = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "digesttype": - v, ok := value.(int) - if ok { - record.DigestType = v - return nil - } - case "digest": - v, ok := value.(string) - if ok { - record.Digest = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *DsRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "keytag": record.Keytag, - "algorithm": record.Algorithm, - "digesttype": record.DigestType, - "digest": record.DigestType, - } -} - -type HinfoRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Hardware string `json:"hardware,omitempty"` - Software string `json:"software,omitempty"` -} - -func NewHinfoRecord() *HinfoRecord { - return &HinfoRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "hardware", - "software", - }, - } -} - -func (record *HinfoRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *HinfoRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "hardware": - v, ok := value.(string) - if ok { - record.Hardware = v - return nil - } - case "software": - v, ok := value.(string) - if ok { - record.Software = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *HinfoRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "hardware": record.Hardware, - "software": record.Software, - } -} - -type LocRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewLocRecord() *LocRecord { - return &LocRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *LocRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *LocRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *LocRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type MxRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` - Priority int `json:"priority,omitempty"` -} - -func NewMxRecord() *MxRecord { - return &MxRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - "priority", - }, - } -} - -func (record *MxRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *MxRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - case "priority": - v, ok := value.(int) - if ok { - record.Priority = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *MxRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - "priority": record.Priority, - } -} - -type NaptrRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Order uint16 `json:"order,omitempty"` - Preference uint16 `json:"preference,omitempty"` - Flags string `json:"flags,omitempty"` - Service string `json:"service,omitempty"` - Regexp string `json:"regexp,omitempty"` - Replacement string `json:"replacement,omitempty"` -} - -func NewNaptrRecord() *NaptrRecord { - return &NaptrRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "order", - "preference", - "flags", - "service", - "regexp", - "replacement", - }, - } -} - -func (record *NaptrRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *NaptrRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "order": - v, ok := value.(uint16) - if ok { - record.Order = v - return nil - } - case "preference": - v, ok := value.(uint16) - if ok { - record.Preference = v - return nil - } - case "flags": - v, ok := value.(string) - if ok { - record.Flags = v - return nil - } - case "service": - v, ok := value.(string) - if ok { - record.Service = v - return nil - } - case "regexp": - v, ok := value.(string) - if ok { - record.Regexp = v - return nil - } - case "replacement": - v, ok := value.(string) - if ok { - record.Replacement = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *NaptrRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "order": record.Order, - "preference": record.Preference, - "flags": record.Flags, - "service": record.Service, - "regexp": record.Regexp, - "replacement": record.Replacement, - } -} - -type NsRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewNsRecord() *NsRecord { - return &NsRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *NsRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *NsRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *NsRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type Nsec3Record struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - Flags int `json:"flags,omitempty"` - Iterations int `json:"iterations,omitempty"` - Salt string `json:"salt,omitempty"` - NextHashedOwnerName string `json:"next_hashed_owner_name,omitempty"` - TypeBitmaps string `json:"type_bitmaps,omitempty"` -} - -func NewNsec3Record() *Nsec3Record { - return &Nsec3Record{ - fieldMap: []string{ - "name", - "ttl", - "active", - "algorithm", - "flags", - "iterations", - "salt", - "nexthashedownername", - "typebitmaps", - }, - } -} - -func (record *Nsec3Record) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *Nsec3Record) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "flags": - v, ok := value.(int) - if ok { - record.Flags = v - return nil - } - case "iterations": - v, ok := value.(int) - if ok { - record.Iterations = v - return nil - } - case "salt": - v, ok := value.(string) - if ok { - record.Salt = v - return nil - } - case "nexthashedownername": - v, ok := value.(string) - if ok { - record.NextHashedOwnerName = v - return nil - } - case "typebitmaps": - v, ok := value.(string) - if ok { - record.TypeBitmaps = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *Nsec3Record) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "algorithm": record.Algorithm, - "flags": record.Flags, - "iterations": record.Iterations, - "salt": record.Salt, - "nexthashedownername": record.NextHashedOwnerName, - "typebitmaps": record.TypeBitmaps, - } -} - -type Nsec3paramRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - Flags int `json:"flags,omitempty"` - Iterations int `json:"iterations,omitempty"` - Salt string `json:"salt,omitempty"` -} - -func NewNsec3paramRecord() *Nsec3paramRecord { - return &Nsec3paramRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "algorithm", - "flags", - "iterations", - "salt", - }, - } -} - -func (record *Nsec3paramRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *Nsec3paramRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "flags": - v, ok := value.(int) - if ok { - record.Flags = v - return nil - } - case "iterations": - v, ok := value.(int) - if ok { - record.Iterations = v - return nil - } - case "salt": - v, ok := value.(string) - if ok { - record.Salt = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *Nsec3paramRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "algorithm": record.Algorithm, - "flags": record.Flags, - "iterations": record.Iterations, - "salt": record.Salt, - } -} - -type PtrRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewPtrRecord() *PtrRecord { - return &PtrRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *PtrRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *PtrRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *PtrRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type RpRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Mailbox string `json:"mailbox,omitempty"` - Txt string `json:"txt,omitempty"` -} - -func NewRpRecord() *RpRecord { - return &RpRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "mailbox", - "txt", - }, - } -} - -func (record *RpRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *RpRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "mailbox": - v, ok := value.(string) - if ok { - record.Mailbox = v - return nil - } - case "txt": - v, ok := value.(string) - if ok { - record.Txt = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *RpRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "mailbox": record.Mailbox, - "txt": record.Txt, - } -} - -type RrsigRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - TypeCovered string `json:"type_covered,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - OriginalTTL int `json:"original_ttl,omitempty"` - Expiration string `json:"expiration,omitempty"` - Inception string `json:"inception,omitempty"` - Keytag int `json:"keytag,omitempty"` - Signer string `json:"signer,omitempty"` - Signature string `json:"signature,omitempty"` - Labels int `json:"labels,omitempty"` -} - -func NewRrsigRecord() *RrsigRecord { - return &RrsigRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "typecovered", - "algorithm", - "originalttl", - "expiration", - "inception", - "keytag", - "signer", - "signature", - "labels", - }, - } -} - -func (record *RrsigRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *RrsigRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "typecovered": - v, ok := value.(string) - if ok { - record.TypeCovered = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "originalttl": - v, ok := value.(int) - if ok { - record.OriginalTTL = v - return nil - } - case "expiration": - v, ok := value.(string) - if ok { - record.Expiration = v - return nil - } - case "inception": - v, ok := value.(string) - if ok { - record.Inception = v - return nil - } - case "keytag": - v, ok := value.(int) - if ok { - record.Keytag = v - return nil - } - case "signer": - v, ok := value.(string) - if ok { - record.Signer = v - return nil - } - case "signature": - v, ok := value.(string) - if ok { - record.Signature = v - return nil - } - case "labels": - v, ok := value.(int) - if ok { - record.Labels = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *RrsigRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "typecovered": record.TypeCovered, - "algorithm": record.Algorithm, - "originalttl": record.OriginalTTL, - "expiration": record.Expiration, - "inception": record.Inception, - "keytag": record.Keytag, - "signer": record.Signer, - "signature": record.Signature, - "labels": record.Labels, - } -} - -type SoaRecord struct { - fieldMap []string `json:"-"` - originalSerial uint `json:"-"` - TTL int `json:"ttl,omitempty"` - Originserver string `json:"originserver,omitempty"` - Contact string `json:"contact,omitempty"` - Serial uint `json:"serial,omitempty"` - Refresh int `json:"refresh,omitempty"` - Retry int `json:"retry,omitempty"` - Expire int `json:"expire,omitempty"` - Minimum uint `json:"minimum,omitempty"` -} - -func NewSoaRecord() *SoaRecord { - r := &SoaRecord{ - fieldMap: []string{ - "ttl", - "originserver", - "contact", - "serial", - "refresh", - "retry", - "expire", - "minimum", - }, - } - r.SetField("serial", int(time.Now().Unix())) - return r -} - -func (record *SoaRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SoaRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "originserver": - v, ok := value.(string) - if ok { - record.Originserver = v - return nil - } - case "contact": - v, ok := value.(string) - if ok { - record.Contact = v - return nil - } - case "serial": - v, ok := value.(uint) - if ok { - record.Serial = v - return nil - } - case "refresh": - v, ok := value.(int) - if ok { - record.Refresh = v - return nil - } - case "retry": - v, ok := value.(int) - if ok { - record.Retry = v - return nil - } - case "expire": - v, ok := value.(int) - if ok { - record.Expire = v - return nil - } - case "minimum": - v, ok := value.(uint) - if ok { - record.Minimum = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SoaRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "ttl": record.TTL, - "originserver": record.Originserver, - "contact": record.Contact, - "serial": record.Serial, - "refresh": record.Refresh, - "retry": record.Retry, - "expire": record.Expire, - "minimum": record.Minimum, - } -} - -type SpfRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewSpfRecord() *SpfRecord { - return &SpfRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *SpfRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SpfRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SpfRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type SrvRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` - Priority int `json:"priority,omitempty"` - Weight uint16 `json:"weight,omitempty"` - Port uint16 `json:"port,omitempty"` -} - -func NewSrvRecord() *SrvRecord { - return &SrvRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - "priority", - "weight", - "port", - }, - } -} - -func (record *SrvRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SrvRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - case "priority": - v, ok := value.(int) - if ok { - record.Priority = v - return nil - } - case "weight": - v, ok := value.(uint16) - if ok { - record.Weight = v - return nil - } - case "port": - v, ok := value.(uint16) - if ok { - record.Port = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SrvRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - "priority": record.Priority, - "weight": record.Weight, - "port": record.Port, - } -} - -type SshfpRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - FingerprintType int `json:"fingerprint_type,omitempty"` - Fingerprint string `json:"fingerprint,omitempty"` -} - -func NewSshfpRecord() *SshfpRecord { - return &SshfpRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "algorithm", - "fingerprinttype", - "fingerprint", - }, - } -} - -func (record *SshfpRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SshfpRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "fingerprinttype": - v, ok := value.(int) - if ok { - record.FingerprintType = v - return nil - } - case "fingerprint": - v, ok := value.(string) - if ok { - record.Fingerprint = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SshfpRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "algorithm": record.Algorithm, - "fingerprinttype": record.FingerprintType, - "fingerprint": record.Fingerprint, - } -} - -type TxtRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewTxtRecord() *TxtRecord { - return &TxtRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *TxtRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *TxtRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *TxtRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -func contains(fieldMap []string, field string) bool { - field = strings.ToLower(field) - - for _, r := range fieldMap { - if r == field { - return true - } - } - - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/service.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/service.go deleted file mode 100644 index 7f8ff80..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/service.go +++ /dev/null @@ -1,16 +0,0 @@ -package dns - -import ( - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" -) - -var ( - // Config contains the Akamai OPEN Edgegrid API credentials - // for automatic signing of requests - Config edgegrid.Config -) - -// Init sets the FastDNS edgegrid Config -func Init(config edgegrid.Config) { - Config = config -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/zone.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/zone.go deleted file mode 100644 index 65da7bc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/zone.go +++ /dev/null @@ -1,1567 +0,0 @@ -package dns - -import ( - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" - - "github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1" -) - -type name struct { - recordType string - name string -} - -var ( - cnameNames []name - nonCnameNames []name - zoneWriteLock sync.Mutex -) - -// Zone represents a DNS zone -type Zone struct { - Token string `json:"token"` - Zone struct { - Name string `json:"name,omitempty"` - A []*ARecord `json:"a,omitempty"` - Aaaa []*AaaaRecord `json:"aaaa,omitempty"` - Afsdb []*AfsdbRecord `json:"afsdb,omitempty"` - Cname []*CnameRecord `json:"cname,omitempty"` - Dnskey []*DnskeyRecord `json:"dnskey,omitempty"` - Ds []*DsRecord `json:"ds,omitempty"` - Hinfo []*HinfoRecord `json:"hinfo,omitempty"` - Loc []*LocRecord `json:"loc,omitempty"` - Mx []*MxRecord `json:"mx,omitempty"` - Naptr []*NaptrRecord `json:"naptr,omitempty"` - Ns []*NsRecord `json:"ns,omitempty"` - Nsec3 []*Nsec3Record `json:"nsec3,omitempty"` - Nsec3param []*Nsec3paramRecord `json:"nsec3param,omitempty"` - Ptr []*PtrRecord `json:"ptr,omitempty"` - Rp []*RpRecord `json:"rp,omitempty"` - Rrsig []*RrsigRecord `json:"rrsig,omitempty"` - Soa *SoaRecord `json:"soa,omitempty"` - Spf []*SpfRecord `json:"spf,omitempty"` - Srv []*SrvRecord `json:"srv,omitempty"` - Sshfp []*SshfpRecord `json:"sshfp,omitempty"` - Txt []*TxtRecord `json:"txt,omitempty"` - } `json:"zone"` -} - -// NewZone creates a new Zone -func NewZone(hostname string) *Zone { - zone := &Zone{Token: "new"} - zone.Zone.Soa = NewSoaRecord() - zone.Zone.Name = hostname - return zone -} - -// GetZone retrieves a DNS Zone for a given hostname -func GetZone(hostname string) (*Zone, error) { - zone := NewZone(hostname) - req, err := client.NewRequest( - Config, - "GET", - "/config-dns/v1/zones/"+hostname, - nil, - ) - if err != nil { - return nil, err - } - - res, err := client.Do(Config, req) - if err != nil { - return nil, err - } - - if client.IsError(res) && res.StatusCode != 404 { - return nil, client.NewAPIError(res) - } else if res.StatusCode == 404 { - return nil, &ZoneError{zoneName: hostname} - } else { - err = client.BodyJSON(res, zone) - if err != nil { - return nil, err - } - - return zone, nil - } -} - -// Save updates the Zone -func (zone *Zone) Save() error { - // This lock will restrict the concurrency of API calls - // to 1 save request at a time. This is needed for the Soa.Serial value which - // is required to be incremented for every subsequent update to a zone - // so we have to save just one request at a time to ensure this is always - // incremented properly - zoneWriteLock.Lock() - defer zoneWriteLock.Unlock() - - valid, f := zone.validateCnames() - if valid == false { - var msg string - for _, v := range f { - msg = msg + fmt.Sprintf("\n%s Record '%s' conflicts with CNAME", v.recordType, v.name) - } - return &ZoneError{ - zoneName: zone.Zone.Name, - apiErrorMessage: "All CNAMEs must be unique in the zone" + msg, - } - } - - req, err := client.NewJSONRequest( - Config, - "POST", - "/config-dns/v1/zones/"+zone.Zone.Name, - zone, - ) - if err != nil { - return err - } - - res, err := client.Do(Config, req) - - // Network error - if err != nil { - return &ZoneError{ - zoneName: zone.Zone.Name, - httpErrorMessage: err.Error(), - err: err, - } - } - - // API error - if client.IsError(res) { - err := client.NewAPIError(res) - return &ZoneError{zoneName: zone.Zone.Name, apiErrorMessage: err.Detail, err: err} - } - - for { - updatedZone, err := GetZone(zone.Zone.Name) - if err != nil { - return err - } - - if updatedZone.Token != zone.Token { - *zone = *updatedZone - break - } - time.Sleep(time.Second) - } - - return nil -} - -func (zone *Zone) Delete() error { - // remove all the records except for SOA - // which is required and save the zone - zone.Zone.A = nil - zone.Zone.Aaaa = nil - zone.Zone.Afsdb = nil - zone.Zone.Cname = nil - zone.Zone.Dnskey = nil - zone.Zone.Ds = nil - zone.Zone.Hinfo = nil - zone.Zone.Loc = nil - zone.Zone.Mx = nil - zone.Zone.Naptr = nil - zone.Zone.Ns = nil - zone.Zone.Nsec3 = nil - zone.Zone.Nsec3param = nil - zone.Zone.Ptr = nil - zone.Zone.Rp = nil - zone.Zone.Rrsig = nil - zone.Zone.Spf = nil - zone.Zone.Srv = nil - zone.Zone.Sshfp = nil - zone.Zone.Txt = nil - - return zone.Save() -} - -func (zone *Zone) AddRecord(recordPtr interface{}) error { - switch recordPtr.(type) { - case *ARecord: - zone.addARecord(recordPtr.(*ARecord)) - case *AaaaRecord: - zone.addAaaaRecord(recordPtr.(*AaaaRecord)) - case *AfsdbRecord: - zone.addAfsdbRecord(recordPtr.(*AfsdbRecord)) - case *CnameRecord: - zone.addCnameRecord(recordPtr.(*CnameRecord)) - case *DnskeyRecord: - zone.addDnskeyRecord(recordPtr.(*DnskeyRecord)) - case *DsRecord: - zone.addDsRecord(recordPtr.(*DsRecord)) - case *HinfoRecord: - zone.addHinfoRecord(recordPtr.(*HinfoRecord)) - case *LocRecord: - zone.addLocRecord(recordPtr.(*LocRecord)) - case *MxRecord: - zone.addMxRecord(recordPtr.(*MxRecord)) - case *NaptrRecord: - zone.addNaptrRecord(recordPtr.(*NaptrRecord)) - case *NsRecord: - zone.addNsRecord(recordPtr.(*NsRecord)) - case *Nsec3Record: - zone.addNsec3Record(recordPtr.(*Nsec3Record)) - case *Nsec3paramRecord: - zone.addNsec3paramRecord(recordPtr.(*Nsec3paramRecord)) - case *PtrRecord: - zone.addPtrRecord(recordPtr.(*PtrRecord)) - case *RpRecord: - zone.addRpRecord(recordPtr.(*RpRecord)) - case *RrsigRecord: - zone.addRrsigRecord(recordPtr.(*RrsigRecord)) - case *SoaRecord: - zone.addSoaRecord(recordPtr.(*SoaRecord)) - case *SpfRecord: - zone.addSpfRecord(recordPtr.(*SpfRecord)) - case *SrvRecord: - zone.addSrvRecord(recordPtr.(*SrvRecord)) - case *SshfpRecord: - zone.addSshfpRecord(recordPtr.(*SshfpRecord)) - case *TxtRecord: - zone.addTxtRecord(recordPtr.(*TxtRecord)) - } - - return nil -} - -func (zone *Zone) RemoveRecord(recordPtr interface{}) error { - switch recordPtr.(type) { - case *ARecord: - return zone.removeARecord(recordPtr.(*ARecord)) - case *AaaaRecord: - return zone.removeAaaaRecord(recordPtr.(*AaaaRecord)) - case *AfsdbRecord: - return zone.removeAfsdbRecord(recordPtr.(*AfsdbRecord)) - case *CnameRecord: - return zone.removeCnameRecord(recordPtr.(*CnameRecord)) - case *DnskeyRecord: - return zone.removeDnskeyRecord(recordPtr.(*DnskeyRecord)) - case *DsRecord: - return zone.removeDsRecord(recordPtr.(*DsRecord)) - case *HinfoRecord: - return zone.removeHinfoRecord(recordPtr.(*HinfoRecord)) - case *LocRecord: - return zone.removeLocRecord(recordPtr.(*LocRecord)) - case *MxRecord: - return zone.removeMxRecord(recordPtr.(*MxRecord)) - case *NaptrRecord: - return zone.removeNaptrRecord(recordPtr.(*NaptrRecord)) - case *NsRecord: - return zone.removeNsRecord(recordPtr.(*NsRecord)) - case *Nsec3Record: - return zone.removeNsec3Record(recordPtr.(*Nsec3Record)) - case *Nsec3paramRecord: - return zone.removeNsec3paramRecord(recordPtr.(*Nsec3paramRecord)) - case *PtrRecord: - return zone.removePtrRecord(recordPtr.(*PtrRecord)) - case *RpRecord: - return zone.removeRpRecord(recordPtr.(*RpRecord)) - case *RrsigRecord: - return zone.removeRrsigRecord(recordPtr.(*RrsigRecord)) - case *SoaRecord: - return zone.removeSoaRecord(recordPtr.(*SoaRecord)) - case *SpfRecord: - return zone.removeSpfRecord(recordPtr.(*SpfRecord)) - case *SrvRecord: - return zone.removeSrvRecord(recordPtr.(*SrvRecord)) - case *SshfpRecord: - return zone.removeSshfpRecord(recordPtr.(*SshfpRecord)) - case *TxtRecord: - return zone.removeTxtRecord(recordPtr.(*TxtRecord)) - } - - return nil -} - -func (zone *Zone) addARecord(record *ARecord) { - zone.Zone.A = append(zone.Zone.A, record) - nonCnameNames = append(nonCnameNames, name{recordType: "A", name: record.Name}) -} - -func (zone *Zone) addAaaaRecord(record *AaaaRecord) { - zone.Zone.Aaaa = append(zone.Zone.Aaaa, record) - nonCnameNames = append(nonCnameNames, name{recordType: "AAAA", name: record.Name}) -} - -func (zone *Zone) addAfsdbRecord(record *AfsdbRecord) { - zone.Zone.Afsdb = append(zone.Zone.Afsdb, record) - nonCnameNames = append(nonCnameNames, name{recordType: "AFSDB", name: record.Name}) -} - -func (zone *Zone) addCnameRecord(record *CnameRecord) { - zone.Zone.Cname = append(zone.Zone.Cname, record) - cnameNames = append(cnameNames, name{recordType: "CNAME", name: record.Name}) -} - -func (zone *Zone) addDnskeyRecord(record *DnskeyRecord) { - zone.Zone.Dnskey = append(zone.Zone.Dnskey, record) - nonCnameNames = append(nonCnameNames, name{recordType: "DNSKEY", name: record.Name}) -} - -func (zone *Zone) addDsRecord(record *DsRecord) { - zone.Zone.Ds = append(zone.Zone.Ds, record) - nonCnameNames = append(nonCnameNames, name{recordType: "DS", name: record.Name}) -} - -func (zone *Zone) addHinfoRecord(record *HinfoRecord) { - zone.Zone.Hinfo = append(zone.Zone.Hinfo, record) - nonCnameNames = append(nonCnameNames, name{recordType: "HINFO", name: record.Name}) -} - -func (zone *Zone) addLocRecord(record *LocRecord) { - zone.Zone.Loc = append(zone.Zone.Loc, record) - nonCnameNames = append(nonCnameNames, name{recordType: "LOC", name: record.Name}) -} - -func (zone *Zone) addMxRecord(record *MxRecord) { - zone.Zone.Mx = append(zone.Zone.Mx, record) - nonCnameNames = append(nonCnameNames, name{recordType: "MX", name: record.Name}) -} - -func (zone *Zone) addNaptrRecord(record *NaptrRecord) { - zone.Zone.Naptr = append(zone.Zone.Naptr, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NAPTR", name: record.Name}) -} - -func (zone *Zone) addNsRecord(record *NsRecord) { - zone.Zone.Ns = append(zone.Zone.Ns, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NS", name: record.Name}) -} - -func (zone *Zone) addNsec3Record(record *Nsec3Record) { - zone.Zone.Nsec3 = append(zone.Zone.Nsec3, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NSEC3", name: record.Name}) -} - -func (zone *Zone) addNsec3paramRecord(record *Nsec3paramRecord) { - zone.Zone.Nsec3param = append(zone.Zone.Nsec3param, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NSEC3PARAM", name: record.Name}) -} - -func (zone *Zone) addPtrRecord(record *PtrRecord) { - zone.Zone.Ptr = append(zone.Zone.Ptr, record) - nonCnameNames = append(nonCnameNames, name{recordType: "PTR", name: record.Name}) -} - -func (zone *Zone) addRpRecord(record *RpRecord) { - zone.Zone.Rp = append(zone.Zone.Rp, record) - nonCnameNames = append(nonCnameNames, name{recordType: "RP", name: record.Name}) -} - -func (zone *Zone) addRrsigRecord(record *RrsigRecord) { - zone.Zone.Rrsig = append(zone.Zone.Rrsig, record) - nonCnameNames = append(nonCnameNames, name{recordType: "RRSIG", name: record.Name}) -} - -func (zone *Zone) addSoaRecord(record *SoaRecord) { - // Only one SOA records is allowed - zone.Zone.Soa = record -} - -func (zone *Zone) addSpfRecord(record *SpfRecord) { - zone.Zone.Spf = append(zone.Zone.Spf, record) - nonCnameNames = append(nonCnameNames, name{recordType: "SPF", name: record.Name}) -} - -func (zone *Zone) addSrvRecord(record *SrvRecord) { - zone.Zone.Srv = append(zone.Zone.Srv, record) - nonCnameNames = append(nonCnameNames, name{recordType: "SRV", name: record.Name}) -} - -func (zone *Zone) addSshfpRecord(record *SshfpRecord) { - zone.Zone.Sshfp = append(zone.Zone.Sshfp, record) - nonCnameNames = append(nonCnameNames, name{recordType: "SSHFP", name: record.Name}) -} - -func (zone *Zone) addTxtRecord(record *TxtRecord) { - zone.Zone.Txt = append(zone.Zone.Txt, record) - nonCnameNames = append(nonCnameNames, name{recordType: "TXT", name: record.Name}) -} - -func (zone *Zone) removeARecord(record *ARecord) error { - for key, r := range zone.Zone.A { - if reflect.DeepEqual(r, record) { - records := zone.Zone.A[:key] - if len(zone.Zone.A) > key { - if len(zone.Zone.A) > key { - zone.Zone.A = append(records, zone.Zone.A[key+1:]...) - } else { - zone.Zone.A = records - } - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("A Record not found") -} - -func (zone *Zone) removeAaaaRecord(record *AaaaRecord) error { - for key, r := range zone.Zone.Aaaa { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Aaaa[:key] - if len(zone.Zone.Aaaa) > key { - zone.Zone.Aaaa = append(records, zone.Zone.Aaaa[key+1:]...) - } else { - zone.Zone.Aaaa = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("AAAA Record not found") -} - -func (zone *Zone) removeAfsdbRecord(record *AfsdbRecord) error { - for key, r := range zone.Zone.Afsdb { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Afsdb[:key] - if len(zone.Zone.Afsdb) > key { - zone.Zone.Afsdb = append(records, zone.Zone.Afsdb[key+1:]...) - } else { - zone.Zone.Afsdb = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Afsdb Record not found") -} - -func (zone *Zone) removeCnameRecord(record *CnameRecord) error { - for key, r := range zone.Zone.Cname { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Cname[:key] - if len(zone.Zone.Cname) > key { - zone.Zone.Cname = append(records, zone.Zone.Cname[key+1:]...) - } else { - zone.Zone.Cname = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Cname Record not found") - - zone.removeCnameName(record.Name) - - return nil -} - -func (zone *Zone) removeDnskeyRecord(record *DnskeyRecord) error { - for key, r := range zone.Zone.Dnskey { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Dnskey[:key] - if len(zone.Zone.Dnskey) > key { - zone.Zone.Dnskey = append(records, zone.Zone.Dnskey[key+1:]...) - } else { - zone.Zone.Dnskey = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Dnskey Record not found") -} - -func (zone *Zone) removeDsRecord(record *DsRecord) error { - for key, r := range zone.Zone.Ds { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Ds[:key] - if len(zone.Zone.Ds) > key { - zone.Zone.Ds = append(records, zone.Zone.Ds[key+1:]...) - } else { - zone.Zone.Ds = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Ds Record not found") -} - -func (zone *Zone) removeHinfoRecord(record *HinfoRecord) error { - for key, r := range zone.Zone.Hinfo { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Hinfo[:key] - if len(zone.Zone.Hinfo) > key { - zone.Zone.Hinfo = append(records, zone.Zone.Hinfo[key+1:]...) - } else { - zone.Zone.Hinfo = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Hinfo Record not found") -} - -func (zone *Zone) removeLocRecord(record *LocRecord) error { - for key, r := range zone.Zone.Loc { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Loc[:key] - if len(zone.Zone.Loc) > key { - zone.Zone.Loc = append(records, zone.Zone.Loc[key+1:]...) - } else { - zone.Zone.Loc = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Loc Record not found") -} - -func (zone *Zone) removeMxRecord(record *MxRecord) error { - for key, r := range zone.Zone.Mx { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Mx[:key] - if len(zone.Zone.Mx) > key { - zone.Zone.Mx = append(records, zone.Zone.Mx[key+1:]...) - } else { - zone.Zone.Mx = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Mx Record not found") -} - -func (zone *Zone) removeNaptrRecord(record *NaptrRecord) error { - for key, r := range zone.Zone.Naptr { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Naptr[:key] - if len(zone.Zone.Naptr) > key { - zone.Zone.Naptr = append(records, zone.Zone.Naptr[key+1:]...) - } else { - zone.Zone.Naptr = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Naptr Record not found") -} - -func (zone *Zone) removeNsRecord(record *NsRecord) error { - for key, r := range zone.Zone.Ns { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Ns[:key] - if len(zone.Zone.Ns) > key { - zone.Zone.Ns = append(records, zone.Zone.Ns[key+1:]...) - } else { - zone.Zone.Ns = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Ns Record not found") -} - -func (zone *Zone) removeNsec3Record(record *Nsec3Record) error { - for key, r := range zone.Zone.Nsec3 { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Nsec3[:key] - if len(zone.Zone.Nsec3) > key { - zone.Zone.Nsec3 = append(records, zone.Zone.Nsec3[key+1:]...) - } else { - zone.Zone.Nsec3 = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Nsec3 Record not found") -} - -func (zone *Zone) removeNsec3paramRecord(record *Nsec3paramRecord) error { - for key, r := range zone.Zone.Nsec3param { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Nsec3param[:key] - if len(zone.Zone.Nsec3param) > key { - zone.Zone.Nsec3param = append(records, zone.Zone.Nsec3param[key+1:]...) - } else { - zone.Zone.Nsec3param = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Nsec3param Record not found") -} - -func (zone *Zone) removePtrRecord(record *PtrRecord) error { - for key, r := range zone.Zone.Ptr { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Ptr[:key] - if len(zone.Zone.Ptr) > key { - zone.Zone.Ptr = append(records, zone.Zone.Ptr[key+1:]...) - } else { - zone.Zone.Ptr = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Ptr Record not found") -} - -func (zone *Zone) removeRpRecord(record *RpRecord) error { - for key, r := range zone.Zone.Rp { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Rp[:key] - if len(zone.Zone.Rp) > key { - zone.Zone.Rp = append(records, zone.Zone.Rp[key+1:]...) - } else { - zone.Zone.Rp = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Rp Record not found") -} - -func (zone *Zone) removeRrsigRecord(record *RrsigRecord) error { - for key, r := range zone.Zone.Rrsig { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Rrsig[:key] - if len(zone.Zone.Rrsig) > key { - zone.Zone.Rrsig = append(records, zone.Zone.Rrsig[key+1:]...) - } else { - zone.Zone.Rrsig = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Rrsig Record not found") -} - -func (zone *Zone) removeSoaRecord(record *SoaRecord) error { - if reflect.DeepEqual(zone.Zone.Soa, record) { - zone.Zone.Soa = nil - - return nil - } - - return errors.New("SOA Record does not match") -} - -func (zone *Zone) removeSpfRecord(record *SpfRecord) error { - for key, r := range zone.Zone.Spf { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Spf[:key] - if len(zone.Zone.Spf) > key { - zone.Zone.Spf = append(records, zone.Zone.Spf[key+1:]...) - } else { - zone.Zone.Spf = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Spf Record not found") -} - -func (zone *Zone) removeSrvRecord(record *SrvRecord) error { - for key, r := range zone.Zone.Srv { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Srv[:key] - if len(zone.Zone.Srv) > key { - zone.Zone.Srv = append(records, zone.Zone.Srv[key+1:]...) - } else { - zone.Zone.Srv = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Srv Record not found") -} - -func (zone *Zone) removeSshfpRecord(record *SshfpRecord) error { - for key, r := range zone.Zone.Sshfp { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Sshfp[:key] - if len(zone.Zone.Sshfp) > key { - zone.Zone.Sshfp = append(records, zone.Zone.Sshfp[key+1:]...) - } else { - zone.Zone.Sshfp = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Sshfp Record not found") -} - -func (zone *Zone) removeTxtRecord(record *TxtRecord) error { - for key, r := range zone.Zone.Txt { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Txt[:key] - if len(zone.Zone.Txt) > key { - zone.Zone.Txt = append(records, zone.Zone.Txt[key+1:]...) - } else { - zone.Zone.Txt = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Txt Record not found") -} - -func (zone *Zone) PostUnmarshalJSON() error { - if zone.Zone.Soa.Serial > 0 { - zone.Zone.Soa.originalSerial = zone.Zone.Soa.Serial - } - return nil -} - -func (zone *Zone) PreMarshalJSON() error { - if zone.Zone.Soa.Serial == 0 { - zone.Zone.Soa.Serial = uint(time.Now().Unix()) - } else if zone.Zone.Soa.Serial == zone.Zone.Soa.originalSerial { - zone.Zone.Soa.Serial = zone.Zone.Soa.Serial + 1 - } - return nil -} - -func (zone *Zone) validateCnames() (bool, []name) { - var valid bool = true - var failedRecords []name - for _, v := range cnameNames { - for _, vv := range nonCnameNames { - if v.name == vv.name { - valid = false - failedRecords = append(failedRecords, vv) - } - } - } - return valid, failedRecords -} - -func (zone *Zone) removeCnameName(host string) { - var ncn []name - for _, v := range cnameNames { - if v.name != host { - ncn =append(ncn, v) - } - } - cnameNames = ncn -} - - -func (zone *Zone) removeNonCnameName(host string) { - var ncn []name - for _, v := range nonCnameNames { - if v.name != host { - ncn =append(ncn, v) - } - } - nonCnameNames = ncn -} - -func (zone *Zone) FindRecords(recordType string, options map[string]interface{}) []DNSRecord { - switch strings.ToUpper(recordType) { - case "A": - return zone.findARecord(options) - case "AAAA": - return zone.findAaaaRecord(options) - case "AFSDB": - return zone.findAfsdbRecord(options) - case "CNAME": - return zone.findCnameRecord(options) - case "DNSKEY": - return zone.findDnskeyRecord(options) - case "DS": - return zone.findDsRecord(options) - case "HINFO": - return zone.findHinfoRecord(options) - case "LOC": - return zone.findLocRecord(options) - case "MX": - return zone.findMxRecord(options) - case "NAPTR": - return zone.findNaptrRecord(options) - case "NS": - return zone.findNsRecord(options) - case "NSEC3": - return zone.findNsec3Record(options) - case "NSEC3PARAM": - return zone.findNsec3paramRecord(options) - case "PTR": - return zone.findPtrRecord(options) - case "RP": - return zone.findRpRecord(options) - case "RRSIG": - return zone.findRrsigRecord(options) - case "SPF": - return zone.findSpfRecord(options) - case "SRV": - return zone.findSrvRecord(options) - case "SSHFP": - return zone.findSshfpRecord(options) - case "TXT": - return zone.findTxtRecord(options) - } - - return make([]DNSRecord, 0) -} - -func (zone *Zone) findARecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.A { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - - return found -} - -func (zone *Zone) findAaaaRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Aaaa { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - - return found -} - -func (zone *Zone) findAfsdbRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Afsdb { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if subtype, ok := options["subtype"]; ok && record.Subtype == subtype.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findCnameRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Cname { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findDnskeyRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Dnskey { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(int) { - matchCounter++ - } - - if protocol, ok := options["protocol"]; ok && record.Protocol == protocol.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if key, ok := options["key"]; ok && record.Key == key.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findDsRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Ds { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if keytag, ok := options["keytag"]; ok && record.Keytag == keytag.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if digesttype, ok := options["digesttype"]; ok && record.DigestType == digesttype.(int) { - matchCounter++ - } - - if digest, ok := options["digest"]; ok && record.Digest == digest.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findHinfoRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Hinfo { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if hardware, ok := options["hardware"]; ok && record.Hardware == hardware.(string) { - matchCounter++ - } - - if software, ok := options["software"]; ok && record.Software == software.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findLocRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Loc { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findMxRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Mx { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if priority, ok := options["priority"]; ok && record.Priority == priority.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNaptrRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Naptr { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if order, ok := options["order"]; ok && record.Order == order.(uint16) { - matchCounter++ - } - - if preference, ok := options["preference"]; ok && record.Preference == preference.(uint16) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(string) { - matchCounter++ - } - - if service, ok := options["service"]; ok && record.Service == service.(string) { - matchCounter++ - } - - if regexp, ok := options["regexp"]; ok && record.Regexp == regexp.(string) { - matchCounter++ - } - - if replacement, ok := options["replacement"]; ok && record.Replacement == replacement.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNsRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Ns { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNsec3Record(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Nsec3 { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(int) { - matchCounter++ - } - - if iterations, ok := options["iterations"]; ok && record.Iterations == iterations.(int) { - matchCounter++ - } - - if salt, ok := options["salt"]; ok && record.Salt == salt.(string) { - matchCounter++ - } - - if nextHashedOwnerName, ok := options["nextHashedOwnerName"]; ok && record.NextHashedOwnerName == nextHashedOwnerName.(string) { - matchCounter++ - } - - if typeBitmaps, ok := options["typeBitmaps"]; ok && record.TypeBitmaps == typeBitmaps.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNsec3paramRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Nsec3param { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(int) { - matchCounter++ - } - - if iterations, ok := options["iterations"]; ok && record.Iterations == iterations.(int) { - matchCounter++ - } - - if salt, ok := options["salt"]; ok && record.Salt == salt.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findPtrRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Ptr { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findRpRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Rp { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if mailbox, ok := options["mailbox"]; ok && record.Mailbox == mailbox.(string) { - matchCounter++ - } - - if txt, ok := options["txt"]; ok && record.Txt == txt.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findRrsigRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Rrsig { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if typeCovered, ok := options["typeCovered"]; ok && record.TypeCovered == typeCovered.(string) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if originalTTL, ok := options["originalTTL"]; ok && record.OriginalTTL == originalTTL.(int) { - matchCounter++ - } - - if expiration, ok := options["expiration"]; ok && record.Expiration == expiration.(string) { - matchCounter++ - } - - if inception, ok := options["inception"]; ok && record.Inception == inception.(string) { - matchCounter++ - } - - if keytag, ok := options["keytag"]; ok && record.Keytag == keytag.(int) { - matchCounter++ - } - - if signer, ok := options["signer"]; ok && record.Signer == signer.(string) { - matchCounter++ - } - - if signature, ok := options["signature"]; ok && record.Signature == signature.(string) { - matchCounter++ - } - - if labels, ok := options["labels"]; ok && record.Labels == labels.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findSpfRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Spf { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findSrvRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Srv { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if priority, ok := options["priority"]; ok && record.Priority == priority.(int) { - matchCounter++ - } - - if weight, ok := options["weight"]; ok && record.Weight == weight.(uint16) { - matchCounter++ - } - - if port, ok := options["port"]; ok && record.Port == port.(uint16) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findSshfpRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Sshfp { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if fingerprintType, ok := options["fingerprintType"]; ok && record.FingerprintType == fingerprintType.(int) { - matchCounter++ - } - - if fingerprint, ok := options["fingerprint"]; ok && record.Fingerprint == fingerprint.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findTxtRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Txt { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/config.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/config.go deleted file mode 100644 index 35a6719..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/config.go +++ /dev/null @@ -1,181 +0,0 @@ -package edgegrid - -import ( - "fmt" - "os" - "strconv" - "strings" - - "github.com/go-ini/ini" - "github.com/mitchellh/go-homedir" -) - -// Config struct provides all the necessary fields to -// create authorization header, debug is optional -type Config struct { - Host string `ini:"host"` - ClientToken string `ini:"client_token"` - ClientSecret string `ini:"client_secret"` - AccessToken string `ini:"access_token"` - HeaderToSign []string `ini:"headers_to_sign"` - MaxBody int `ini:"max_body"` - Debug bool `ini:"debug"` -} - -// Init initializes by first attempting to use ENV vars, with .edgerc as a fallback -// -// See: InitEnv() -// See: InitEdgeRc() -func Init(filepath string, section string) (Config, error) { - if section == "" { - section = defaultSection - } else { - section = strings.ToUpper(section) - } - - _, exists := os.LookupEnv("AKAMAI_" + section + "_HOST") - if !exists && section == defaultSection { - _, exists := os.LookupEnv("AKAMAI_HOST") - - if exists { - return InitEnv("") - } - } - - if exists { - return InitEnv(section) - } - - c, err := InitEdgeRc(filepath, strings.ToLower(section)) - - if err == nil { - return c, nil - } - - if section != defaultSection { - _, ok := os.LookupEnv("AKAMAI_HOST") - if ok { - return InitEnv("") - } - } - - return c, fmt.Errorf("Unable to create instance using environment or .edgerc file") -} - -// InitEdgeRc initializes using a configuration file in standard INI format -// -// By default, it uses the .edgerc found in the users home directory, and the -// "default" section. -func InitEdgeRc(filepath string, section string) (Config, error) { - var ( - c Config - requiredOptions = []string{"host", "client_token", "client_secret", "access_token"} - missing []string - ) - - // Check if filepath is empty - if filepath == "" { - filepath = "~/.edgerc" - } - - // Check if section is empty - if section == "" { - section = "default" - } - - // Tilde seems to be not working when passing ~/.edgerc as file - // Takes current user and use home dir instead - - path, err := homedir.Expand(filepath) - - if err != nil { - return c, fmt.Errorf(errorMap[ErrHomeDirNotFound], err) - } - - edgerc, err := ini.Load(path) - if err != nil { - return c, fmt.Errorf(errorMap[ErrConfigFile], err) - } - err = edgerc.Section(section).MapTo(&c) - if err != nil { - return c, fmt.Errorf(errorMap[ErrConfigFileSection], err) - } - for _, opt := range requiredOptions { - if !(edgerc.Section(section).HasKey(opt)) { - missing = append(missing, opt) - } - } - if len(missing) > 0 { - return c, fmt.Errorf(errorMap[ErrConfigMissingOptions], missing) - } - if c.MaxBody == 0 { - c.MaxBody = 131072 - } - return c, nil -} - -// InitEnv initializes using the Environment (ENV) -// -// By default, it uses AKAMAI_HOST, AKAMAI_CLIENT_TOKEN, AKAMAI_CLIENT_SECRET, -// AKAMAI_ACCESS_TOKEN, and AKAMAI_MAX_BODY variables. -// -// You can define multiple configurations by prefixing with the section name specified, e.g. -// passing "ccu" will cause it to look for AKAMAI_CCU_HOST, etc. -// -// If AKAMAI_{SECTION} does not exist, it will fall back to just AKAMAI_. -func InitEnv(section string) (Config, error) { - var ( - c Config - requiredOptions = []string{"HOST", "CLIENT_TOKEN", "CLIENT_SECRET", "ACCESS_TOKEN"} - missing []string - prefix string - ) - - // Check if section is empty - if section == "" { - section = defaultSection - } else { - section = strings.ToUpper(section) - } - - prefix = "AKAMAI_" - _, ok := os.LookupEnv("AKAMAI_" + section + "_HOST") - if ok { - prefix = "AKAMAI_" + section + "_" - } - - for _, opt := range requiredOptions { - val, ok := os.LookupEnv(prefix + opt) - if !ok { - missing = append(missing, prefix+opt) - } else { - switch { - case opt == "HOST": - c.Host = val - case opt == "CLIENT_TOKEN": - c.ClientToken = val - case opt == "CLIENT_SECRET": - c.ClientSecret = val - case opt == "ACCESS_TOKEN": - c.AccessToken = val - } - } - } - - if len(missing) > 0 { - return c, fmt.Errorf(errorMap[ErrMissingEnvVariables], missing) - } - - c.MaxBody = 0 - - val, ok := os.LookupEnv(prefix + "MAX_BODY") - if i, err := strconv.Atoi(val); err == nil { - c.MaxBody = i - } - - if !ok || c.MaxBody == 0 { - c.MaxBody = 131072 - } - - return c, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/errors.go deleted file mode 100644 index d5448ae..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/errors.go +++ /dev/null @@ -1,22 +0,0 @@ -package edgegrid - -// Error constants -const ( - ErrUUIDGenerateFailed = 500 - ErrHomeDirNotFound = 501 - ErrConfigFile = 502 - ErrConfigFileSection = 503 - ErrConfigMissingOptions = 504 - ErrMissingEnvVariables = 505 -) - -var ( - errorMap = map[int]string{ - ErrUUIDGenerateFailed: "Generate UUID failed: %s", - ErrHomeDirNotFound: "Fatal could not find home dir from user: %s", - ErrConfigFile: "Fatal error edgegrid file: %s", - ErrConfigFileSection: "Could not map section: %s", - ErrConfigMissingOptions: "Fatal missing required options: %s", - ErrMissingEnvVariables: "Fatal missing required environment variables: %s", - } -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/signer.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/signer.go deleted file mode 100644 index 27e6d06..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/signer.go +++ /dev/null @@ -1,195 +0,0 @@ -// Package edgegrid allows you to sign http.Request's using the Akamai OPEN Edgegrid Signing Scheme -package edgegrid - -import ( - "bytes" - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "fmt" - "io/ioutil" - "net/http" - "sort" - "strings" - "time" - "unicode" - - "github.com/google/uuid" - log "github.com/sirupsen/logrus" -) - -const defaultSection = "DEFAULT" - -// AddRequestHeader sets the Authorization header to use Akamai Open API -func AddRequestHeader(config Config, req *http.Request) *http.Request { - if config.Debug { - log.SetLevel(log.DebugLevel) - } - timestamp := makeEdgeTimeStamp() - nonce := createNonce() - - if req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "application/json") - } - - req.Header.Set("Authorization", createAuthHeader(config, req, timestamp, nonce)) - return req -} - -// Must be assigned the UTC time when the request is signed. -// Format of “yyyyMMddTHH:mm:ss+0000” -func makeEdgeTimeStamp() string { - local := time.FixedZone("GMT", 0) - t := time.Now().In(local) - return fmt.Sprintf("%d%02d%02dT%02d:%02d:%02d+0000", - t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) -} - -// Must be assigned a nonce (number used once) for the request. -// It is a random string used to detect replayed request messages. -// A GUID is recommended. -func createNonce() string { - uuid, err := uuid.NewRandom() - if err != nil { - log.Errorf(errorMap[ErrUUIDGenerateFailed], err) - return "" - } - return uuid.String() -} - -func stringMinifier(in string) (out string) { - white := false - for _, c := range in { - if unicode.IsSpace(c) { - if !white { - out = out + " " - } - white = true - } else { - out = out + string(c) - white = false - } - } - return -} - -func concatPathQuery(path, query string) string { - if query == "" { - return path - } - return fmt.Sprintf("%s?%s", path, query) -} - -// createSignature is the base64-encoding of the SHA–256 HMAC of the data to sign with the signing key. -func createSignature(message string, secret string) string { - key := []byte(secret) - h := hmac.New(sha256.New, key) - h.Write([]byte(message)) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} - -func createHash(data string) string { - h := sha256.Sum256([]byte(data)) - return base64.StdEncoding.EncodeToString(h[:]) -} - -func canonicalizeHeaders(config Config, req *http.Request) string { - var unsortedHeader []string - var sortedHeader []string - for k := range req.Header { - unsortedHeader = append(unsortedHeader, k) - } - sort.Strings(unsortedHeader) - for _, k := range unsortedHeader { - for _, sign := range config.HeaderToSign { - if sign == k { - v := strings.TrimSpace(req.Header.Get(k)) - sortedHeader = append(sortedHeader, fmt.Sprintf("%s:%s", strings.ToLower(k), strings.ToLower(stringMinifier(v)))) - } - } - } - return strings.Join(sortedHeader, "\t") - -} - -// signingKey is derived from the client secret. -// The signing key is computed as the base64 encoding of the SHA–256 HMAC of the timestamp string -// (the field value included in the HTTP authorization header described above) with the client secret as the key. -func signingKey(config Config, timestamp string) string { - key := createSignature(timestamp, config.ClientSecret) - return key -} - -// The content hash is the base64-encoded SHA–256 hash of the POST body. -// For any other request methods, this field is empty. But the tac separator (\t) must be included. -// The size of the POST body must be less than or equal to the value specified by the service. -// Any request that does not meet this criteria SHOULD be rejected during the signing process, -// as the request will be rejected by EdgeGrid. -func createContentHash(config Config, req *http.Request) string { - var ( - contentHash string - preparedBody string - bodyBytes []byte - ) - if req.Body != nil { - bodyBytes, _ = ioutil.ReadAll(req.Body) - req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) - preparedBody = string(bodyBytes) - } - - log.Debugf("Body is %s", preparedBody) - if req.Method == "POST" && len(preparedBody) > 0 { - log.Debugf("Signing content: %s", preparedBody) - if len(preparedBody) > config.MaxBody { - log.Debugf("Data length %d is larger than maximum %d", - len(preparedBody), config.MaxBody) - - preparedBody = preparedBody[0:config.MaxBody] - log.Debugf("Data truncated to %d for computing the hash", len(preparedBody)) - } - contentHash = createHash(preparedBody) - } - log.Debugf("Content hash is '%s'", contentHash) - return contentHash -} - -// The data to sign includes the information from the HTTP request that is relevant to ensuring that the request is authentic. -// This data set comprised of the request data combined with the authorization header value (excluding the signature field, -// but including the ; right before the signature field). -func signingData(config Config, req *http.Request, authHeader string) string { - - dataSign := []string{ - req.Method, - req.URL.Scheme, - req.URL.Host, - concatPathQuery(req.URL.Path, req.URL.RawQuery), - canonicalizeHeaders(config, req), - createContentHash(config, req), - authHeader, - } - log.Debugf("Data to sign %s", strings.Join(dataSign, "\t")) - return strings.Join(dataSign, "\t") -} - -func signingRequest(config Config, req *http.Request, authHeader string, timestamp string) string { - return createSignature(signingData(config, req, authHeader), - signingKey(config, timestamp)) -} - -// The Authorization header starts with the signing algorithm moniker (name of the algorithm) used to sign the request. -// The moniker below identifies EdgeGrid V1, hash message authentication code, SHA–256 as the hash standard. -// This moniker is then followed by a space and an ordered list of name value pairs with each field separated by a semicolon. -func createAuthHeader(config Config, req *http.Request, timestamp string, nonce string) string { - authHeader := fmt.Sprintf("EG1-HMAC-SHA256 client_token=%s;access_token=%s;timestamp=%s;nonce=%s;", - config.ClientToken, - config.AccessToken, - timestamp, - nonce, - ) - log.Debugf("Unsigned authorization header: '%s'", authHeader) - - signedAuthHeader := fmt.Sprintf("%ssignature=%s", authHeader, signingRequest(config, req, authHeader, timestamp)) - - log.Debugf("Signed authorization header: '%s'", signedAuthHeader) - return signedAuthHeader -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/errors.go deleted file mode 100644 index 594c04e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/errors.go +++ /dev/null @@ -1 +0,0 @@ -package jsonhooks diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/jsonhooks.go b/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/jsonhooks.go deleted file mode 100644 index 24c5b8b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/jsonhooks.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package jsonhooks adds hooks that are automatically called before JSON marshaling (PreMarshalJSON) and -// after JSON unmarshaling (PostUnmarshalJSON). It does not do so recursively. -package jsonhooks - -import ( - "encoding/json" - "reflect" -) - -// Marshal wraps encoding/json.Marshal, calls v.PreMarshalJSON() if it exists -func Marshal(v interface{}) ([]byte, error) { - if ImplementsPreJSONMarshaler(v) { - err := v.(PreJSONMarshaler).PreMarshalJSON() - if err != nil { - return nil, err - } - } - - return json.Marshal(v) -} - -// Unmarshal wraps encoding/json.Unmarshal, calls v.PostUnmarshalJSON() if it exists -func Unmarshal(data []byte, v interface{}) error { - err := json.Unmarshal(data, v) - if err != nil { - return err - } - - if ImplementsPostJSONUnmarshaler(v) { - err := v.(PostJSONUnmarshaler).PostUnmarshalJSON() - if err != nil { - return err - } - } - - return nil -} - -// PreJSONMarshaler infers support for the PreMarshalJSON pre-hook -type PreJSONMarshaler interface { - PreMarshalJSON() error -} - -// ImplementsPreJSONMarshaler checks for support for the PreMarshalJSON pre-hook -func ImplementsPreJSONMarshaler(v interface{}) bool { - value := reflect.ValueOf(v) - if !value.IsValid() { - return false - } - - _, ok := value.Interface().(PreJSONMarshaler) - return ok -} - -// PostJSONUnmarshaler infers support for the PostUnmarshalJSON post-hook -type PostJSONUnmarshaler interface { - PostUnmarshalJSON() error -} - -// ImplementsPostJSONUnmarshaler checks for support for the PostUnmarshalJSON post-hook -func ImplementsPostJSONUnmarshaler(v interface{}) bool { - value := reflect.ValueOf(v) - if value.Kind() == reflect.Ptr && value.IsNil() { - return false - } - - _, ok := value.Interface().(PostJSONUnmarshaler) - return ok -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go deleted file mode 100644 index 7f20b7a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 auth - -type Credential interface { -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go deleted file mode 100644 index 68f8226..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go +++ /dev/null @@ -1,34 +0,0 @@ -package credentials - -// Deprecated: Use AccessKeyCredential in this package instead. -type BaseCredential struct { - AccessKeyId string - AccessKeySecret string -} - -type AccessKeyCredential struct { - AccessKeyId string - AccessKeySecret string -} - -// Deprecated: Use NewAccessKeyCredential in this package instead. -func NewBaseCredential(accessKeyId, accessKeySecret string) *BaseCredential { - return &BaseCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } -} - -func (baseCred *BaseCredential) ToAccessKeyCredential() *AccessKeyCredential { - return &AccessKeyCredential{ - AccessKeyId: baseCred.AccessKeyId, - AccessKeySecret: baseCred.AccessKeySecret, - } -} - -func NewAccessKeyCredential(accessKeyId, accessKeySecret string) *AccessKeyCredential { - return &AccessKeyCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go deleted file mode 100644 index 1e1f73a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go +++ /dev/null @@ -1,29 +0,0 @@ -package credentials - -// Deprecated: Use EcsRamRoleCredential in this package instead. -type StsRoleNameOnEcsCredential struct { - RoleName string -} - -// Deprecated: Use NewEcsRamRoleCredential in this package instead. -func NewStsRoleNameOnEcsCredential(roleName string) *StsRoleNameOnEcsCredential { - return &StsRoleNameOnEcsCredential{ - RoleName: roleName, - } -} - -func (oldCred *StsRoleNameOnEcsCredential) ToEcsRamRoleCredential() *EcsRamRoleCredential { - return &EcsRamRoleCredential{ - RoleName: oldCred.RoleName, - } -} - -type EcsRamRoleCredential struct { - RoleName string -} - -func NewEcsRamRoleCredential(roleName string) *EcsRamRoleCredential { - return &EcsRamRoleCredential{ - RoleName: roleName, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go deleted file mode 100644 index 00d688e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go +++ /dev/null @@ -1,15 +0,0 @@ -package credentials - -type RsaKeyPairCredential struct { - PrivateKey string - PublicKeyId string - SessionExpiration int -} - -func NewRsaKeyPairCredential(privateKey, publicKeyId string, sessionExpiration int) *RsaKeyPairCredential { - return &RsaKeyPairCredential{ - PrivateKey: privateKey, - PublicKeyId: publicKeyId, - SessionExpiration: sessionExpiration, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go deleted file mode 100644 index 554431f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go +++ /dev/null @@ -1,15 +0,0 @@ -package credentials - -type StsTokenCredential struct { - AccessKeyId string - AccessKeySecret string - AccessKeyStsToken string -} - -func NewStsTokenCredential(accessKeyId, accessKeySecret, accessKeyStsToken string) *StsTokenCredential { - return &StsTokenCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - AccessKeyStsToken: accessKeyStsToken, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go deleted file mode 100644 index 7a9db75..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go +++ /dev/null @@ -1,49 +0,0 @@ -package credentials - -// Deprecated: Use RamRoleArnCredential in this package instead. -type StsRoleArnCredential struct { - AccessKeyId string - AccessKeySecret string - RoleArn string - RoleSessionName string - RoleSessionExpiration int -} - -type RamRoleArnCredential struct { - AccessKeyId string - AccessKeySecret string - RoleArn string - RoleSessionName string - RoleSessionExpiration int -} - -// Deprecated: Use RamRoleArnCredential in this package instead. -func NewStsRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *StsRoleArnCredential { - return &StsRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - } -} - -func (oldCred *StsRoleArnCredential) ToRamRoleArnCredential() *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: oldCred.AccessKeyId, - AccessKeySecret: oldCred.AccessKeySecret, - RoleArn: oldCred.RoleArn, - RoleSessionName: oldCred.RoleSessionName, - RoleSessionExpiration: oldCred.RoleSessionExpiration, - } -} - -func NewRamRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go deleted file mode 100644 index 8666dd0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 auth - -import ( - "bytes" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "sort" - "strings" -) - -func signRoaRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) { - completeROASignParams(request, signer, regionId) - stringToSign := buildRoaStringToSign(request) - request.SetStringToSign(stringToSign) - signature := signer.Sign(stringToSign, "") - accessKeyId, err := signer.GetAccessKeyId() - if err != nil { - return nil - } - - request.GetHeaders()["Authorization"] = "acs " + accessKeyId + ":" + signature - - return -} - -func completeROASignParams(request requests.AcsRequest, signer Signer, regionId string) { - headerParams := request.GetHeaders() - - // complete query params - queryParams := request.GetQueryParams() - //if _, ok := queryParams["RegionId"]; !ok { - // queryParams["RegionId"] = regionId - //} - if extraParam := signer.GetExtraParam(); extraParam != nil { - for key, value := range extraParam { - if key == "SecurityToken" { - headerParams["x-acs-security-token"] = value - continue - } - - queryParams[key] = value - } - } - - // complete header params - headerParams["Date"] = utils.GetTimeInFormatRFC2616() - headerParams["x-acs-signature-method"] = signer.GetName() - headerParams["x-acs-signature-version"] = signer.GetVersion() - if request.GetFormParams() != nil && len(request.GetFormParams()) > 0 { - formString := utils.GetUrlFormedMap(request.GetFormParams()) - request.SetContent([]byte(formString)) - headerParams["Content-Type"] = requests.Form - } - contentMD5 := utils.GetMD5Base64(request.GetContent()) - headerParams["Content-MD5"] = contentMD5 - if _, contains := headerParams["Content-Type"]; !contains { - headerParams["Content-Type"] = requests.Raw - } - switch format := request.GetAcceptFormat(); format { - case "JSON": - headerParams["Accept"] = requests.Json - case "XML": - headerParams["Accept"] = requests.Xml - default: - headerParams["Accept"] = requests.Raw - } -} - -func buildRoaStringToSign(request requests.AcsRequest) (stringToSign string) { - - headers := request.GetHeaders() - - stringToSignBuilder := bytes.Buffer{} - stringToSignBuilder.WriteString(request.GetMethod()) - stringToSignBuilder.WriteString(requests.HeaderSeparator) - - // append header keys for sign - appendIfContain(headers, &stringToSignBuilder, "Accept", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Content-MD5", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Content-Type", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Date", requests.HeaderSeparator) - - // sort and append headers witch starts with 'x-acs-' - var acsHeaders []string - for key := range headers { - if strings.HasPrefix(key, "x-acs-") { - acsHeaders = append(acsHeaders, key) - } - } - sort.Strings(acsHeaders) - for _, key := range acsHeaders { - stringToSignBuilder.WriteString(key + ":" + headers[key]) - stringToSignBuilder.WriteString(requests.HeaderSeparator) - } - - // append query params - stringToSignBuilder.WriteString(request.BuildQueries()) - stringToSign = stringToSignBuilder.String() - return -} - -func appendIfContain(sourceMap map[string]string, target *bytes.Buffer, key, separator string) { - if value, contain := sourceMap[key]; contain && len(value) > 0 { - target.WriteString(sourceMap[key]) - target.WriteString(separator) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go deleted file mode 100644 index 0c6f6d1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 auth - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "net/url" - "sort" - "strings" -) - -func signRpcRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) { - err = completeRpcSignParams(request, signer, regionId) - if err != nil { - return - } - // remove while retry - if _, containsSign := request.GetQueryParams()["Signature"]; containsSign { - delete(request.GetQueryParams(), "Signature") - } - stringToSign := buildRpcStringToSign(request) - request.SetStringToSign(stringToSign) - signature := signer.Sign(stringToSign, "&") - request.GetQueryParams()["Signature"] = signature - - return -} - -func completeRpcSignParams(request requests.AcsRequest, signer Signer, regionId string) (err error) { - queryParams := request.GetQueryParams() - queryParams["Version"] = request.GetVersion() - queryParams["Action"] = request.GetActionName() - queryParams["Format"] = request.GetAcceptFormat() - queryParams["Timestamp"] = utils.GetTimeInFormatISO8601() - queryParams["SignatureMethod"] = signer.GetName() - queryParams["SignatureType"] = signer.GetType() - queryParams["SignatureVersion"] = signer.GetVersion() - queryParams["SignatureNonce"] = utils.GetUUIDV4() - queryParams["AccessKeyId"], err = signer.GetAccessKeyId() - - if err != nil { - return - } - - if _, contains := queryParams["RegionId"]; !contains { - queryParams["RegionId"] = regionId - } - if extraParam := signer.GetExtraParam(); extraParam != nil { - for key, value := range extraParam { - queryParams[key] = value - } - } - - request.GetHeaders()["Content-Type"] = requests.Form - formString := utils.GetUrlFormedMap(request.GetFormParams()) - request.SetContent([]byte(formString)) - - return -} - -func buildRpcStringToSign(request requests.AcsRequest) (stringToSign string) { - signParams := make(map[string]string) - for key, value := range request.GetQueryParams() { - signParams[key] = value - } - for key, value := range request.GetFormParams() { - signParams[key] = value - } - - // sort params by key - var paramKeySlice []string - for key := range signParams { - paramKeySlice = append(paramKeySlice, key) - } - sort.Strings(paramKeySlice) - stringToSign = utils.GetUrlFormedMap(signParams) - stringToSign = strings.Replace(stringToSign, "+", "%20", -1) - stringToSign = strings.Replace(stringToSign, "*", "%2A", -1) - stringToSign = strings.Replace(stringToSign, "%7E", "~", -1) - stringToSign = url.QueryEscape(stringToSign) - stringToSign = request.GetMethod() + "&%2F&" + stringToSign - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go deleted file mode 100644 index ba946d0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 auth - -import ( - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "reflect" -) - -type Signer interface { - GetName() string - GetType() string - GetVersion() string - GetAccessKeyId() (string, error) - GetExtraParam() map[string]string - Sign(stringToSign, secretSuffix string) string - Shutdown() -} - -func NewSignerWithCredential(credential Credential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer Signer, err error) { - switch instance := credential.(type) { - case *credentials.AccessKeyCredential: - { - signer, err = signers.NewAccessKeySigner(instance) - } - case *credentials.StsTokenCredential: - { - signer, err = signers.NewStsTokenSigner(instance) - } - - case *credentials.RamRoleArnCredential: - { - signer, err = signers.NewRamRoleArnSigner(instance, commonApi) - } - case *credentials.RsaKeyPairCredential: - { - signer, err = signers.NewSignerKeyPair(instance, commonApi) - } - case *credentials.EcsRamRoleCredential: - { - signer, err = signers.NewEcsRamRoleSigner(instance, commonApi) - } - case *credentials.BaseCredential: // deprecated user interface - { - signer, err = signers.NewAccessKeySigner(instance.ToAccessKeyCredential()) - } - case *credentials.StsRoleArnCredential: // deprecated user interface - { - signer, err = signers.NewRamRoleArnSigner(instance.ToRamRoleArnCredential(), commonApi) - } - case *credentials.StsRoleNameOnEcsCredential: // deprecated user interface - { - signer, err = signers.NewEcsRamRoleSigner(instance.ToEcsRamRoleCredential(), commonApi) - } - default: - message := fmt.Sprintf(errors.UnsupportedCredentialErrorMessage, reflect.TypeOf(credential)) - err = errors.NewClientError(errors.UnsupportedCredentialErrorCode, message, nil) - } - return -} - -func Sign(request requests.AcsRequest, signer Signer, regionId string) (err error) { - switch request.GetStyle() { - case requests.ROA: - { - signRoaRequest(request, signer, regionId) - } - case requests.RPC: - { - err = signRpcRequest(request, signer, regionId) - } - default: - message := fmt.Sprintf(errors.UnknownRequestTypeErrorMessage, reflect.TypeOf(request)) - err = errors.NewClientError(errors.UnknownRequestTypeErrorCode, message, nil) - } - - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go deleted file mode 100644 index 975e985..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "crypto" - "crypto/hmac" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" - "fmt" - /*"encoding/pem" - "io/ioutil" - "os/user" - "crypto/sha256"*/) - -func ShaHmac1(source, secret string) string { - key := []byte(secret) - hmac := hmac.New(sha1.New, key) - hmac.Write([]byte(source)) - signedBytes := hmac.Sum(nil) - signedString := base64.StdEncoding.EncodeToString(signedBytes) - return signedString -} - -func Sha256WithRsa(source, secret string) string { - decodeString, err := base64.StdEncoding.DecodeString(secret) - if err != nil { - fmt.Println("DecodeString err", err) - } - private, err := x509.ParsePKCS8PrivateKey(decodeString) - if err != nil { - fmt.Println("ParsePKCS8PrivateKey err", err) - } - - h := crypto.Hash.New(crypto.SHA256) - h.Write([]byte(source)) - hashed := h.Sum(nil) - signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey), - crypto.SHA256, hashed) - if err != nil { - fmt.Println("Error from signing:", err) - return "" - } - - signedString := base64.StdEncoding.EncodeToString(signature) - //fmt.Printf("Encoded: %v\n", signedString) - return signedString -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go deleted file mode 100644 index bb73d24..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "time" -) - -const defaultInAdvanceScale = 0.8 - -type credentialUpdater struct { - credentialExpiration int - lastUpdateTimestamp int64 - inAdvanceScale float64 - buildRequestMethod func() (*requests.CommonRequest, error) - responseCallBack func(response *responses.CommonResponse) error - refreshApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) -} - -func (updater *credentialUpdater) needUpdateCredential() (result bool) { - if updater.inAdvanceScale == 0 { - updater.inAdvanceScale = defaultInAdvanceScale - } - return time.Now().Unix()-updater.lastUpdateTimestamp >= int64(float64(updater.credentialExpiration)*updater.inAdvanceScale) -} - -func (updater *credentialUpdater) updateCredential() (err error) { - request, err := updater.buildRequestMethod() - if err != nil { - return - } - response, err := updater.refreshApi(request) - if err != nil { - return - } - updater.lastUpdateTimestamp = time.Now().Unix() - err = updater.responseCallBack(response) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go deleted file mode 100644 index 99c624c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go +++ /dev/null @@ -1,7 +0,0 @@ -package signers - -type SessionCredential struct { - AccessKeyId string - AccessKeySecret string - StsToken string -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go deleted file mode 100644 index 92466ea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type AccessKeySigner struct { - credential *credentials.AccessKeyCredential -} - -func (signer *AccessKeySigner) GetExtraParam() map[string]string { - return nil -} - -func NewAccessKeySigner(credential *credentials.AccessKeyCredential) (*AccessKeySigner, error) { - return &AccessKeySigner{ - credential: credential, - }, nil -} - -func (*AccessKeySigner) GetName() string { - return "HMAC-SHA1" -} - -func (*AccessKeySigner) GetType() string { - return "" -} - -func (*AccessKeySigner) GetVersion() string { - return "1.0" -} - -func (signer *AccessKeySigner) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.AccessKeyId, nil -} - -func (signer *AccessKeySigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *AccessKeySigner) Shutdown() { - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go deleted file mode 100644 index 6cacc14..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/jmespath/go-jmespath" - "net/http" - "strings" - "time" -) - -type EcsRamRoleSigner struct { - *credentialUpdater - sessionCredential *SessionCredential - credential *credentials.EcsRamRoleCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewEcsRamRoleSigner(credential *credentials.EcsRamRoleCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *EcsRamRoleSigner, err error) { - signer = &EcsRamRoleSigner{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: defaultDurationSeconds / 60, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - return -} - -func (*EcsRamRoleSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*EcsRamRoleSigner) GetType() string { - return "" -} - -func (*EcsRamRoleSigner) GetVersion() string { - return "1.0" -} - -func (signer *EcsRamRoleSigner) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - } - if err != nil && (signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0) { - return "", err - } - return signer.sessionCredential.AccessKeyId, nil -} - -func (signer *EcsRamRoleSigner) GetExtraParam() map[string]string { - if signer.sessionCredential == nil { - return make(map[string]string) - } - if len(signer.sessionCredential.StsToken) <= 0 { - return make(map[string]string) - } - return map[string]string{"SecurityToken": signer.sessionCredential.StsToken} -} - -func (signer *EcsRamRoleSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeyId + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *EcsRamRoleSigner) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - return -} - -func (signer *EcsRamRoleSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - requestUrl := "http://100.100.100.200/latest/meta-data/ram/security-credentials/" + signer.credential.RoleName - httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader("")) - if err != nil { - fmt.Println("refresh Ecs sts token err", err) - return - } - httpClient := &http.Client{} - httpResponse, err := httpClient.Do(httpRequest) - if err != nil { - fmt.Println("refresh Ecs sts token err", err) - return - } - - response = responses.NewCommonResponse() - err = responses.Unmarshal(response, httpResponse, "") - - return -} - -func (signer *EcsRamRoleSigner) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - fmt.Println("refresh Ecs sts token err, httpStatus: " + string(response.GetHttpStatus()) + ", message = " + response.GetHttpContentString()) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - fmt.Println("refresh Ecs sts token err, json.Unmarshal fail", err) - return - } - code, err := jmespath.Search("Code", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get Code", err) - return - } - if code.(string) != "Success" { - fmt.Println("refresh Ecs sts token err, Code is not Success", err) - return - } - accessKeyId, err := jmespath.Search("AccessKeyId", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get AccessKeyId", err) - return - } - accessKeySecret, err := jmespath.Search("AccessKeySecret", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get AccessKeySecret", err) - return - } - securityToken, err := jmespath.Search("SecurityToken", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get SecurityToken", err) - return - } - expiration, err := jmespath.Search("Expiration", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get Expiration", err) - return - } - if accessKeyId == nil || accessKeySecret == nil || securityToken == nil { - return - } - - expirationTime, err := time.Parse("2006-01-02T15:04:05Z", expiration.(string)) - signer.credentialExpiration = int(expirationTime.Unix() - time.Now().Unix()) - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - StsToken: securityToken.(string), - } - - return -} - -func (signer *EcsRamRoleSigner) GetSessionCredential() *SessionCredential { - return signer.sessionCredential -} - -func (signer *EcsRamRoleSigner) Shutdown() { - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go deleted file mode 100644 index c5fe394..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/jmespath/go-jmespath" - "net/http" - "strconv" -) - -type SignerKeyPair struct { - *credentialUpdater - sessionCredential *SessionCredential - credential *credentials.RsaKeyPairCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewSignerKeyPair(credential *credentials.RsaKeyPairCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *SignerKeyPair, err error) { - signer = &SignerKeyPair{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: credential.SessionExpiration, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - if credential.SessionExpiration > 0 { - if credential.SessionExpiration >= 900 && credential.SessionExpiration <= 3600 { - signer.credentialExpiration = credential.SessionExpiration - } else { - err = errors.NewClientError(errors.InvalidParamErrorCode, "Key Pair session duration should be in the range of 15min - 1Hr", nil) - } - } else { - signer.credentialExpiration = defaultDurationSeconds - } - return -} - -func (*SignerKeyPair) GetName() string { - return "HMAC-SHA1" -} - -func (*SignerKeyPair) GetType() string { - return "" -} - -func (*SignerKeyPair) GetVersion() string { - return "1.0" -} - -func (signer *SignerKeyPair) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - } - if err != nil && (signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0) { - return "", err - } - return signer.sessionCredential.AccessKeyId, err -} - -func (signer *SignerKeyPair) GetExtraParam() map[string]string { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - signer.updateCredential() - } - if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 { - return make(map[string]string) - } - return make(map[string]string) -} - -func (signer *SignerKeyPair) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeyId + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *SignerKeyPair) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - request.Product = "Sts" - request.Version = "2015-04-01" - request.ApiName = "GenerateSessionAccessKey" - request.Scheme = requests.HTTPS - request.QueryParams["PublicKeyId"] = signer.credential.PublicKeyId - request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration) - return -} - -func (signerKeyPair *SignerKeyPair) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - signerV2, err := NewSignerV2(signerKeyPair.credential) - return signerKeyPair.commonApi(request, signerV2) -} - -func (signer *SignerKeyPair) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - message := "refresh session AccessKey failed" - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - fmt.Println("refresh KeyPair err, json.Unmarshal fail", err) - return - } - accessKeyId, err := jmespath.Search("SessionAccessKey.SessionAccessKeyId", data) - if err != nil { - fmt.Println("refresh KeyPair err, fail to get SessionAccessKeyId", err) - return - } - accessKeySecret, err := jmespath.Search("SessionAccessKey.SessionAccessKeySecret", data) - if err != nil { - fmt.Println("refresh KeyPair err, fail to get SessionAccessKeySecret", err) - return - } - if accessKeyId == nil || accessKeySecret == nil { - return - } - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - } - return -} - -func (signer *SignerKeyPair) Shutdown() { - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go deleted file mode 100644 index bfcaa95..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/jmespath/go-jmespath" - "net/http" - "strconv" - "time" -) - -const ( - defaultDurationSeconds = 3600 -) - -type RamRoleArnSigner struct { - *credentialUpdater - roleSessionName string - sessionCredential *SessionCredential - credential *credentials.RamRoleArnCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewRamRoleArnSigner(credential *credentials.RamRoleArnCredential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer *RamRoleArnSigner, err error) { - signer = &RamRoleArnSigner{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: credential.RoleSessionExpiration, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - if len(credential.RoleSessionName) > 0 { - signer.roleSessionName = credential.RoleSessionName - } else { - signer.roleSessionName = "aliyun-go-sdk-" + strconv.FormatInt(time.Now().UnixNano()/1000, 10) - } - if credential.RoleSessionExpiration > 0 { - if credential.RoleSessionExpiration >= 900 && credential.RoleSessionExpiration <= 3600 { - signer.credentialExpiration = credential.RoleSessionExpiration - } else { - err = errors.NewClientError(errors.InvalidParamErrorCode, "Assume Role session duration should be in the range of 15min - 1Hr", nil) - } - } else { - signer.credentialExpiration = defaultDurationSeconds - } - return -} - -func (*RamRoleArnSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*RamRoleArnSigner) GetType() string { - return "" -} - -func (*RamRoleArnSigner) GetVersion() string { - return "1.0" -} - -func (signer *RamRoleArnSigner) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - } - if err != nil && (signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0) { - return "", err - } - return signer.sessionCredential.AccessKeyId, nil -} - -func (signer *RamRoleArnSigner) GetExtraParam() map[string]string { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - signer.updateCredential() - } - if signer.sessionCredential == nil || len(signer.sessionCredential.StsToken) <= 0 { - return make(map[string]string) - } - return map[string]string{"SecurityToken": signer.sessionCredential.StsToken} -} - -func (signer *RamRoleArnSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *RamRoleArnSigner) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - request.Product = "Sts" - request.Version = "2015-04-01" - request.ApiName = "AssumeRole" - request.Scheme = requests.HTTPS - request.QueryParams["RoleArn"] = signer.credential.RoleArn - request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName - request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration) - return -} - -func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - credential := &credentials.AccessKeyCredential{ - AccessKeyId: signer.credential.AccessKeyId, - AccessKeySecret: signer.credential.AccessKeySecret, - } - signerV1, err := NewAccessKeySigner(credential) - return signer.commonApi(request, signerV1) -} - -func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - message := "refresh session token failed" - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, json.Unmarshal fail", err) - return - } - accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, fail to get AccessKeyId", err) - return - } - accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, fail to get AccessKeySecret", err) - return - } - securityToken, err := jmespath.Search("Credentials.SecurityToken", data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, fail to get SecurityToken", err) - return - } - if accessKeyId == nil || accessKeySecret == nil || securityToken == nil { - return - } - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - StsToken: securityToken.(string), - } - return -} - -func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential { - return signer.sessionCredential -} - -func (signer *RamRoleArnSigner) Shutdown() { - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go deleted file mode 100644 index 9e178d0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type StsTokenSigner struct { - credential *credentials.StsTokenCredential -} - -func NewStsTokenSigner(credential *credentials.StsTokenCredential) (*StsTokenSigner, error) { - return &StsTokenSigner{ - credential: credential, - }, nil -} - -func (*StsTokenSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*StsTokenSigner) GetType() string { - return "" -} - -func (*StsTokenSigner) GetVersion() string { - return "1.0" -} - -func (signer *StsTokenSigner) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.AccessKeyId, nil -} - -func (signer *StsTokenSigner) GetExtraParam() map[string]string { - return map[string]string{"SecurityToken": signer.credential.AccessKeyStsToken} -} - -func (signer *StsTokenSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *StsTokenSigner) Shutdown() { - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go deleted file mode 100644 index 1814fe7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type SignerV2 struct { - credential *credentials.RsaKeyPairCredential -} - -func (signer *SignerV2) GetExtraParam() map[string]string { - return nil -} - -func NewSignerV2(credential *credentials.RsaKeyPairCredential) (*SignerV2, error) { - return &SignerV2{ - credential: credential, - }, nil -} - -func (*SignerV2) GetName() string { - return "SHA256withRSA" -} - -func (*SignerV2) GetType() string { - return "PRIVATEKEY" -} - -func (*SignerV2) GetVersion() string { - return "1.0" -} - -func (signer *SignerV2) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.PublicKeyId, err -} - -func (signer *SignerV2) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.PrivateKey - return Sha256WithRsa(stringToSign, secret) -} - -func (signer *SignerV2) Shutdown() { - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go deleted file mode 100644 index e204676..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 sdk - -import ( - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "net" - "net/http" - "strconv" - "sync" -) - -// this value will be replaced while build: -ldflags="-X sdk.version=x.x.x" -var Version = "0.0.1" - -type Client struct { - regionId string - config *Config - signer auth.Signer - httpClient *http.Client - asyncTaskQueue chan func() - - debug bool - isRunning bool - // void "panic(write to close channel)" cause of addAsync() after Shutdown() - asyncChanLock *sync.RWMutex -} - -func (client *Client) Init() (err error) { - panic("not support yet") -} - -func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) { - client.isRunning = true - client.asyncChanLock = new(sync.RWMutex) - client.regionId = regionId - client.config = config - if err != nil { - return - } - client.httpClient = &http.Client{} - - if config.HttpTransport != nil { - client.httpClient.Transport = config.HttpTransport - } - - if config.Timeout > 0 { - client.httpClient.Timeout = config.Timeout - } - - if config.EnableAsync { - client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize) - } - - client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner) - - return -} - -func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) { - client.asyncTaskQueue = make(chan func(), maxTaskQueueSize) - for i := 0; i < routinePoolSize; i++ { - go func() { - for client.isRunning { - select { - case task, notClosed := <-client.asyncTaskQueue: - if notClosed { - task() - } - } - } - }() - } -} - -func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) { - config := client.InitClientConfig() - credential := &credentials.BaseCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) { - config := client.InitClientConfig() - credential := &credentials.StsTokenCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - AccessKeyStsToken: securityToken, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) { - config := client.InitClientConfig() - credential := &credentials.RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) { - config := client.InitClientConfig() - credential := &credentials.RsaKeyPairCredential{ - PrivateKey: privateKey, - PublicKeyId: publicKeyId, - SessionExpiration: sessionExpiration, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) { - config := client.InitClientConfig() - credential := &credentials.EcsRamRoleCredential{ - RoleName: roleName, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitClientConfig() (config *Config) { - if client.config != nil { - return client.config - } else { - return NewConfig() - } -} - -func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) { - return client.DoActionWithSigner(request, response, nil) -} - -func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) { - // add clientVersion - request.GetHeaders()["x-sdk-core-version"] = Version - - regionId := client.regionId - if len(request.GetRegionId()) > 0 { - regionId = request.GetRegionId() - } - - // resolve endpoint - resolveParam := &endpoints.ResolveParam{ - Domain: request.GetDomain(), - Product: request.GetProduct(), - RegionId: regionId, - LocationProduct: request.GetLocationServiceCode(), - LocationEndpointType: request.GetLocationEndpointType(), - CommonApi: client.ProcessCommonRequest, - } - endpoint, err := endpoints.Resolve(resolveParam) - if err != nil { - return - } - request.SetDomain(endpoint) - - // init request params - err = requests.InitParams(request) - if err != nil { - return - } - - // signature - var finalSigner auth.Signer - if signer != nil { - finalSigner = signer - } else { - finalSigner = client.signer - } - httpRequest, err := buildHttpRequest(request, finalSigner, regionId) - if client.config.UserAgent != "" { - httpRequest.Header.Set("User-Agent", client.config.UserAgent) - } - return err -} - -func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) { - - // add clientVersion - request.GetHeaders()["x-sdk-core-version"] = Version - - regionId := client.regionId - if len(request.GetRegionId()) > 0 { - regionId = request.GetRegionId() - } - - // resolve endpoint - resolveParam := &endpoints.ResolveParam{ - Domain: request.GetDomain(), - Product: request.GetProduct(), - RegionId: regionId, - LocationProduct: request.GetLocationServiceCode(), - LocationEndpointType: request.GetLocationEndpointType(), - CommonApi: client.ProcessCommonRequest, - } - endpoint, err := endpoints.Resolve(resolveParam) - if err != nil { - return - } - request.SetDomain(endpoint) - - if request.GetScheme() == "" { - request.SetScheme(client.config.Scheme) - } - // init request params - err = requests.InitParams(request) - if err != nil { - return - } - - // signature - var finalSigner auth.Signer - if signer != nil { - finalSigner = signer - } else { - finalSigner = client.signer - } - httpRequest, err := buildHttpRequest(request, finalSigner, regionId) - if client.config.UserAgent != "" { - httpRequest.Header.Set("User-Agent", client.config.UserAgent) - } - if err != nil { - return - } - var httpResponse *http.Response - for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ { - httpResponse, err = client.httpClient.Do(httpRequest) - - var timeout bool - // receive error - if err != nil { - if !client.config.AutoRetry { - return - } else if timeout = isTimeout(err); !timeout { - // if not timeout error, return - return - } else if retryTimes >= client.config.MaxRetryTime { - // timeout but reached the max retry times, return - timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, strconv.Itoa(retryTimes+1), strconv.Itoa(retryTimes+1)) - err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err) - return - } - } - // if status code >= 500 or timeout, will trigger retry - if client.config.AutoRetry && (timeout || isServerError(httpResponse)) { - // rewrite signatureNonce and signature - httpRequest, err = buildHttpRequest(request, finalSigner, regionId) - if err != nil { - return - } - continue - } - break - } - err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat()) - // wrap server errors - if serverErr, ok := err.(*errors.ServerError); ok { - var wrapInfo = map[string]string{} - wrapInfo["StringToSign"] = request.GetStringToSign() - err = errors.WrapServerError(serverErr, wrapInfo) - } - return -} - -func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) { - err = auth.Sign(request, singer, regionId) - if err != nil { - return - } - requestMethod := request.GetMethod() - requestUrl := request.BuildUrl() - body := request.GetBodyReader() - httpRequest, err = http.NewRequest(requestMethod, requestUrl, body) - if err != nil { - return - } - for key, value := range request.GetHeaders() { - httpRequest.Header[key] = []string{value} - } - // host is a special case - if host, containsHost := request.GetHeaders()["Host"]; containsHost { - httpRequest.Host = host - } - return -} - -func isTimeout(err error) bool { - if err == nil { - return false - } - netErr, isNetError := err.(net.Error) - return isNetError && netErr.Timeout() -} - -func isServerError(httpResponse *http.Response) bool { - return httpResponse.StatusCode >= http.StatusInternalServerError -} - -/** -only block when any one of the following occurs: -1. the asyncTaskQueue is full, increase the queue size to avoid this -2. Shutdown() in progressing, the client is being closed -**/ -func (client *Client) AddAsyncTask(task func()) (err error) { - if client.asyncTaskQueue != nil { - client.asyncChanLock.RLock() - defer client.asyncChanLock.RUnlock() - if client.isRunning { - client.asyncTaskQueue <- task - } - } else { - err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil) - } - return -} - -func (client *Client) GetConfig() *Config { - return client.config -} - -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - return -} - -func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - return -} - -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - return -} - -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - return -} - -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - return -} - -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - return -} - -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - return -} - -// Deprecated: Use NewClientWithRamRoleArn in this package instead. -func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) -} - -// Deprecated: Use NewClientWithEcsRamRole in this package instead. -func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) { - return NewClientWithEcsRamRole(regionId, roleName) -} - -func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - request.TransToAcsRequest() - response = responses.NewCommonResponse() - err = client.DoAction(request, response) - return -} - -func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) { - if signer, isSigner := signerInterface.(auth.Signer); isSigner { - request.TransToAcsRequest() - response = responses.NewCommonResponse() - err = client.DoActionWithSigner(request, response, signer) - return - } else { - panic("should not be here") - } -} - -func (client *Client) Shutdown() { - client.signer.Shutdown() - // lock the addAsync() - client.asyncChanLock.Lock() - defer client.asyncChanLock.Unlock() - client.isRunning = false - close(client.asyncTaskQueue) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go deleted file mode 100644 index c67c2ad..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 sdk - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "net/http" - "time" -) - -type Config struct { - AutoRetry bool `default:"true"` - MaxRetryTime int `default:"3"` - UserAgent string `default:""` - Debug bool `default:"false"` - Timeout time.Duration `default:"10000000000"` - HttpTransport *http.Transport `default:""` - EnableAsync bool `default:"false"` - MaxTaskQueueSize int `default:"1000"` - GoRoutinePoolSize int `default:"5"` - Scheme string `default:"HTTP"` -} - -func NewConfig() (config *Config) { - config = &Config{} - utils.InitStructWithDefaultTag(config) - return -} - -func (c *Config) WithTimeout(timeout time.Duration) *Config { - c.Timeout = timeout - return c -} - -func (c *Config) WithAutoRetry(isAutoRetry bool) *Config { - c.AutoRetry = isAutoRetry - return c -} - -func (c *Config) WithMaxRetryTime(maxRetryTime int) *Config { - c.MaxRetryTime = maxRetryTime - return c -} - -func (c *Config) WithUserAgent(userAgent string) *Config { - c.UserAgent = userAgent - return c -} - -func (c *Config) WithHttpTransport(httpTransport *http.Transport) *Config { - c.HttpTransport = httpTransport - return c -} - -func (c *Config) WithEnableAsync(isEnableAsync bool) *Config { - c.EnableAsync = isEnableAsync - return c -} - -func (c *Config) WithMaxTaskQueueSize(maxTaskQueueSize int) *Config { - c.MaxTaskQueueSize = maxTaskQueueSize - return c -} - -func (c *Config) WithGoRoutinePoolSize(goRoutinePoolSize int) *Config { - c.GoRoutinePoolSize = goRoutinePoolSize - return c -} - -func (c *Config) WithDebug(isDebug bool) *Config { - c.Debug = isDebug - return c -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go deleted file mode 100644 index ec0d56f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go +++ /dev/null @@ -1,505 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "sync" -) - -const endpointsJson = "{" + - " \"products\":[" + - " {" + - " \"code\": \"aegis\"," + - " \"document_id\": \"28449\"," + - " \"location_service_code\": \"vipaegis\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"aegis.cn-hangzhou.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"alidns\"," + - " \"document_id\": \"29739\"," + - " \"location_service_code\": \"alidns\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"alidns.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"arms\"," + - " \"document_id\": \"42924\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-southeast-1\"," + - " \"endpoint\": \"arms.ap-southeast-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"arms.cn-beijing.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"arms.cn-hangzhou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hongkong\"," + - " \"endpoint\": \"arms.cn-hongkong.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-qingdao\"," + - " \"endpoint\": \"arms.cn-qingdao.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"arms.cn-shanghai.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shenzhen\"," + - " \"endpoint\": \"arms.cn-shenzhen.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"arms.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"batchcompute\"," + - " \"document_id\": \"44717\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-southeast-1\"," + - " \"endpoint\": \"batchcompute.ap-southeast-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"batchcompute.cn-beijing.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"batchcompute.cn-hangzhou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-huhehaote\"," + - " \"endpoint\": \"batchcompute.cn-huhehaote.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-qingdao\"," + - " \"endpoint\": \"batchcompute.cn-qingdao.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"batchcompute.cn-shanghai.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shenzhen\"," + - " \"endpoint\": \"batchcompute.cn-shenzhen.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-zhangjiakou\"," + - " \"endpoint\": \"batchcompute.cn-zhangjiakou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-west-1\"," + - " \"endpoint\": \"batchcompute.us-west-1.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"batchcompute.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"ccc\"," + - " \"document_id\": \"63027\"," + - " \"location_service_code\": \"ccc\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"ccc.cn-hangzhou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"ccc.cn-shanghai.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"ccc.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cdn\"," + - " \"document_id\": \"27148\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cdn.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cds\"," + - " \"document_id\": \"62887\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cds.cn-beijing.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"chatbot\"," + - " \"document_id\": \"60760\"," + - " \"location_service_code\": \"beebot\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"chatbot.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cloudapi\"," + - " \"document_id\": \"43590\"," + - " \"location_service_code\": \"apigateway\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-northeast-1\"," + - " \"endpoint\": \"apigateway.ap-northeast-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-west-1\"," + - " \"endpoint\": \"apigateway.us-west-1.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"apigateway.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cloudauth\"," + - " \"document_id\": \"60687\"," + - " \"location_service_code\": \"cloudauth\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cloudauth.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cloudphoto\"," + - " \"document_id\": \"59902\"," + - " \"location_service_code\": \"cloudphoto\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"cloudphoto.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cloudwf\"," + - " \"document_id\": \"58111\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cloudwf.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cms\"," + - " \"document_id\": \"28615\"," + - " \"location_service_code\": \"cms\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cr\"," + - " \"document_id\": \"60716\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cr.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cs\"," + - " \"document_id\": \"26043\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cs.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"csb\"," + - " \"document_id\": \"64837\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"csb.cn-beijing.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"csb.cn-hangzhou.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"csb.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"dds\"," + - " \"document_id\": \"61715\"," + - " \"location_service_code\": \"dds\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"mongodb.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"mongodb.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"dm\"," + - " \"document_id\": \"29434\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-southeast-1\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"ap-southeast-2\"," + - " \"endpoint\": \"dm.ap-southeast-2.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hongkong\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-qingdao\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shenzhen\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-east-1\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-west-1\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"dm.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"dm.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"domain\"," + - " \"document_id\": \"42875\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"domain.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"domain.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"domain-intl\"," + - " \"document_id\": \"\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"domain-intl.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"domain-intl.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"drds\"," + - " \"document_id\": \"51111\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"drds.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"drds.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"ecs\"," + - " \"document_id\": \"25484\"," + - " \"location_service_code\": \"ecs\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"emr\"," + - " \"document_id\": \"28140\"," + - " \"location_service_code\": \"emr\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"emr.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"ess\"," + - " \"document_id\": \"25925\"," + - " \"location_service_code\": \"ess\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"ess.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"green\"," + - " \"document_id\": \"28427\"," + - " \"location_service_code\": \"green\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"green.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"hpc\"," + - " \"document_id\": \"35201\"," + - " \"location_service_code\": \"hpc\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"hpc.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"httpdns\"," + - " \"document_id\": \"52679\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"httpdns-api.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"iot\"," + - " \"document_id\": \"30557\"," + - " \"location_service_code\": \"iot\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"iot.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"itaas\"," + - " \"document_id\": \"55759\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"itaas.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"jaq\"," + - " \"document_id\": \"35037\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"jaq.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"live\"," + - " \"document_id\": \"48207\"," + - " \"location_service_code\": \"live\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"live.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"mts\"," + - " \"document_id\": \"29212\"," + - " \"location_service_code\": \"mts\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"nas\"," + - " \"document_id\": \"62598\"," + - " \"location_service_code\": \"nas\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"ons\"," + - " \"document_id\": \"44416\"," + - " \"location_service_code\": \"ons\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"polardb\"," + - " \"document_id\": \"58764\"," + - " \"location_service_code\": \"polardb\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-south-1\"," + - " \"endpoint\": \"polardb.ap-south-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"ap-southeast-5\"," + - " \"endpoint\": \"polardb.ap-southeast-5.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"polardb.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"push\"," + - " \"document_id\": \"30074\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cloudpush.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"qualitycheck\"," + - " \"document_id\": \"50807\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"qualitycheck.cn-hangzhou.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"r-kvstore\"," + - " \"document_id\": \"60831\"," + - " \"location_service_code\": \"redisa\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"ram\"," + - " \"document_id\": \"28672\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"ram.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"rds\"," + - " \"document_id\": \"26223\"," + - " \"location_service_code\": \"rds\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"ros\"," + - " \"document_id\": \"28899\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"ros.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"sas-api\"," + - " \"document_id\": \"28498\"," + - " \"location_service_code\": \"sas\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"slb\"," + - " \"document_id\": \"27565\"," + - " \"location_service_code\": \"slb\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"sts\"," + - " \"document_id\": \"28756\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"sts.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"vod\"," + - " \"document_id\": \"60574\"," + - " \"location_service_code\": \"vod\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"vpc\"," + - " \"document_id\": \"34962\"," + - " \"location_service_code\": \"vpc\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"waf\"," + - " \"document_id\": \"62847\"," + - " \"location_service_code\": \"waf\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }]" + - "}" - -var initOnce sync.Once -var data interface{} - -func getEndpointConfigData() interface{} { - initOnce.Do(func() { - err := json.Unmarshal([]byte(endpointsJson), &data) - if err != nil { - fmt.Println("init endpoint config data failed.", err) - } - }) - return data -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go deleted file mode 100644 index 864b7cc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 endpoints - -import ( - "fmt" - "github.com/jmespath/go-jmespath" - "strings" -) - -type LocalGlobalResolver struct { -} - -func (resolver *LocalGlobalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - // get the global endpoints configs - endpointExpression := fmt.Sprintf("products[?code=='%s'].global_endpoint", strings.ToLower(param.Product)) - endpointData, err := jmespath.Search(endpointExpression, getEndpointConfigData()) - if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 { - endpoint = endpointData.([]interface{})[0].(string) - support = len(endpoint) > 0 - return endpoint, support, nil - } - support = false - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go deleted file mode 100644 index f8aa0f9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 endpoints - -import ( - "fmt" - "github.com/jmespath/go-jmespath" - "strings" -) - -type LocalRegionalResolver struct { -} - -func (resolver *LocalRegionalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - // get the regional endpoints configs - regionalExpression := fmt.Sprintf("products[?code=='%s'].regional_endpoints", strings.ToLower(param.Product)) - regionalData, err := jmespath.Search(regionalExpression, getEndpointConfigData()) - if err == nil && regionalData != nil && len(regionalData.([]interface{})) > 0 { - endpointExpression := fmt.Sprintf("[0][?region=='%s'].endpoint", strings.ToLower(param.RegionId)) - endpointData, err := jmespath.Search(endpointExpression, regionalData) - if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 { - endpoint = endpointData.([]interface{})[0].(string) - support = len(endpoint) > 0 - return endpoint, support, nil - } - } - support = false - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go deleted file mode 100644 index 803bc57..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 endpoints - -import ( - "encoding/json" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "sync" - "time" -) - -const ( - EndpointCacheExpireTime = 3600 //Seconds -) - -var lastClearTimePerProduct = struct { - sync.RWMutex - cache map[string]int64 -}{cache: make(map[string]int64)} - -var endpointCache = struct { - sync.RWMutex - cache map[string]string -}{cache: make(map[string]string)} - -type LocationResolver struct { -} - -func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - if len(param.LocationProduct) <= 0 { - support = false - return - } - - //get from cache - cacheKey := param.Product + "#" + param.RegionId - if endpointCache.cache != nil && len(endpointCache.cache[cacheKey]) > 0 && !CheckCacheIsExpire(cacheKey) { - endpoint = endpointCache.cache[cacheKey] - support = true - return - } - - //get from remote - getEndpointRequest := requests.NewCommonRequest() - - getEndpointRequest.Product = "Location" - getEndpointRequest.Version = "2015-06-12" - getEndpointRequest.ApiName = "DescribeEndpoints" - getEndpointRequest.Domain = "location.aliyuncs.com" - getEndpointRequest.Method = "GET" - getEndpointRequest.Scheme = requests.HTTPS - - getEndpointRequest.QueryParams["Id"] = param.RegionId - getEndpointRequest.QueryParams["ServiceCode"] = param.LocationProduct - if len(param.LocationEndpointType) > 0 { - getEndpointRequest.QueryParams["Type"] = param.LocationEndpointType - } else { - getEndpointRequest.QueryParams["Type"] = "openAPI" - } - - response, err := param.CommonApi(getEndpointRequest) - var getEndpointResponse GetEndpointResponse - if !response.IsSuccess() { - support = false - return - } - - json.Unmarshal([]byte(response.GetHttpContentString()), &getEndpointResponse) - if !getEndpointResponse.Success || getEndpointResponse.Endpoints == nil { - support = false - return - } - if len(getEndpointResponse.Endpoints.Endpoint) <= 0 { - support = false - return - } - if len(getEndpointResponse.Endpoints.Endpoint[0].Endpoint) > 0 { - endpoint = getEndpointResponse.Endpoints.Endpoint[0].Endpoint - endpointCache.Lock() - endpointCache.cache[cacheKey] = endpoint - endpointCache.Unlock() - lastClearTimePerProduct.Lock() - lastClearTimePerProduct.cache[cacheKey] = time.Now().Unix() - lastClearTimePerProduct.Unlock() - support = true - return - } - - support = false - return -} - -func CheckCacheIsExpire(cacheKey string) bool { - lastClearTime := lastClearTimePerProduct.cache[cacheKey] - if lastClearTime <= 0 { - lastClearTime = time.Now().Unix() - lastClearTimePerProduct.Lock() - lastClearTimePerProduct.cache[cacheKey] = lastClearTime - lastClearTimePerProduct.Unlock() - } - - now := time.Now().Unix() - elapsedTime := now - lastClearTime - if elapsedTime > EndpointCacheExpireTime { - return true - } - - return false -} - -type GetEndpointResponse struct { - Endpoints *EndpointsObj - RequestId string - Success bool -} - -type EndpointsObj struct { - Endpoint []EndpointObj -} - -type EndpointObj struct { - Protocols map[string]string - Type string - Namespace string - Id string - SerivceCode string - Endpoint string -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go deleted file mode 100644 index f7b5a1a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 endpoints - -import ( - "fmt" - "strings" -) - -const keyFormatter = "%s::%s" - -var endpointMapping = make(map[string]string) - -func AddEndpointMapping(regionId, productId, endpoint string) (err error) { - key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId)) - endpointMapping[key] = endpoint - return nil -} - -type MappingResolver struct { -} - -func (resolver *MappingResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - key := fmt.Sprintf(keyFormatter, strings.ToLower(param.RegionId), strings.ToLower(param.Product)) - endpoint, contains := endpointMapping[key] - return endpoint, contains, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go deleted file mode 100644 index e58cfbf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 endpoints - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "sync" -) - -const ( - ResolveEndpointUserGuideLink = "" -) - -var once sync.Once -var resolvers []Resolver - -type Resolver interface { - TryResolve(param *ResolveParam) (endpoint string, support bool, err error) -} - -func Resolve(param *ResolveParam) (endpoint string, err error) { - supportedResolvers := getAllResolvers() - for _, resolver := range supportedResolvers { - endpoint, supported, err := resolver.TryResolve(param) - if supported { - return endpoint, err - } - } - - // not support - errorMsg := fmt.Sprintf(errors.CanNotResolveEndpointErrorMessage, param, ResolveEndpointUserGuideLink) - err = errors.NewClientError(errors.CanNotResolveEndpointErrorCode, errorMsg, nil) - return -} - -func getAllResolvers() []Resolver { - once.Do(func() { - resolvers = []Resolver{ - &SimpleHostResolver{}, - &MappingResolver{}, - &LocationResolver{}, - &LocalRegionalResolver{}, - &LocalGlobalResolver{}, - } - }) - return resolvers -} - -type ResolveParam struct { - Domain string - Product string - RegionId string - LocationProduct string - LocationEndpointType string - CommonApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) `json:"-"` -} - -func (param *ResolveParam) String() string { - jsonBytes, err := json.Marshal(param) - if err != nil { - return fmt.Sprint("ResolveParam.String() process error:", err) - } - return string(jsonBytes) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/simple_host_resolver.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/simple_host_resolver.go deleted file mode 100644 index 3e2e731..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/simple_host_resolver.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 endpoints - -type SimpleHostResolver struct { -} - -func (resolver *SimpleHostResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - if support = len(param.Domain) > 0; support { - endpoint = param.Domain - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go deleted file mode 100644 index 3d4048b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 errors - -import "fmt" - -const ( - DefaultClientErrorStatus = 400 - DefaultClientErrorCode = "SDK.ClientError" - - UnsupportedCredentialErrorCode = "SDK.UnsupportedCredential" - UnsupportedCredentialErrorMessage = "Specified credential (type = %s) is not supported, please check" - - CanNotResolveEndpointErrorCode = "SDK.CanNotResolveEndpoint" - CanNotResolveEndpointErrorMessage = "Can not resolve endpoint(param = %s), please check your accessKey with secret, and read the user guide\n %s" - - UnsupportedParamPositionErrorCode = "SDK.UnsupportedParamPosition" - UnsupportedParamPositionErrorMessage = "Specified param position (%s) is not supported, please upgrade sdk and retry" - - AsyncFunctionNotEnabledCode = "SDK.AsyncFunctionNotEnabled" - AsyncFunctionNotEnabledMessage = "Async function is not enabled in client, please invoke 'client.EnableAsync' function" - - UnknownRequestTypeErrorCode = "SDK.UnknownRequestType" - UnknownRequestTypeErrorMessage = "Unknown Request Type: %s" - - MissingParamErrorCode = "SDK.MissingParam" - InvalidParamErrorCode = "SDK.InvalidParam" - - JsonUnmarshalErrorCode = "SDK.JsonUnmarshalError" - JsonUnmarshalErrorMessage = "Failed to unmarshal response, but you can get the data via response.GetHttpStatusCode() and response.GetHttpContentString()" - - TimeoutErrorCode = "SDK.TimeoutError" - TimeoutErrorMessage = "The request timed out %s times(%s for retry), perhaps we should have the threshold raised a little?" -) - -type ClientError struct { - errorCode string - message string - originError error -} - -func NewClientError(errorCode, message string, originErr error) Error { - return &ClientError{ - errorCode: errorCode, - message: message, - originError: originErr, - } -} - -func (err *ClientError) Error() string { - clientErrMsg := fmt.Sprintf("[%s] %s", err.errorCode, err.message) - if err.originError != nil { - return clientErrMsg + "\ncaused by:\n" + err.originError.Error() - } - return clientErrMsg -} - -func (err *ClientError) OriginError() error { - return err.originError -} - -func (*ClientError) HttpStatus() int { - return DefaultClientErrorStatus -} - -func (err *ClientError) ErrorCode() string { - if err.errorCode == "" { - return DefaultClientErrorCode - } else { - return err.errorCode - } -} - -func (err *ClientError) Message() string { - return err.message -} - -func (err *ClientError) String() string { - return err.Error() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go deleted file mode 100644 index 49962f3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 errors - -type Error interface { - error - HttpStatus() int - ErrorCode() string - Message() string - OriginError() error -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go deleted file mode 100644 index d90638c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 errors - -import ( - "encoding/json" - "fmt" - "github.com/jmespath/go-jmespath" -) - -var wrapperList = []ServerErrorWrapper{ - &SignatureDostNotMatchWrapper{}, -} - -type ServerError struct { - httpStatus int - requestId string - hostId string - errorCode string - recommend string - message string - comment string -} - -type ServerErrorWrapper interface { - tryWrap(error *ServerError, wrapInfo map[string]string) (bool, *ServerError) -} - -func (err *ServerError) Error() string { - return fmt.Sprintf("SDK.ServerError\nErrorCode: %s\nRecommend: %s\nRequestId: %s\nMessage: %s", - err.errorCode, err.comment+err.recommend, err.requestId, err.message) -} - -func NewServerError(httpStatus int, responseContent, comment string) Error { - result := &ServerError{ - httpStatus: httpStatus, - message: responseContent, - comment: comment, - } - - var data interface{} - err := json.Unmarshal([]byte(responseContent), &data) - if err == nil { - requestId, _ := jmespath.Search("RequestId", data) - hostId, _ := jmespath.Search("HostId", data) - errorCode, _ := jmespath.Search("Code", data) - recommend, _ := jmespath.Search("Recommend", data) - message, _ := jmespath.Search("Message", data) - - if requestId != nil { - result.requestId = requestId.(string) - } - if hostId != nil { - result.hostId = hostId.(string) - } - if errorCode != nil { - result.errorCode = errorCode.(string) - } - if recommend != nil { - result.recommend = recommend.(string) - } - if message != nil { - result.message = message.(string) - } - } - - return result -} - -func WrapServerError(originError *ServerError, wrapInfo map[string]string) *ServerError { - for _, wrapper := range wrapperList { - ok, newError := wrapper.tryWrap(originError, wrapInfo) - if ok { - return newError - } - } - return originError -} - -func (err *ServerError) HttpStatus() int { - return err.httpStatus -} - -func (err *ServerError) ErrorCode() string { - return err.errorCode -} - -func (err *ServerError) Message() string { - return err.message -} - -func (err *ServerError) OriginError() error { - return nil -} - -func (err *ServerError) HostId() string { - return err.hostId -} - -func (err *ServerError) RequestId() string { - return err.requestId -} - -func (err *ServerError) Recommend() string { - return err.recommend -} - -func (err *ServerError) Comment() string { - return err.comment -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go deleted file mode 100644 index 33b3e4c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go +++ /dev/null @@ -1,29 +0,0 @@ -package errors - -import "strings" - -const SignatureDostNotMatchErrorCode = "SignatureDoesNotMatch" -const MessagePrefix = "Specified signature is not matched with our calculation. server string to sign is:" - -type SignatureDostNotMatchWrapper struct { -} - -func (*SignatureDostNotMatchWrapper) tryWrap(error *ServerError, wrapInfo map[string]string) (bool, *ServerError) { - clientStringToSign := wrapInfo["StringToSign"] - if error.errorCode == SignatureDostNotMatchErrorCode && clientStringToSign != "" { - message := error.message - if strings.HasPrefix(message, MessagePrefix) { - serverStringToSign := message[len(MessagePrefix):] - if clientStringToSign == serverStringToSign { - // user secret is error - error.recommend = "Please check you AccessKeySecret" - } else { - error.recommend = "This may be a bug with the SDK and we hope you can submit this question in the " + - "github issue(https://github.com/aliyun/alibaba-cloud-sdk-go/issues), thanks very much" - } - } - return true, error - } else { - return false, nil - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_reqeust.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_reqeust.go deleted file mode 100644 index 5f4a42b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_reqeust.go +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 requests - -import ( - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "io" - "reflect" - "strconv" -) - -const ( - RPC = "RPC" - ROA = "ROA" - - HTTP = "HTTP" - HTTPS = "HTTPS" - - DefaultHttpPort = "80" - - GET = "GET" - PUT = "PUT" - POST = "POST" - DELETE = "DELETE" - HEAD = "HEAD" - OPTIONS = "OPTIONS" - - Json = "application/json" - Xml = "application/xml" - Raw = "application/octet-stream" - Form = "application/x-www-form-urlencoded" - - Header = "Header" - Query = "Query" - Body = "Body" - Path = "Path" - - HeaderSeparator = "\n" -) - -// interface -type AcsRequest interface { - GetScheme() string - GetMethod() string - GetDomain() string - GetPort() string - GetRegionId() string - GetUrl() string - GetQueries() string - GetHeaders() map[string]string - GetQueryParams() map[string]string - GetFormParams() map[string]string - GetContent() []byte - GetBodyReader() io.Reader - GetStyle() string - GetProduct() string - GetVersion() string - GetActionName() string - GetAcceptFormat() string - GetLocationServiceCode() string - GetLocationEndpointType() string - - SetStringToSign(stringToSign string) - GetStringToSign() string - - SetDomain(domain string) - SetContent(content []byte) - SetScheme(scheme string) - BuildUrl() string - BuildQueries() string - - addHeaderParam(key, value string) - addQueryParam(key, value string) - addFormParam(key, value string) - addPathParam(key, value string) -} - -// base class -type baseRequest struct { - Scheme string - Method string - Domain string - Port string - RegionId string - - product string - version string - - actionName string - - AcceptFormat string - - QueryParams map[string]string - Headers map[string]string - FormParams map[string]string - Content []byte - - locationServiceCode string - locationEndpointType string - - queries string - - stringToSign string -} - -func (request *baseRequest) GetQueryParams() map[string]string { - return request.QueryParams -} - -func (request *baseRequest) GetFormParams() map[string]string { - return request.FormParams -} - -func (request *baseRequest) GetContent() []byte { - return request.Content -} - -func (request *baseRequest) GetVersion() string { - return request.version -} - -func (request *baseRequest) GetActionName() string { - return request.actionName -} - -func (request *baseRequest) SetContent(content []byte) { - request.Content = content -} - -func (request *baseRequest) addHeaderParam(key, value string) { - request.Headers[key] = value -} - -func (request *baseRequest) addQueryParam(key, value string) { - request.QueryParams[key] = value -} - -func (request *baseRequest) addFormParam(key, value string) { - request.FormParams[key] = value -} - -func (request *baseRequest) GetAcceptFormat() string { - return request.AcceptFormat -} - -func (request *baseRequest) GetLocationServiceCode() string { - return request.locationServiceCode -} - -func (request *baseRequest) GetLocationEndpointType() string { - return request.locationEndpointType -} - -func (request *baseRequest) GetProduct() string { - return request.product -} - -func (request *baseRequest) GetScheme() string { - return request.Scheme -} - -func (request *baseRequest) SetScheme(scheme string) { - request.Scheme = scheme -} - -func (request *baseRequest) GetMethod() string { - return request.Method -} - -func (request *baseRequest) GetDomain() string { - return request.Domain -} - -func (request *baseRequest) SetDomain(host string) { - request.Domain = host -} - -func (request *baseRequest) GetPort() string { - return request.Port -} - -func (request *baseRequest) GetRegionId() string { - return request.RegionId -} - -func (request *baseRequest) GetHeaders() map[string]string { - return request.Headers -} - -func (request *baseRequest) SetContentType(contentType string) { - request.Headers["Content-Type"] = contentType -} - -func (request *baseRequest) GetContentType() (contentType string, contains bool) { - contentType, contains = request.Headers["Content-Type"] - return -} - -func (request *baseRequest) SetStringToSign(stringToSign string) { - request.stringToSign = stringToSign -} - -func (request *baseRequest) GetStringToSign() string { - return request.stringToSign -} - -func defaultBaseRequest() (request *baseRequest) { - request = &baseRequest{ - Scheme: "", - AcceptFormat: "JSON", - Method: GET, - QueryParams: make(map[string]string), - Headers: map[string]string{ - "x-sdk-client": "golang/1.0.0", - "x-sdk-invoke-type": "normal", - "Accept-Encoding": "identity", - }, - FormParams: make(map[string]string), - } - return -} - -func InitParams(request AcsRequest) (err error) { - requestValue := reflect.ValueOf(request).Elem() - err = flatRepeatedList(requestValue, request, "", "") - return -} - -func flatRepeatedList(dataValue reflect.Value, request AcsRequest, position, prefix string) (err error) { - dataType := dataValue.Type() - for i := 0; i < dataType.NumField(); i++ { - field := dataType.Field(i) - name, containsNameTag := field.Tag.Lookup("name") - fieldPosition := position - if fieldPosition == "" { - fieldPosition, _ = field.Tag.Lookup("position") - } - typeTag, containsTypeTag := field.Tag.Lookup("type") - if containsNameTag { - if !containsTypeTag { - // simple param - key := prefix + name - value := dataValue.Field(i).String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else if typeTag == "Repeated" { - // repeated param - repeatedFieldValue := dataValue.Field(i) - if repeatedFieldValue.Kind() != reflect.Slice { - // possible value: {"[]string", "*[]struct"}, we must call Elem() in the last condition - repeatedFieldValue = repeatedFieldValue.Elem() - } - if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() { - for m := 0; m < repeatedFieldValue.Len(); m++ { - elementValue := repeatedFieldValue.Index(m) - key := prefix + name + "." + strconv.Itoa(m+1) - if elementValue.Type().String() == "string" { - value := elementValue.String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else { - err = flatRepeatedList(elementValue, request, fieldPosition, key+".") - if err != nil { - return - } - } - } - } - } - } - } - return -} - -func addParam(request AcsRequest, position, name, value string) (err error) { - if len(value) > 0 { - switch position { - case Header: - request.addHeaderParam(name, value) - case Query: - request.addQueryParam(name, value) - case Path: - request.addPathParam(name, value) - case Body: - request.addFormParam(name, value) - default: - errMsg := fmt.Sprintf(errors.UnsupportedParamPositionErrorMessage, position) - err = errors.NewClientError(errors.UnsupportedParamPositionErrorCode, errMsg, nil) - } - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go deleted file mode 100644 index d5d841b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go +++ /dev/null @@ -1,128 +0,0 @@ -package requests - -import ( - "bytes" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "io" - "strings" -) - -type CommonRequest struct { - *baseRequest - - Version string - ApiName string - Product string - - // roa params - PathPattern string - PathParams map[string]string - - Ontology AcsRequest -} - -func NewCommonRequest() (request *CommonRequest) { - request = &CommonRequest{ - baseRequest: defaultBaseRequest(), - } - request.Headers["x-sdk-invoke-type"] = "common" - request.PathParams = make(map[string]string) - return -} - -func (request *CommonRequest) String() string { - request.TransToAcsRequest() - request.BuildQueries() - request.BuildUrl() - - resultBuilder := bytes.Buffer{} - - mapOutput := func(m map[string]string) { - if len(m) > 0 { - for key, value := range m { - resultBuilder.WriteString(key + ": " + value + "\n") - } - } - } - - // Request Line - resultBuilder.WriteString("\n") - resultBuilder.WriteString(fmt.Sprintf("%s %s %s/1.1\n", request.Method, request.GetQueries(), strings.ToUpper(request.Scheme))) - - // Headers - resultBuilder.WriteString("Host" + ": " + request.Domain + "\n") - mapOutput(request.Headers) - - resultBuilder.WriteString("\n") - // Body - if len(request.Content) > 0 { - resultBuilder.WriteString(string(request.Content) + "\n") - } else { - mapOutput(request.FormParams) - } - - return resultBuilder.String() -} - -func (request *CommonRequest) TransToAcsRequest() { - if len(request.Version) == 0 { - errors.NewClientError(errors.MissingParamErrorCode, "Common request [version] is required", nil) - } - if len(request.ApiName) == 0 && len(request.PathPattern) == 0 { - errors.NewClientError(errors.MissingParamErrorCode, "At least one of [ApiName] and [PathPattern] should has a value", nil) - } - if len(request.Domain) == 0 && len(request.Product) == 0 { - errors.NewClientError(errors.MissingParamErrorCode, "At least one of [Domain] and [Product] should has a value", nil) - } - - if len(request.PathPattern) > 0 { - roaRequest := &RoaRequest{} - roaRequest.initWithCommonRequest(request) - request.Ontology = roaRequest - } else { - rpcRequest := &RpcRequest{} - rpcRequest.baseRequest = request.baseRequest - rpcRequest.product = request.Product - rpcRequest.version = request.Version - rpcRequest.actionName = request.ApiName - request.Ontology = rpcRequest - } - -} - -func (request *CommonRequest) BuildUrl() string { - if len(request.Port) > 0 { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.BuildQueries() - } - - return strings.ToLower(request.Scheme) + "://" + request.Domain + request.BuildQueries() -} - -func (request *CommonRequest) BuildQueries() string { - return request.Ontology.BuildQueries() -} - -func (request *CommonRequest) GetUrl() string { - if len(request.Port) > 0 { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.GetQueries() - } - - return strings.ToLower(request.Scheme) + "://" + request.Domain + request.GetQueries() -} - -func (request *CommonRequest) GetQueries() string { - return request.Ontology.GetQueries() -} - -func (request *CommonRequest) GetBodyReader() io.Reader { - return request.Ontology.GetBodyReader() -} - -func (request *CommonRequest) GetStyle() string { - return request.Ontology.GetStyle() -} - -func (request *CommonRequest) addPathParam(key, value string) { - request.PathParams[key] = value -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go deleted file mode 100644 index cd1ab17..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 requests - -import ( - "bytes" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "io" - "net/url" - "sort" - "strings" -) - -type RoaRequest struct { - *baseRequest - pathPattern string - PathParams map[string]string -} - -func (*RoaRequest) GetStyle() string { - return ROA -} - -func (request *RoaRequest) GetBodyReader() io.Reader { - if request.FormParams != nil && len(request.FormParams) > 0 { - formString := utils.GetUrlFormedMap(request.FormParams) - return strings.NewReader(formString) - } else if len(request.Content) > 0 { - return bytes.NewReader(request.Content) - } else { - return nil - } -} - -func (request *RoaRequest) GetQueries() string { - return request.queries -} - -// for sign method, need not url encoded -func (request *RoaRequest) BuildQueries() string { - return request.buildQueries(false) -} - -func (request *RoaRequest) buildQueries(needParamEncode bool) string { - // replace path params with value - path := request.pathPattern - for key, value := range request.PathParams { - path = strings.Replace(path, "["+key+"]", value, 1) - } - - queryParams := request.QueryParams - // check if path contains params - splitArray := strings.Split(path, "?") - path = splitArray[0] - if len(splitArray) > 1 && len(splitArray[1]) > 0 { - queryParams[splitArray[1]] = "" - } - // sort QueryParams by key - var queryKeys []string - for key := range queryParams { - queryKeys = append(queryKeys, key) - } - sort.Strings(queryKeys) - - // append urlBuilder - urlBuilder := bytes.Buffer{} - urlBuilder.WriteString(path) - if len(queryKeys) > 0 { - urlBuilder.WriteString("?") - } - for i := 0; i < len(queryKeys); i++ { - queryKey := queryKeys[i] - urlBuilder.WriteString(queryKey) - if value := queryParams[queryKey]; len(value) > 0 { - urlBuilder.WriteString("=") - if needParamEncode { - urlBuilder.WriteString(url.QueryEscape(value)) - } else { - urlBuilder.WriteString(value) - } - } - if i < len(queryKeys)-1 { - urlBuilder.WriteString("&") - } - } - result := urlBuilder.String() - result = popStandardUrlencode(result) - request.queries = result - return request.queries -} - -func popStandardUrlencode(stringToSign string) (result string) { - result = strings.Replace(stringToSign, "+", "%20", -1) - result = strings.Replace(result, "*", "%2A", -1) - result = strings.Replace(result, "%7E", "~", -1) - return -} - -func (request *RoaRequest) GetUrl() string { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.GetQueries() -} - -func (request *RoaRequest) BuildUrl() string { - // for network trans, need url encoded - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.buildQueries(true) -} - -func (request *RoaRequest) addPathParam(key, value string) { - request.PathParams[key] = value -} - -func (request *RoaRequest) InitWithApiInfo(product, version, action, uriPattern, serviceCode, endpointType string) { - request.baseRequest = defaultBaseRequest() - request.PathParams = make(map[string]string) - request.Headers["x-acs-version"] = version - request.pathPattern = uriPattern - request.locationServiceCode = serviceCode - request.locationEndpointType = endpointType - //request.product = product - //request.version = version - //request.actionName = action -} - -func (request *RoaRequest) initWithCommonRequest(commonRequest *CommonRequest) { - request.baseRequest = commonRequest.baseRequest - request.PathParams = commonRequest.PathParams - //request.product = commonRequest.Product - //request.version = commonRequest.Version - request.Headers["x-acs-version"] = commonRequest.Version - //request.actionName = commonRequest.ApiName - request.pathPattern = commonRequest.PathPattern - request.locationServiceCode = "" - request.locationEndpointType = "" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go deleted file mode 100644 index 7a61c19..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 requests - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "io" - "strings" -) - -type RpcRequest struct { - *baseRequest -} - -func (request *RpcRequest) init() { - request.baseRequest = defaultBaseRequest() - request.Method = POST -} - -func (*RpcRequest) GetStyle() string { - return RPC -} - -func (request *RpcRequest) GetBodyReader() io.Reader { - if request.FormParams != nil && len(request.FormParams) > 0 { - formString := utils.GetUrlFormedMap(request.FormParams) - return strings.NewReader(formString) - } else { - return strings.NewReader("") - } -} - -func (request *RpcRequest) BuildQueries() string { - request.queries = "/?" + utils.GetUrlFormedMap(request.QueryParams) - return request.queries -} - -func (request *RpcRequest) GetQueries() string { - return request.queries -} - -func (request *RpcRequest) BuildUrl() string { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.BuildQueries() -} - -func (request *RpcRequest) GetUrl() string { - return strings.ToLower(request.Scheme) + "://" + request.Domain + request.GetQueries() -} - -func (request *RpcRequest) GetVersion() string { - return request.version -} - -func (request *RpcRequest) GetActionName() string { - return request.actionName -} - -func (request *RpcRequest) addPathParam(key, value string) { - panic("not support") -} - -func (request *RpcRequest) InitWithApiInfo(product, version, action, serviceCode, endpointType string) { - request.init() - request.product = product - request.version = version - request.actionName = action - request.locationServiceCode = serviceCode - request.locationEndpointType = endpointType -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go deleted file mode 100644 index 28af63e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go +++ /dev/null @@ -1,53 +0,0 @@ -package requests - -import "strconv" - -type Integer string - -func NewInteger(integer int) Integer { - return Integer(strconv.Itoa(integer)) -} - -func (integer Integer) HasValue() bool { - return integer != "" -} - -func (integer Integer) GetValue() (int, error) { - return strconv.Atoi(string(integer)) -} - -func NewInteger64(integer int64) Integer { - return Integer(strconv.FormatInt(integer, 10)) -} - -func (integer Integer) GetValue64() (int64, error) { - return strconv.ParseInt(string(integer), 10, 0) -} - -type Boolean string - -func NewBoolean(bool bool) Boolean { - return Boolean(strconv.FormatBool(bool)) -} - -func (boolean Boolean) HasValue() bool { - return boolean != "" -} - -func (boolean Boolean) GetValue() (bool, error) { - return strconv.ParseBool(string(boolean)) -} - -type Float string - -func NewFloat(f float64) Float { - return Float(strconv.FormatFloat(f, 'f', 6, 64)) -} - -func (float Float) HasValue() bool { - return float != "" -} - -func (float Float) GetValue() (float64, error) { - return strconv.ParseFloat(string(float), 64) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go deleted file mode 100644 index 43ba6fc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go +++ /dev/null @@ -1,341 +0,0 @@ -package responses - -import ( - "encoding/json" - "github.com/json-iterator/go" - "io" - "math" - "strconv" - "strings" - "sync" - "unsafe" -) - -const maxUint = ^uint(0) -const maxInt = int(maxUint >> 1) -const minInt = -maxInt - 1 - -var jsonParser jsoniter.API -var initJson = &sync.Once{} - -func initJsonParserOnce() { - initJson.Do(func() { - registerBetterFuzzyDecoder() - jsonParser = jsoniter.ConfigCompatibleWithStandardLibrary - }) -} - -func registerBetterFuzzyDecoder() { - jsoniter.RegisterTypeDecoder("string", &nullableFuzzyStringDecoder{}) - jsoniter.RegisterTypeDecoder("bool", &fuzzyBoolDecoder{}) - jsoniter.RegisterTypeDecoder("float32", &nullableFuzzyFloat32Decoder{}) - jsoniter.RegisterTypeDecoder("float64", &nullableFuzzyFloat64Decoder{}) - jsoniter.RegisterTypeDecoder("int", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(maxInt) || val < float64(minInt) { - iter.ReportError("fuzzy decode int", "exceed range") - return - } - *((*int)(ptr)) = int(val) - } else { - *((*int)(ptr)) = iter.ReadInt() - } - }}) - jsoniter.RegisterTypeDecoder("uint", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(maxUint) || val < 0 { - iter.ReportError("fuzzy decode uint", "exceed range") - return - } - *((*uint)(ptr)) = uint(val) - } else { - *((*uint)(ptr)) = iter.ReadUint() - } - }}) - jsoniter.RegisterTypeDecoder("int8", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt8) || val < float64(math.MinInt8) { - iter.ReportError("fuzzy decode int8", "exceed range") - return - } - *((*int8)(ptr)) = int8(val) - } else { - *((*int8)(ptr)) = iter.ReadInt8() - } - }}) - jsoniter.RegisterTypeDecoder("uint8", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint8) || val < 0 { - iter.ReportError("fuzzy decode uint8", "exceed range") - return - } - *((*uint8)(ptr)) = uint8(val) - } else { - *((*uint8)(ptr)) = iter.ReadUint8() - } - }}) - jsoniter.RegisterTypeDecoder("int16", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt16) || val < float64(math.MinInt16) { - iter.ReportError("fuzzy decode int16", "exceed range") - return - } - *((*int16)(ptr)) = int16(val) - } else { - *((*int16)(ptr)) = iter.ReadInt16() - } - }}) - jsoniter.RegisterTypeDecoder("uint16", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint16) || val < 0 { - iter.ReportError("fuzzy decode uint16", "exceed range") - return - } - *((*uint16)(ptr)) = uint16(val) - } else { - *((*uint16)(ptr)) = iter.ReadUint16() - } - }}) - jsoniter.RegisterTypeDecoder("int32", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt32) || val < float64(math.MinInt32) { - iter.ReportError("fuzzy decode int32", "exceed range") - return - } - *((*int32)(ptr)) = int32(val) - } else { - *((*int32)(ptr)) = iter.ReadInt32() - } - }}) - jsoniter.RegisterTypeDecoder("uint32", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint32) || val < 0 { - iter.ReportError("fuzzy decode uint32", "exceed range") - return - } - *((*uint32)(ptr)) = uint32(val) - } else { - *((*uint32)(ptr)) = iter.ReadUint32() - } - }}) - jsoniter.RegisterTypeDecoder("int64", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt64) || val < float64(math.MinInt64) { - iter.ReportError("fuzzy decode int64", "exceed range") - return - } - *((*int64)(ptr)) = int64(val) - } else { - *((*int64)(ptr)) = iter.ReadInt64() - } - }}) - jsoniter.RegisterTypeDecoder("uint64", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint64) || val < 0 { - iter.ReportError("fuzzy decode uint64", "exceed range") - return - } - *((*uint64)(ptr)) = uint64(val) - } else { - *((*uint64)(ptr)) = iter.ReadUint64() - } - }}) -} - -type nullableFuzzyStringDecoder struct { -} - -func (decoder *nullableFuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - switch valueType { - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - *((*string)(ptr)) = string(number) - case jsoniter.StringValue: - *((*string)(ptr)) = iter.ReadString() - case jsoniter.BoolValue: - *((*string)(ptr)) = strconv.FormatBool(iter.ReadBool()) - case jsoniter.NilValue: - iter.ReadNil() - *((*string)(ptr)) = "" - default: - iter.ReportError("fuzzyStringDecoder", "not number or string or bool") - } -} - -type fuzzyBoolDecoder struct { -} - -func (decoder *fuzzyBoolDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - switch valueType { - case jsoniter.BoolValue: - *((*bool)(ptr)) = iter.ReadBool() - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - num, err := number.Int64() - if err != nil { - iter.ReportError("fuzzyBoolDecoder", "get value from json.number failed") - } - if num == 0 { - *((*bool)(ptr)) = false - } else { - *((*bool)(ptr)) = true - } - case jsoniter.StringValue: - strValue := strings.ToLower(iter.ReadString()) - if strValue == "true" { - *((*bool)(ptr)) = true - } else if strValue == "false" || strValue == "" { - *((*bool)(ptr)) = false - } else { - iter.ReportError("fuzzyBoolDecoder", "unsupported bool value: "+strValue) - } - case jsoniter.NilValue: - iter.ReadNil() - *((*bool)(ptr)) = false - default: - iter.ReportError("fuzzyBoolDecoder", "not number or string or nil") - } -} - -type tolerateEmptyArrayDecoder struct { - valDecoder jsoniter.ValDecoder -} - -func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if iter.WhatIsNext() == jsoniter.ArrayValue { - iter.Skip() - newIter := iter.Pool().BorrowIterator([]byte("{}")) - defer iter.Pool().ReturnIterator(newIter) - decoder.valDecoder.Decode(ptr, newIter) - } else { - decoder.valDecoder.Decode(ptr, iter) - } -} - -type nullableFuzzyIntegerDecoder struct { - fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) -} - -func (decoder *nullableFuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - str = string(number) - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - str = "0" - } - case jsoniter.BoolValue: - if iter.ReadBool() { - str = "1" - } else { - str = "0" - } - case jsoniter.NilValue: - iter.ReadNil() - str = "0" - default: - iter.ReportError("fuzzyIntegerDecoder", "not number or string") - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - isFloat := strings.IndexByte(str, '.') != -1 - decoder.fun(isFloat, ptr, newIter) - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } -} - -type nullableFuzzyFloat32Decoder struct { -} - -func (decoder *nullableFuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - *((*float32)(ptr)) = iter.ReadFloat32() - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - *((*float32)(ptr)) = 0 - return - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - *((*float32)(ptr)) = newIter.ReadFloat32() - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } - case jsoniter.BoolValue: - // support bool to float32 - if iter.ReadBool() { - *((*float32)(ptr)) = 1 - } else { - *((*float32)(ptr)) = 0 - } - case jsoniter.NilValue: - iter.ReadNil() - *((*float32)(ptr)) = 0 - default: - iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string") - } -} - -type nullableFuzzyFloat64Decoder struct { -} - -func (decoder *nullableFuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - *((*float64)(ptr)) = iter.ReadFloat64() - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - *((*float64)(ptr)) = 0 - return - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - *((*float64)(ptr)) = newIter.ReadFloat64() - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } - case jsoniter.BoolValue: - // support bool to float64 - if iter.ReadBool() { - *((*float64)(ptr)) = 1 - } else { - *((*float64)(ptr)) = 0 - } - case jsoniter.NilValue: - // support empty string - iter.ReadNil() - *((*float64)(ptr)) = 0 - default: - iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string") - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go deleted file mode 100644 index 8780f26..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 responses - -import ( - "bytes" - "encoding/xml" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "io/ioutil" - "net/http" - "strings" -) - -type AcsResponse interface { - IsSuccess() bool - GetHttpStatus() int - GetHttpHeaders() map[string][]string - GetHttpContentString() string - GetHttpContentBytes() []byte - GetOriginHttpResponse() *http.Response - parseFromHttpResponse(httpResponse *http.Response) error -} - -func Unmarshal(response AcsResponse, httpResponse *http.Response, format string) (err error) { - err = response.parseFromHttpResponse(httpResponse) - if err != nil { - return - } - if !response.IsSuccess() { - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), "") - return - } - if _, isCommonResponse := response.(CommonResponse); isCommonResponse { - // common response need not unmarshal - return - } - - if len(response.GetHttpContentBytes()) == 0 { - return - } - - if strings.ToUpper(format) == "JSON" { - initJsonParserOnce() - err = jsonParser.Unmarshal(response.GetHttpContentBytes(), response) - if err != nil { - err = errors.NewClientError(errors.JsonUnmarshalErrorCode, errors.JsonUnmarshalErrorMessage, err) - } - } else if strings.ToUpper(format) == "XML" { - err = xml.Unmarshal(response.GetHttpContentBytes(), response) - } - return -} - -type BaseResponse struct { - httpStatus int - httpHeaders map[string][]string - httpContentString string - httpContentBytes []byte - originHttpResponse *http.Response -} - -func (baseResponse *BaseResponse) GetHttpStatus() int { - return baseResponse.httpStatus -} - -func (baseResponse *BaseResponse) GetHttpHeaders() map[string][]string { - return baseResponse.httpHeaders -} - -func (baseResponse *BaseResponse) GetHttpContentString() string { - return baseResponse.httpContentString -} - -func (baseResponse *BaseResponse) GetHttpContentBytes() []byte { - return baseResponse.httpContentBytes -} - -func (baseResponse *BaseResponse) GetOriginHttpResponse() *http.Response { - return baseResponse.originHttpResponse -} - -func (baseResponse *BaseResponse) IsSuccess() bool { - if baseResponse.GetHttpStatus() >= 200 && baseResponse.GetHttpStatus() < 300 { - return true - } - - return false -} - -func (baseResponse *BaseResponse) parseFromHttpResponse(httpResponse *http.Response) (err error) { - defer httpResponse.Body.Close() - body, err := ioutil.ReadAll(httpResponse.Body) - if err != nil { - return - } - baseResponse.httpStatus = httpResponse.StatusCode - baseResponse.httpHeaders = httpResponse.Header - baseResponse.httpContentBytes = body - baseResponse.httpContentString = string(body) - baseResponse.originHttpResponse = httpResponse - return -} - -func (baseResponse *BaseResponse) String() string { - resultBuilder := bytes.Buffer{} - // statusCode - resultBuilder.WriteString("\n") - resultBuilder.WriteString(fmt.Sprintf("%s %s\n", baseResponse.originHttpResponse.Proto, baseResponse.originHttpResponse.Status)) - // httpHeaders - //resultBuilder.WriteString("Headers:\n") - for key, value := range baseResponse.httpHeaders { - resultBuilder.WriteString(key + ": " + strings.Join(value, ";") + "\n") - } - resultBuilder.WriteString("\n") - // content - //resultBuilder.WriteString("Content:\n") - resultBuilder.WriteString(baseResponse.httpContentString + "\n") - return resultBuilder.String() -} - -type CommonResponse struct { - *BaseResponse -} - -func NewCommonResponse() (response *CommonResponse) { - return &CommonResponse{ - BaseResponse: &BaseResponse{}, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go deleted file mode 100644 index a00c775..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 utils - -import ( - "crypto/md5" - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "github.com/satori/go.uuid" - "net/url" - "reflect" - "strconv" - "time" -) - -// if you use go 1.10 or higher, you can hack this util by these to avoid "TimeZone.zip not found" on Windows -var LoadLocationFromTZData func(name string, data []byte) (*time.Location, error) = nil -var TZData []byte = nil - -func GetUUIDV4() (uuidHex string) { - uuidV4 := uuid.NewV4() - uuidHex = hex.EncodeToString(uuidV4.Bytes()) - return -} - -func GetMD5Base64(bytes []byte) (base64Value string) { - md5Ctx := md5.New() - md5Ctx.Write(bytes) - md5Value := md5Ctx.Sum(nil) - base64Value = base64.StdEncoding.EncodeToString(md5Value) - return -} - -func GetGMTLocation() (*time.Location, error) { - if LoadLocationFromTZData != nil && TZData != nil { - return LoadLocationFromTZData("GMT", TZData) - } else { - return time.LoadLocation("GMT") - } -} - -func GetTimeInFormatISO8601() (timeStr string) { - gmt, err := GetGMTLocation() - - if err != nil { - panic(err) - } - return time.Now().In(gmt).Format("2006-01-02T15:04:05Z") -} - -func GetTimeInFormatRFC2616() (timeStr string) { - gmt, err := GetGMTLocation() - - if err != nil { - panic(err) - } - return time.Now().In(gmt).Format("Mon, 02 Jan 2006 15:04:05 GMT") -} - -func GetUrlFormedMap(source map[string]string) (urlEncoded string) { - urlEncoder := url.Values{} - for key, value := range source { - urlEncoder.Add(key, value) - } - urlEncoded = urlEncoder.Encode() - return -} - -func GetFromJsonString(jsonString, key string) (result string, err error) { - var responseMap map[string]*json.RawMessage - err = json.Unmarshal([]byte(jsonString), &responseMap) - if err != nil { - return - } - fmt.Println(string(*responseMap[key])) - err = json.Unmarshal(*responseMap[key], &result) - return -} - -func InitStructWithDefaultTag(bean interface{}) { - configType := reflect.TypeOf(bean) - for i := 0; i < configType.Elem().NumField(); i++ { - field := configType.Elem().Field(i) - defaultValue := field.Tag.Get("default") - if defaultValue == "" { - continue - } - setter := reflect.ValueOf(bean).Elem().Field(i) - switch field.Type.String() { - case "int": - intValue, _ := strconv.ParseInt(defaultValue, 10, 64) - setter.SetInt(intValue) - case "time.Duration": - intValue, _ := strconv.ParseInt(defaultValue, 10, 64) - setter.SetInt(intValue) - case "string": - setter.SetString(defaultValue) - case "bool": - boolValue, _ := strconv.ParseBool(defaultValue) - setter.SetBool(boolValue) - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_batch_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_batch_domain_records.go deleted file mode 100644 index 30e1dea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_batch_domain_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddBatchDomainRecords invokes the alidns.AddBatchDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/addbatchdomainrecords.html -func (client *Client) AddBatchDomainRecords(request *AddBatchDomainRecordsRequest) (response *AddBatchDomainRecordsResponse, err error) { - response = CreateAddBatchDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// AddBatchDomainRecordsWithChan invokes the alidns.AddBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/addbatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddBatchDomainRecordsWithChan(request *AddBatchDomainRecordsRequest) (<-chan *AddBatchDomainRecordsResponse, <-chan error) { - responseChan := make(chan *AddBatchDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddBatchDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddBatchDomainRecordsWithCallback invokes the alidns.AddBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/addbatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddBatchDomainRecordsWithCallback(request *AddBatchDomainRecordsRequest, callback func(response *AddBatchDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddBatchDomainRecordsResponse - var err error - defer close(result) - response, err = client.AddBatchDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddBatchDomainRecordsRequest is the request struct for api AddBatchDomainRecords -type AddBatchDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Records string `position:"Query" name:"Records"` -} - -// AddBatchDomainRecordsResponse is the response struct for api AddBatchDomainRecords -type AddBatchDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateAddBatchDomainRecordsRequest creates a request to invoke AddBatchDomainRecords API -func CreateAddBatchDomainRecordsRequest() (request *AddBatchDomainRecordsRequest) { - request = &AddBatchDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddBatchDomainRecords", "", "") - return -} - -// CreateAddBatchDomainRecordsResponse creates a response to parse from AddBatchDomainRecords response -func CreateAddBatchDomainRecordsResponse() (response *AddBatchDomainRecordsResponse) { - response = &AddBatchDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain.go deleted file mode 100644 index 1b2249e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddDomain invokes the alidns.AddDomain API synchronously -// api document: https://help.aliyun.com/api/alidns/adddomain.html -func (client *Client) AddDomain(request *AddDomainRequest) (response *AddDomainResponse, err error) { - response = CreateAddDomainResponse() - err = client.DoAction(request, response) - return -} - -// AddDomainWithChan invokes the alidns.AddDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainWithChan(request *AddDomainRequest) (<-chan *AddDomainResponse, <-chan error) { - responseChan := make(chan *AddDomainResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddDomain(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddDomainWithCallback invokes the alidns.AddDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainWithCallback(request *AddDomainRequest, callback func(response *AddDomainResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddDomainResponse - var err error - defer close(result) - response, err = client.AddDomain(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddDomainRequest is the request struct for api AddDomain -type AddDomainRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - GroupId string `position:"Query" name:"GroupId"` -} - -// AddDomainResponse is the response struct for api AddDomain -type AddDomainResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - DnsServers DnsServersInAddDomain `json:"DnsServers" xml:"DnsServers"` -} - -// CreateAddDomainRequest creates a request to invoke AddDomain API -func CreateAddDomainRequest() (request *AddDomainRequest) { - request = &AddDomainRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddDomain", "", "") - return -} - -// CreateAddDomainResponse creates a response to parse from AddDomain response -func CreateAddDomainResponse() (response *AddDomainResponse) { - response = &AddDomainResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_group.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_group.go deleted file mode 100644 index a1c7cd4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_group.go +++ /dev/null @@ -1,107 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddDomainGroup invokes the alidns.AddDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/adddomaingroup.html -func (client *Client) AddDomainGroup(request *AddDomainGroupRequest) (response *AddDomainGroupResponse, err error) { - response = CreateAddDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// AddDomainGroupWithChan invokes the alidns.AddDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainGroupWithChan(request *AddDomainGroupRequest) (<-chan *AddDomainGroupResponse, <-chan error) { - responseChan := make(chan *AddDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddDomainGroupWithCallback invokes the alidns.AddDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainGroupWithCallback(request *AddDomainGroupRequest, callback func(response *AddDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddDomainGroupResponse - var err error - defer close(result) - response, err = client.AddDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddDomainGroupRequest is the request struct for api AddDomainGroup -type AddDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - GroupName string `position:"Query" name:"GroupName"` -} - -// AddDomainGroupResponse is the response struct for api AddDomainGroup -type AddDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateAddDomainGroupRequest creates a request to invoke AddDomainGroup API -func CreateAddDomainGroupRequest() (request *AddDomainGroupRequest) { - request = &AddDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddDomainGroup", "", "") - return -} - -// CreateAddDomainGroupResponse creates a response to parse from AddDomainGroup response -func CreateAddDomainGroupResponse() (response *AddDomainGroupResponse) { - response = &AddDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_record.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_record.go deleted file mode 100644 index 1da6024..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_record.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddDomainRecord invokes the alidns.AddDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/adddomainrecord.html -func (client *Client) AddDomainRecord(request *AddDomainRecordRequest) (response *AddDomainRecordResponse, err error) { - response = CreateAddDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// AddDomainRecordWithChan invokes the alidns.AddDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainRecordWithChan(request *AddDomainRecordRequest) (<-chan *AddDomainRecordResponse, <-chan error) { - responseChan := make(chan *AddDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddDomainRecordWithCallback invokes the alidns.AddDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainRecordWithCallback(request *AddDomainRecordRequest, callback func(response *AddDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddDomainRecordResponse - var err error - defer close(result) - response, err = client.AddDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddDomainRecordRequest is the request struct for api AddDomainRecord -type AddDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` - Value string `position:"Query" name:"Value"` - TTL requests.Integer `position:"Query" name:"TTL"` - Priority requests.Integer `position:"Query" name:"Priority"` - Line string `position:"Query" name:"Line"` -} - -// AddDomainRecordResponse is the response struct for api AddDomainRecord -type AddDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` -} - -// CreateAddDomainRecordRequest creates a request to invoke AddDomainRecord API -func CreateAddDomainRecordRequest() (request *AddDomainRecordRequest) { - request = &AddDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddDomainRecord", "", "") - return -} - -// CreateAddDomainRecordResponse creates a response to parse from AddDomainRecord response -func CreateAddDomainRecordResponse() (response *AddDomainRecordResponse) { - response = &AddDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/apply_for_retrieval_domain_name.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/apply_for_retrieval_domain_name.go deleted file mode 100644 index 86b68e7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/apply_for_retrieval_domain_name.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ApplyForRetrievalDomainName invokes the alidns.ApplyForRetrievalDomainName API synchronously -// api document: https://help.aliyun.com/api/alidns/applyforretrievaldomainname.html -func (client *Client) ApplyForRetrievalDomainName(request *ApplyForRetrievalDomainNameRequest) (response *ApplyForRetrievalDomainNameResponse, err error) { - response = CreateApplyForRetrievalDomainNameResponse() - err = client.DoAction(request, response) - return -} - -// ApplyForRetrievalDomainNameWithChan invokes the alidns.ApplyForRetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/applyforretrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ApplyForRetrievalDomainNameWithChan(request *ApplyForRetrievalDomainNameRequest) (<-chan *ApplyForRetrievalDomainNameResponse, <-chan error) { - responseChan := make(chan *ApplyForRetrievalDomainNameResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ApplyForRetrievalDomainName(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ApplyForRetrievalDomainNameWithCallback invokes the alidns.ApplyForRetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/applyforretrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ApplyForRetrievalDomainNameWithCallback(request *ApplyForRetrievalDomainNameRequest, callback func(response *ApplyForRetrievalDomainNameResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ApplyForRetrievalDomainNameResponse - var err error - defer close(result) - response, err = client.ApplyForRetrievalDomainName(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ApplyForRetrievalDomainNameRequest is the request struct for api ApplyForRetrievalDomainName -type ApplyForRetrievalDomainNameRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// ApplyForRetrievalDomainNameResponse is the response struct for api ApplyForRetrievalDomainName -type ApplyForRetrievalDomainNameResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` -} - -// CreateApplyForRetrievalDomainNameRequest creates a request to invoke ApplyForRetrievalDomainName API -func CreateApplyForRetrievalDomainNameRequest() (request *ApplyForRetrievalDomainNameRequest) { - request = &ApplyForRetrievalDomainNameRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ApplyForRetrievalDomainName", "", "") - return -} - -// CreateApplyForRetrievalDomainNameResponse creates a response to parse from ApplyForRetrievalDomainName response -func CreateApplyForRetrievalDomainNameResponse() (response *ApplyForRetrievalDomainNameResponse) { - response = &ApplyForRetrievalDomainNameResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_group.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_group.go deleted file mode 100644 index 61fed5b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_group.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ChangeDomainGroup invokes the alidns.ChangeDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/changedomaingroup.html -func (client *Client) ChangeDomainGroup(request *ChangeDomainGroupRequest) (response *ChangeDomainGroupResponse, err error) { - response = CreateChangeDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// ChangeDomainGroupWithChan invokes the alidns.ChangeDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainGroupWithChan(request *ChangeDomainGroupRequest) (<-chan *ChangeDomainGroupResponse, <-chan error) { - responseChan := make(chan *ChangeDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ChangeDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ChangeDomainGroupWithCallback invokes the alidns.ChangeDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainGroupWithCallback(request *ChangeDomainGroupRequest, callback func(response *ChangeDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ChangeDomainGroupResponse - var err error - defer close(result) - response, err = client.ChangeDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ChangeDomainGroupRequest is the request struct for api ChangeDomainGroup -type ChangeDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - GroupId string `position:"Query" name:"GroupId"` -} - -// ChangeDomainGroupResponse is the response struct for api ChangeDomainGroup -type ChangeDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateChangeDomainGroupRequest creates a request to invoke ChangeDomainGroup API -func CreateChangeDomainGroupRequest() (request *ChangeDomainGroupRequest) { - request = &ChangeDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ChangeDomainGroup", "", "") - return -} - -// CreateChangeDomainGroupResponse creates a response to parse from ChangeDomainGroup response -func CreateChangeDomainGroupResponse() (response *ChangeDomainGroupResponse) { - response = &ChangeDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_of_dns_product.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_of_dns_product.go deleted file mode 100644 index 04f329e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_of_dns_product.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ChangeDomainOfDnsProduct invokes the alidns.ChangeDomainOfDnsProduct API synchronously -// api document: https://help.aliyun.com/api/alidns/changedomainofdnsproduct.html -func (client *Client) ChangeDomainOfDnsProduct(request *ChangeDomainOfDnsProductRequest) (response *ChangeDomainOfDnsProductResponse, err error) { - response = CreateChangeDomainOfDnsProductResponse() - err = client.DoAction(request, response) - return -} - -// ChangeDomainOfDnsProductWithChan invokes the alidns.ChangeDomainOfDnsProduct API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomainofdnsproduct.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainOfDnsProductWithChan(request *ChangeDomainOfDnsProductRequest) (<-chan *ChangeDomainOfDnsProductResponse, <-chan error) { - responseChan := make(chan *ChangeDomainOfDnsProductResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ChangeDomainOfDnsProduct(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ChangeDomainOfDnsProductWithCallback invokes the alidns.ChangeDomainOfDnsProduct API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomainofdnsproduct.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainOfDnsProductWithCallback(request *ChangeDomainOfDnsProductRequest, callback func(response *ChangeDomainOfDnsProductResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ChangeDomainOfDnsProductResponse - var err error - defer close(result) - response, err = client.ChangeDomainOfDnsProduct(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ChangeDomainOfDnsProductRequest is the request struct for api ChangeDomainOfDnsProduct -type ChangeDomainOfDnsProductRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - InstanceId string `position:"Query" name:"InstanceId"` - NewDomain string `position:"Query" name:"NewDomain"` - Force requests.Boolean `position:"Query" name:"Force"` -} - -// ChangeDomainOfDnsProductResponse is the response struct for api ChangeDomainOfDnsProduct -type ChangeDomainOfDnsProductResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - OriginalDomain string `json:"OriginalDomain" xml:"OriginalDomain"` -} - -// CreateChangeDomainOfDnsProductRequest creates a request to invoke ChangeDomainOfDnsProduct API -func CreateChangeDomainOfDnsProductRequest() (request *ChangeDomainOfDnsProductRequest) { - request = &ChangeDomainOfDnsProductRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ChangeDomainOfDnsProduct", "", "") - return -} - -// CreateChangeDomainOfDnsProductResponse creates a response to parse from ChangeDomainOfDnsProduct response -func CreateChangeDomainOfDnsProductResponse() (response *ChangeDomainOfDnsProductResponse) { - response = &ChangeDomainOfDnsProductResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/check_domain_record.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/check_domain_record.go deleted file mode 100644 index 876e4de..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/check_domain_record.go +++ /dev/null @@ -1,109 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// CheckDomainRecord invokes the alidns.CheckDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/checkdomainrecord.html -func (client *Client) CheckDomainRecord(request *CheckDomainRecordRequest) (response *CheckDomainRecordResponse, err error) { - response = CreateCheckDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// CheckDomainRecordWithChan invokes the alidns.CheckDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/checkdomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) CheckDomainRecordWithChan(request *CheckDomainRecordRequest) (<-chan *CheckDomainRecordResponse, <-chan error) { - responseChan := make(chan *CheckDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.CheckDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// CheckDomainRecordWithCallback invokes the alidns.CheckDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/checkdomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) CheckDomainRecordWithCallback(request *CheckDomainRecordRequest, callback func(response *CheckDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *CheckDomainRecordResponse - var err error - defer close(result) - response, err = client.CheckDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// CheckDomainRecordRequest is the request struct for api CheckDomainRecord -type CheckDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` - Value string `position:"Query" name:"Value"` -} - -// CheckDomainRecordResponse is the response struct for api CheckDomainRecord -type CheckDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - IsExist bool `json:"IsExist" xml:"IsExist"` -} - -// CreateCheckDomainRecordRequest creates a request to invoke CheckDomainRecord API -func CreateCheckDomainRecordRequest() (request *CheckDomainRecordRequest) { - request = &CheckDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "CheckDomainRecord", "", "") - return -} - -// CreateCheckDomainRecordResponse creates a response to parse from CheckDomainRecord response -func CreateCheckDomainRecordResponse() (response *CheckDomainRecordResponse) { - response = &CheckDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/client.go deleted file mode 100644 index bd92fdd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/client.go +++ /dev/null @@ -1,81 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" -) - -// Client is the sdk client struct, each func corresponds to an OpenAPI -type Client struct { - sdk.Client -} - -// NewClient creates a sdk client with environment variables -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - return -} - -// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential -// this is the common api to create a sdk client -func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - return -} - -// NewClientWithAccessKey is a shortcut to create sdk client with accesskey -// usage: https://help.aliyun.com/document_detail/66217.html -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - return -} - -// NewClientWithStsToken is a shortcut to create sdk client with sts token -// usage: https://help.aliyun.com/document_detail/66222.html -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - return -} - -// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn -// usage: https://help.aliyun.com/document_detail/66222.html -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - return -} - -// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role -// usage: https://help.aliyun.com/document_detail/66223.html -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - return -} - -// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair -// attention: rsa key pair auth is only Japan regions available -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domain_records.go deleted file mode 100644 index 8c973f7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domain_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteBatchDomainRecords invokes the alidns.DeleteBatchDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomainrecords.html -func (client *Client) DeleteBatchDomainRecords(request *DeleteBatchDomainRecordsRequest) (response *DeleteBatchDomainRecordsResponse, err error) { - response = CreateDeleteBatchDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DeleteBatchDomainRecordsWithChan invokes the alidns.DeleteBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainRecordsWithChan(request *DeleteBatchDomainRecordsRequest) (<-chan *DeleteBatchDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DeleteBatchDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteBatchDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteBatchDomainRecordsWithCallback invokes the alidns.DeleteBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainRecordsWithCallback(request *DeleteBatchDomainRecordsRequest, callback func(response *DeleteBatchDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteBatchDomainRecordsResponse - var err error - defer close(result) - response, err = client.DeleteBatchDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteBatchDomainRecordsRequest is the request struct for api DeleteBatchDomainRecords -type DeleteBatchDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Records string `position:"Query" name:"Records"` -} - -// DeleteBatchDomainRecordsResponse is the response struct for api DeleteBatchDomainRecords -type DeleteBatchDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateDeleteBatchDomainRecordsRequest creates a request to invoke DeleteBatchDomainRecords API -func CreateDeleteBatchDomainRecordsRequest() (request *DeleteBatchDomainRecordsRequest) { - request = &DeleteBatchDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteBatchDomainRecords", "", "") - return -} - -// CreateDeleteBatchDomainRecordsResponse creates a response to parse from DeleteBatchDomainRecords response -func CreateDeleteBatchDomainRecordsResponse() (response *DeleteBatchDomainRecordsResponse) { - response = &DeleteBatchDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domains.go deleted file mode 100644 index fbbac4c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domains.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteBatchDomains invokes the alidns.DeleteBatchDomains API synchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomains.html -func (client *Client) DeleteBatchDomains(request *DeleteBatchDomainsRequest) (response *DeleteBatchDomainsResponse, err error) { - response = CreateDeleteBatchDomainsResponse() - err = client.DoAction(request, response) - return -} - -// DeleteBatchDomainsWithChan invokes the alidns.DeleteBatchDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainsWithChan(request *DeleteBatchDomainsRequest) (<-chan *DeleteBatchDomainsResponse, <-chan error) { - responseChan := make(chan *DeleteBatchDomainsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteBatchDomains(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteBatchDomainsWithCallback invokes the alidns.DeleteBatchDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainsWithCallback(request *DeleteBatchDomainsRequest, callback func(response *DeleteBatchDomainsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteBatchDomainsResponse - var err error - defer close(result) - response, err = client.DeleteBatchDomains(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteBatchDomainsRequest is the request struct for api DeleteBatchDomains -type DeleteBatchDomainsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Domains string `position:"Query" name:"Domains"` -} - -// DeleteBatchDomainsResponse is the response struct for api DeleteBatchDomains -type DeleteBatchDomainsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateDeleteBatchDomainsRequest creates a request to invoke DeleteBatchDomains API -func CreateDeleteBatchDomainsRequest() (request *DeleteBatchDomainsRequest) { - request = &DeleteBatchDomainsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteBatchDomains", "", "") - return -} - -// CreateDeleteBatchDomainsResponse creates a response to parse from DeleteBatchDomains response -func CreateDeleteBatchDomainsResponse() (response *DeleteBatchDomainsResponse) { - response = &DeleteBatchDomainsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain.go deleted file mode 100644 index 097f37f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteDomain invokes the alidns.DeleteDomain API synchronously -// api document: https://help.aliyun.com/api/alidns/deletedomain.html -func (client *Client) DeleteDomain(request *DeleteDomainRequest) (response *DeleteDomainResponse, err error) { - response = CreateDeleteDomainResponse() - err = client.DoAction(request, response) - return -} - -// DeleteDomainWithChan invokes the alidns.DeleteDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainWithChan(request *DeleteDomainRequest) (<-chan *DeleteDomainResponse, <-chan error) { - responseChan := make(chan *DeleteDomainResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteDomain(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteDomainWithCallback invokes the alidns.DeleteDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainWithCallback(request *DeleteDomainRequest, callback func(response *DeleteDomainResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteDomainResponse - var err error - defer close(result) - response, err = client.DeleteDomain(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteDomainRequest is the request struct for api DeleteDomain -type DeleteDomainRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// DeleteDomainResponse is the response struct for api DeleteDomain -type DeleteDomainResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` -} - -// CreateDeleteDomainRequest creates a request to invoke DeleteDomain API -func CreateDeleteDomainRequest() (request *DeleteDomainRequest) { - request = &DeleteDomainRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteDomain", "", "") - return -} - -// CreateDeleteDomainResponse creates a response to parse from DeleteDomain response -func CreateDeleteDomainResponse() (response *DeleteDomainResponse) { - response = &DeleteDomainResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_group.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_group.go deleted file mode 100644 index 341b912..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_group.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteDomainGroup invokes the alidns.DeleteDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/deletedomaingroup.html -func (client *Client) DeleteDomainGroup(request *DeleteDomainGroupRequest) (response *DeleteDomainGroupResponse, err error) { - response = CreateDeleteDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// DeleteDomainGroupWithChan invokes the alidns.DeleteDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainGroupWithChan(request *DeleteDomainGroupRequest) (<-chan *DeleteDomainGroupResponse, <-chan error) { - responseChan := make(chan *DeleteDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteDomainGroupWithCallback invokes the alidns.DeleteDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainGroupWithCallback(request *DeleteDomainGroupRequest, callback func(response *DeleteDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteDomainGroupResponse - var err error - defer close(result) - response, err = client.DeleteDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteDomainGroupRequest is the request struct for api DeleteDomainGroup -type DeleteDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - GroupId string `position:"Query" name:"GroupId"` -} - -// DeleteDomainGroupResponse is the response struct for api DeleteDomainGroup -type DeleteDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateDeleteDomainGroupRequest creates a request to invoke DeleteDomainGroup API -func CreateDeleteDomainGroupRequest() (request *DeleteDomainGroupRequest) { - request = &DeleteDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteDomainGroup", "", "") - return -} - -// CreateDeleteDomainGroupResponse creates a response to parse from DeleteDomainGroup response -func CreateDeleteDomainGroupResponse() (response *DeleteDomainGroupResponse) { - response = &DeleteDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_record.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_record.go deleted file mode 100644 index 73f2b08..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_record.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteDomainRecord invokes the alidns.DeleteDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/deletedomainrecord.html -func (client *Client) DeleteDomainRecord(request *DeleteDomainRecordRequest) (response *DeleteDomainRecordResponse, err error) { - response = CreateDeleteDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// DeleteDomainRecordWithChan invokes the alidns.DeleteDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainRecordWithChan(request *DeleteDomainRecordRequest) (<-chan *DeleteDomainRecordResponse, <-chan error) { - responseChan := make(chan *DeleteDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteDomainRecordWithCallback invokes the alidns.DeleteDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainRecordWithCallback(request *DeleteDomainRecordRequest, callback func(response *DeleteDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteDomainRecordResponse - var err error - defer close(result) - response, err = client.DeleteDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteDomainRecordRequest is the request struct for api DeleteDomainRecord -type DeleteDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` -} - -// DeleteDomainRecordResponse is the response struct for api DeleteDomainRecord -type DeleteDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` -} - -// CreateDeleteDomainRecordRequest creates a request to invoke DeleteDomainRecord API -func CreateDeleteDomainRecordRequest() (request *DeleteDomainRecordRequest) { - request = &DeleteDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteDomainRecord", "", "") - return -} - -// CreateDeleteDomainRecordResponse creates a response to parse from DeleteDomainRecord response -func CreateDeleteDomainRecordResponse() (response *DeleteDomainRecordResponse) { - response = &DeleteDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_sub_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_sub_domain_records.go deleted file mode 100644 index 06bb0fd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_sub_domain_records.go +++ /dev/null @@ -1,109 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteSubDomainRecords invokes the alidns.DeleteSubDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/deletesubdomainrecords.html -func (client *Client) DeleteSubDomainRecords(request *DeleteSubDomainRecordsRequest) (response *DeleteSubDomainRecordsResponse, err error) { - response = CreateDeleteSubDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DeleteSubDomainRecordsWithChan invokes the alidns.DeleteSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteSubDomainRecordsWithChan(request *DeleteSubDomainRecordsRequest) (<-chan *DeleteSubDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DeleteSubDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteSubDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteSubDomainRecordsWithCallback invokes the alidns.DeleteSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteSubDomainRecordsWithCallback(request *DeleteSubDomainRecordsRequest, callback func(response *DeleteSubDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteSubDomainRecordsResponse - var err error - defer close(result) - response, err = client.DeleteSubDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteSubDomainRecordsRequest is the request struct for api DeleteSubDomainRecords -type DeleteSubDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` -} - -// DeleteSubDomainRecordsResponse is the response struct for api DeleteSubDomainRecords -type DeleteSubDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RR string `json:"RR" xml:"RR"` - TotalCount string `json:"TotalCount" xml:"TotalCount"` -} - -// CreateDeleteSubDomainRecordsRequest creates a request to invoke DeleteSubDomainRecords API -func CreateDeleteSubDomainRecordsRequest() (request *DeleteSubDomainRecordsRequest) { - request = &DeleteSubDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteSubDomainRecords", "", "") - return -} - -// CreateDeleteSubDomainRecordsResponse creates a response to parse from DeleteSubDomainRecords response -func CreateDeleteSubDomainRecordsResponse() (response *DeleteSubDomainRecordsResponse) { - response = &DeleteSubDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_batch_result.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_batch_result.go deleted file mode 100644 index 67590cb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_batch_result.go +++ /dev/null @@ -1,110 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeBatchResult invokes the alidns.DescribeBatchResult API synchronously -// api document: https://help.aliyun.com/api/alidns/describebatchresult.html -func (client *Client) DescribeBatchResult(request *DescribeBatchResultRequest) (response *DescribeBatchResultResponse, err error) { - response = CreateDescribeBatchResultResponse() - err = client.DoAction(request, response) - return -} - -// DescribeBatchResultWithChan invokes the alidns.DescribeBatchResult API asynchronously -// api document: https://help.aliyun.com/api/alidns/describebatchresult.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeBatchResultWithChan(request *DescribeBatchResultRequest) (<-chan *DescribeBatchResultResponse, <-chan error) { - responseChan := make(chan *DescribeBatchResultResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeBatchResult(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeBatchResultWithCallback invokes the alidns.DescribeBatchResult API asynchronously -// api document: https://help.aliyun.com/api/alidns/describebatchresult.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeBatchResultWithCallback(request *DescribeBatchResultRequest, callback func(response *DescribeBatchResultResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeBatchResultResponse - var err error - defer close(result) - response, err = client.DescribeBatchResult(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeBatchResultRequest is the request struct for api DescribeBatchResult -type DescribeBatchResultRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - TraceId string `position:"Query" name:"TraceId"` -} - -// DescribeBatchResultResponse is the response struct for api DescribeBatchResult -type DescribeBatchResultResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` - Status int `json:"Status" xml:"Status"` - BatchCount int `json:"BatchCount" xml:"BatchCount"` - SuccessNumber int `json:"SuccessNumber" xml:"SuccessNumber"` - FailResults FailResults `json:"FailResults" xml:"FailResults"` -} - -// CreateDescribeBatchResultRequest creates a request to invoke DescribeBatchResult API -func CreateDescribeBatchResultRequest() (request *DescribeBatchResultRequest) { - request = &DescribeBatchResultRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeBatchResult", "", "") - return -} - -// CreateDescribeBatchResultResponse creates a response to parse from DescribeBatchResult response -func CreateDescribeBatchResultResponse() (response *DescribeBatchResultResponse) { - response = &DescribeBatchResultResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instance.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instance.go deleted file mode 100644 index b92bf78..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instance.go +++ /dev/null @@ -1,134 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDnsProductInstance invokes the alidns.DescribeDnsProductInstance API synchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstance.html -func (client *Client) DescribeDnsProductInstance(request *DescribeDnsProductInstanceRequest) (response *DescribeDnsProductInstanceResponse, err error) { - response = CreateDescribeDnsProductInstanceResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDnsProductInstanceWithChan invokes the alidns.DescribeDnsProductInstance API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstance.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstanceWithChan(request *DescribeDnsProductInstanceRequest) (<-chan *DescribeDnsProductInstanceResponse, <-chan error) { - responseChan := make(chan *DescribeDnsProductInstanceResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDnsProductInstance(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDnsProductInstanceWithCallback invokes the alidns.DescribeDnsProductInstance API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstance.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstanceWithCallback(request *DescribeDnsProductInstanceRequest, callback func(response *DescribeDnsProductInstanceResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDnsProductInstanceResponse - var err error - defer close(result) - response, err = client.DescribeDnsProductInstance(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDnsProductInstanceRequest is the request struct for api DescribeDnsProductInstance -type DescribeDnsProductInstanceRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - InstanceId string `position:"Query" name:"InstanceId"` -} - -// DescribeDnsProductInstanceResponse is the response struct for api DescribeDnsProductInstance -type DescribeDnsProductInstanceResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - StartTime string `json:"StartTime" xml:"StartTime"` - StartTimestamp int `json:"StartTimestamp" xml:"StartTimestamp"` - EndTime string `json:"EndTime" xml:"EndTime"` - EndTimestamp int `json:"EndTimestamp" xml:"EndTimestamp"` - Domain string `json:"Domain" xml:"Domain"` - BindCount int `json:"BindCount" xml:"BindCount"` - BindUsedCount int `json:"BindUsedCount" xml:"BindUsedCount"` - TTLMinValue int `json:"TTLMinValue" xml:"TTLMinValue"` - SubDomainLevel int `json:"SubDomainLevel" xml:"SubDomainLevel"` - DnsSLBCount int `json:"DnsSLBCount" xml:"DnsSLBCount"` - URLForwardCount int `json:"URLForwardCount" xml:"URLForwardCount"` - DDosDefendFlow int `json:"DDosDefendFlow" xml:"DDosDefendFlow"` - DDosDefendQuery int `json:"DDosDefendQuery" xml:"DDosDefendQuery"` - OverseaDDosDefendFlow int `json:"OverseaDDosDefendFlow" xml:"OverseaDDosDefendFlow"` - SearchEngineLines string `json:"SearchEngineLines" xml:"SearchEngineLines"` - ISPLines string `json:"ISPLines" xml:"ISPLines"` - ISPRegionLines string `json:"ISPRegionLines" xml:"ISPRegionLines"` - OverseaLine string `json:"OverseaLine" xml:"OverseaLine"` - MonitorNodeCount int `json:"MonitorNodeCount" xml:"MonitorNodeCount"` - MonitorFrequency int `json:"MonitorFrequency" xml:"MonitorFrequency"` - MonitorTaskCount int `json:"MonitorTaskCount" xml:"MonitorTaskCount"` - RegionLines bool `json:"RegionLines" xml:"RegionLines"` - Gslb bool `json:"Gslb" xml:"Gslb"` - InClean bool `json:"InClean" xml:"InClean"` - InBlackHole bool `json:"InBlackHole" xml:"InBlackHole"` - DnsServers DnsServersInDescribeDnsProductInstance `json:"DnsServers" xml:"DnsServers"` -} - -// CreateDescribeDnsProductInstanceRequest creates a request to invoke DescribeDnsProductInstance API -func CreateDescribeDnsProductInstanceRequest() (request *DescribeDnsProductInstanceRequest) { - request = &DescribeDnsProductInstanceRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDnsProductInstance", "", "") - return -} - -// CreateDescribeDnsProductInstanceResponse creates a response to parse from DescribeDnsProductInstance response -func CreateDescribeDnsProductInstanceResponse() (response *DescribeDnsProductInstanceResponse) { - response = &DescribeDnsProductInstanceResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instances.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instances.go deleted file mode 100644 index ae17278..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instances.go +++ /dev/null @@ -1,111 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDnsProductInstances invokes the alidns.DescribeDnsProductInstances API synchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstances.html -func (client *Client) DescribeDnsProductInstances(request *DescribeDnsProductInstancesRequest) (response *DescribeDnsProductInstancesResponse, err error) { - response = CreateDescribeDnsProductInstancesResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDnsProductInstancesWithChan invokes the alidns.DescribeDnsProductInstances API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstances.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstancesWithChan(request *DescribeDnsProductInstancesRequest) (<-chan *DescribeDnsProductInstancesResponse, <-chan error) { - responseChan := make(chan *DescribeDnsProductInstancesResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDnsProductInstances(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDnsProductInstancesWithCallback invokes the alidns.DescribeDnsProductInstances API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstances.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstancesWithCallback(request *DescribeDnsProductInstancesRequest, callback func(response *DescribeDnsProductInstancesResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDnsProductInstancesResponse - var err error - defer close(result) - response, err = client.DescribeDnsProductInstances(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDnsProductInstancesRequest is the request struct for api DescribeDnsProductInstances -type DescribeDnsProductInstancesRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - VersionCode string `position:"Query" name:"VersionCode"` -} - -// DescribeDnsProductInstancesResponse is the response struct for api DescribeDnsProductInstances -type DescribeDnsProductInstancesResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DnsProducts DnsProducts `json:"DnsProducts" xml:"DnsProducts"` -} - -// CreateDescribeDnsProductInstancesRequest creates a request to invoke DescribeDnsProductInstances API -func CreateDescribeDnsProductInstancesRequest() (request *DescribeDnsProductInstancesRequest) { - request = &DescribeDnsProductInstancesRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDnsProductInstances", "", "") - return -} - -// CreateDescribeDnsProductInstancesResponse creates a response to parse from DescribeDnsProductInstances response -func CreateDescribeDnsProductInstancesResponse() (response *DescribeDnsProductInstancesResponse) { - response = &DescribeDnsProductInstancesResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dnsslb_sub_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dnsslb_sub_domains.go deleted file mode 100644 index b545f41..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dnsslb_sub_domains.go +++ /dev/null @@ -1,111 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDNSSLBSubDomains invokes the alidns.DescribeDNSSLBSubDomains API synchronously -// api document: https://help.aliyun.com/api/alidns/describednsslbsubdomains.html -func (client *Client) DescribeDNSSLBSubDomains(request *DescribeDNSSLBSubDomainsRequest) (response *DescribeDNSSLBSubDomainsResponse, err error) { - response = CreateDescribeDNSSLBSubDomainsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDNSSLBSubDomainsWithChan invokes the alidns.DescribeDNSSLBSubDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsslbsubdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDNSSLBSubDomainsWithChan(request *DescribeDNSSLBSubDomainsRequest) (<-chan *DescribeDNSSLBSubDomainsResponse, <-chan error) { - responseChan := make(chan *DescribeDNSSLBSubDomainsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDNSSLBSubDomains(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDNSSLBSubDomainsWithCallback invokes the alidns.DescribeDNSSLBSubDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsslbsubdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDNSSLBSubDomainsWithCallback(request *DescribeDNSSLBSubDomainsRequest, callback func(response *DescribeDNSSLBSubDomainsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDNSSLBSubDomainsResponse - var err error - defer close(result) - response, err = client.DescribeDNSSLBSubDomains(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDNSSLBSubDomainsRequest is the request struct for api DescribeDNSSLBSubDomains -type DescribeDNSSLBSubDomainsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` -} - -// DescribeDNSSLBSubDomainsResponse is the response struct for api DescribeDNSSLBSubDomains -type DescribeDNSSLBSubDomainsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - SlbSubDomains SlbSubDomains `json:"SlbSubDomains" xml:"SlbSubDomains"` -} - -// CreateDescribeDNSSLBSubDomainsRequest creates a request to invoke DescribeDNSSLBSubDomains API -func CreateDescribeDNSSLBSubDomainsRequest() (request *DescribeDNSSLBSubDomainsRequest) { - request = &DescribeDNSSLBSubDomainsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDNSSLBSubDomains", "", "") - return -} - -// CreateDescribeDNSSLBSubDomainsResponse creates a response to parse from DescribeDNSSLBSubDomains response -func CreateDescribeDNSSLBSubDomainsResponse() (response *DescribeDNSSLBSubDomainsResponse) { - response = &DescribeDNSSLBSubDomainsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_groups.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_groups.go deleted file mode 100644 index ffe1f1f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_groups.go +++ /dev/null @@ -1,111 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainGroups invokes the alidns.DescribeDomainGroups API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomaingroups.html -func (client *Client) DescribeDomainGroups(request *DescribeDomainGroupsRequest) (response *DescribeDomainGroupsResponse, err error) { - response = CreateDescribeDomainGroupsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainGroupsWithChan invokes the alidns.DescribeDomainGroups API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaingroups.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainGroupsWithChan(request *DescribeDomainGroupsRequest) (<-chan *DescribeDomainGroupsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainGroupsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainGroups(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainGroupsWithCallback invokes the alidns.DescribeDomainGroups API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaingroups.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainGroupsWithCallback(request *DescribeDomainGroupsRequest, callback func(response *DescribeDomainGroupsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainGroupsResponse - var err error - defer close(result) - response, err = client.DescribeDomainGroups(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainGroupsRequest is the request struct for api DescribeDomainGroups -type DescribeDomainGroupsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - KeyWord string `position:"Query" name:"KeyWord"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` -} - -// DescribeDomainGroupsResponse is the response struct for api DescribeDomainGroups -type DescribeDomainGroupsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainGroups DomainGroups `json:"DomainGroups" xml:"DomainGroups"` -} - -// CreateDescribeDomainGroupsRequest creates a request to invoke DescribeDomainGroups API -func CreateDescribeDomainGroupsRequest() (request *DescribeDomainGroupsRequest) { - request = &DescribeDomainGroupsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainGroups", "", "") - return -} - -// CreateDescribeDomainGroupsResponse creates a response to parse from DescribeDomainGroups response -func CreateDescribeDomainGroupsResponse() (response *DescribeDomainGroupsResponse) { - response = &DescribeDomainGroupsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_info.go deleted file mode 100644 index 0f6f3e0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_info.go +++ /dev/null @@ -1,123 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainInfo invokes the alidns.DescribeDomainInfo API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomaininfo.html -func (client *Client) DescribeDomainInfo(request *DescribeDomainInfoRequest) (response *DescribeDomainInfoResponse, err error) { - response = CreateDescribeDomainInfoResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainInfoWithChan invokes the alidns.DescribeDomainInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaininfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainInfoWithChan(request *DescribeDomainInfoRequest) (<-chan *DescribeDomainInfoResponse, <-chan error) { - responseChan := make(chan *DescribeDomainInfoResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainInfo(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainInfoWithCallback invokes the alidns.DescribeDomainInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaininfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainInfoWithCallback(request *DescribeDomainInfoRequest, callback func(response *DescribeDomainInfoResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainInfoResponse - var err error - defer close(result) - response, err = client.DescribeDomainInfo(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainInfoRequest is the request struct for api DescribeDomainInfo -type DescribeDomainInfoRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - NeedDetailAttributes requests.Boolean `position:"Query" name:"NeedDetailAttributes"` -} - -// DescribeDomainInfoResponse is the response struct for api DescribeDomainInfo -type DescribeDomainInfoResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - AliDomain bool `json:"AliDomain" xml:"AliDomain"` - Remark string `json:"Remark" xml:"Remark"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - MinTtl int `json:"MinTtl" xml:"MinTtl"` - RecordLineTreeJson string `json:"RecordLineTreeJson" xml:"RecordLineTreeJson"` - LineType string `json:"LineType" xml:"LineType"` - RegionLines bool `json:"RegionLines" xml:"RegionLines"` - DnsServers DnsServersInDescribeDomainInfo `json:"DnsServers" xml:"DnsServers"` - AvailableTtls AvailableTtls `json:"AvailableTtls" xml:"AvailableTtls"` - RecordLines RecordLinesInDescribeDomainInfo `json:"RecordLines" xml:"RecordLines"` -} - -// CreateDescribeDomainInfoRequest creates a request to invoke DescribeDomainInfo API -func CreateDescribeDomainInfoRequest() (request *DescribeDomainInfoRequest) { - request = &DescribeDomainInfoRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainInfo", "", "") - return -} - -// CreateDescribeDomainInfoResponse creates a response to parse from DescribeDomainInfo response -func CreateDescribeDomainInfoResponse() (response *DescribeDomainInfoResponse) { - response = &DescribeDomainInfoResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_logs.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_logs.go deleted file mode 100644 index 39e18ce..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_logs.go +++ /dev/null @@ -1,114 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainLogs invokes the alidns.DescribeDomainLogs API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainlogs.html -func (client *Client) DescribeDomainLogs(request *DescribeDomainLogsRequest) (response *DescribeDomainLogsResponse, err error) { - response = CreateDescribeDomainLogsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainLogsWithChan invokes the alidns.DescribeDomainLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainLogsWithChan(request *DescribeDomainLogsRequest) (<-chan *DescribeDomainLogsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainLogsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainLogs(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainLogsWithCallback invokes the alidns.DescribeDomainLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainLogsWithCallback(request *DescribeDomainLogsRequest, callback func(response *DescribeDomainLogsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainLogsResponse - var err error - defer close(result) - response, err = client.DescribeDomainLogs(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainLogsRequest is the request struct for api DescribeDomainLogs -type DescribeDomainLogsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - KeyWord string `position:"Query" name:"KeyWord"` - GroupId string `position:"Query" name:"GroupId"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - StartDate string `position:"Query" name:"StartDate"` - EndDate string `position:"Query" name:"endDate"` -} - -// DescribeDomainLogsResponse is the response struct for api DescribeDomainLogs -type DescribeDomainLogsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainLogs DomainLogs `json:"DomainLogs" xml:"DomainLogs"` -} - -// CreateDescribeDomainLogsRequest creates a request to invoke DescribeDomainLogs API -func CreateDescribeDomainLogsRequest() (request *DescribeDomainLogsRequest) { - request = &DescribeDomainLogsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainLogs", "", "") - return -} - -// CreateDescribeDomainLogsResponse creates a response to parse from DescribeDomainLogs response -func CreateDescribeDomainLogsResponse() (response *DescribeDomainLogsResponse) { - response = &DescribeDomainLogsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_ns.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_ns.go deleted file mode 100644 index 51c86a9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_ns.go +++ /dev/null @@ -1,109 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainNs invokes the alidns.DescribeDomainNs API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainns.html -func (client *Client) DescribeDomainNs(request *DescribeDomainNsRequest) (response *DescribeDomainNsResponse, err error) { - response = CreateDescribeDomainNsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainNsWithChan invokes the alidns.DescribeDomainNs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainNsWithChan(request *DescribeDomainNsRequest) (<-chan *DescribeDomainNsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainNsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainNs(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainNsWithCallback invokes the alidns.DescribeDomainNs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainNsWithCallback(request *DescribeDomainNsRequest, callback func(response *DescribeDomainNsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainNsResponse - var err error - defer close(result) - response, err = client.DescribeDomainNs(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainNsRequest is the request struct for api DescribeDomainNs -type DescribeDomainNsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// DescribeDomainNsResponse is the response struct for api DescribeDomainNs -type DescribeDomainNsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - AllAliDns bool `json:"AllAliDns" xml:"AllAliDns"` - IncludeAliDns bool `json:"IncludeAliDns" xml:"IncludeAliDns"` - DnsServers DnsServersInDescribeDomainNs `json:"DnsServers" xml:"DnsServers"` - ExpectDnsServers ExpectDnsServers `json:"ExpectDnsServers" xml:"ExpectDnsServers"` -} - -// CreateDescribeDomainNsRequest creates a request to invoke DescribeDomainNs API -func CreateDescribeDomainNsRequest() (request *DescribeDomainNsRequest) { - request = &DescribeDomainNsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainNs", "", "") - return -} - -// CreateDescribeDomainNsResponse creates a response to parse from DescribeDomainNs response -func CreateDescribeDomainNsResponse() (response *DescribeDomainNsResponse) { - response = &DescribeDomainNsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_record_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_record_info.go deleted file mode 100644 index c59a7c5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_record_info.go +++ /dev/null @@ -1,119 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainRecordInfo invokes the alidns.DescribeDomainRecordInfo API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecordinfo.html -func (client *Client) DescribeDomainRecordInfo(request *DescribeDomainRecordInfoRequest) (response *DescribeDomainRecordInfoResponse, err error) { - response = CreateDescribeDomainRecordInfoResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainRecordInfoWithChan invokes the alidns.DescribeDomainRecordInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecordinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordInfoWithChan(request *DescribeDomainRecordInfoRequest) (<-chan *DescribeDomainRecordInfoResponse, <-chan error) { - responseChan := make(chan *DescribeDomainRecordInfoResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainRecordInfo(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainRecordInfoWithCallback invokes the alidns.DescribeDomainRecordInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecordinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordInfoWithCallback(request *DescribeDomainRecordInfoRequest, callback func(response *DescribeDomainRecordInfoResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainRecordInfoResponse - var err error - defer close(result) - response, err = client.DescribeDomainRecordInfo(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainRecordInfoRequest is the request struct for api DescribeDomainRecordInfo -type DescribeDomainRecordInfoRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` -} - -// DescribeDomainRecordInfoResponse is the response struct for api DescribeDomainRecordInfo -type DescribeDomainRecordInfoResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - RecordId string `json:"RecordId" xml:"RecordId"` - RR string `json:"RR" xml:"RR"` - Type string `json:"Type" xml:"Type"` - Value string `json:"Value" xml:"Value"` - TTL int `json:"TTL" xml:"TTL"` - Priority int `json:"Priority" xml:"Priority"` - Line string `json:"Line" xml:"Line"` - Status string `json:"Status" xml:"Status"` - Locked bool `json:"Locked" xml:"Locked"` -} - -// CreateDescribeDomainRecordInfoRequest creates a request to invoke DescribeDomainRecordInfo API -func CreateDescribeDomainRecordInfoRequest() (request *DescribeDomainRecordInfoRequest) { - request = &DescribeDomainRecordInfoRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainRecordInfo", "", "") - return -} - -// CreateDescribeDomainRecordInfoResponse creates a response to parse from DescribeDomainRecordInfo response -func CreateDescribeDomainRecordInfoResponse() (response *DescribeDomainRecordInfoResponse) { - response = &DescribeDomainRecordInfoResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_records.go deleted file mode 100644 index bc90538..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_records.go +++ /dev/null @@ -1,117 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainRecords invokes the alidns.DescribeDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecords.html -func (client *Client) DescribeDomainRecords(request *DescribeDomainRecordsRequest) (response *DescribeDomainRecordsResponse, err error) { - response = CreateDescribeDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainRecordsWithChan invokes the alidns.DescribeDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordsWithChan(request *DescribeDomainRecordsRequest) (<-chan *DescribeDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainRecordsWithCallback invokes the alidns.DescribeDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordsWithCallback(request *DescribeDomainRecordsRequest, callback func(response *DescribeDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainRecordsResponse - var err error - defer close(result) - response, err = client.DescribeDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainRecordsRequest is the request struct for api DescribeDomainRecords -type DescribeDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - KeyWord string `position:"Query" name:"KeyWord"` - RRKeyWord string `position:"Query" name:"RRKeyWord"` - TypeKeyWord string `position:"Query" name:"TypeKeyWord"` - ValueKeyWord string `position:"Query" name:"ValueKeyWord"` - OrderBy string `position:"Query" name:"OrderBy"` - Direction string `position:"Query" name:"Direction"` -} - -// DescribeDomainRecordsResponse is the response struct for api DescribeDomainRecords -type DescribeDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainRecords DomainRecordsInDescribeDomainRecords `json:"DomainRecords" xml:"DomainRecords"` -} - -// CreateDescribeDomainRecordsRequest creates a request to invoke DescribeDomainRecords API -func CreateDescribeDomainRecordsRequest() (request *DescribeDomainRecordsRequest) { - request = &DescribeDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainRecords", "", "") - return -} - -// CreateDescribeDomainRecordsResponse creates a response to parse from DescribeDomainRecords response -func CreateDescribeDomainRecordsResponse() (response *DescribeDomainRecordsResponse) { - response = &DescribeDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_whois_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_whois_info.go deleted file mode 100644 index 9984f6d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_whois_info.go +++ /dev/null @@ -1,113 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainWhoisInfo invokes the alidns.DescribeDomainWhoisInfo API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainwhoisinfo.html -func (client *Client) DescribeDomainWhoisInfo(request *DescribeDomainWhoisInfoRequest) (response *DescribeDomainWhoisInfoResponse, err error) { - response = CreateDescribeDomainWhoisInfoResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainWhoisInfoWithChan invokes the alidns.DescribeDomainWhoisInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainwhoisinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainWhoisInfoWithChan(request *DescribeDomainWhoisInfoRequest) (<-chan *DescribeDomainWhoisInfoResponse, <-chan error) { - responseChan := make(chan *DescribeDomainWhoisInfoResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainWhoisInfo(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainWhoisInfoWithCallback invokes the alidns.DescribeDomainWhoisInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainwhoisinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainWhoisInfoWithCallback(request *DescribeDomainWhoisInfoRequest, callback func(response *DescribeDomainWhoisInfoResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainWhoisInfoResponse - var err error - defer close(result) - response, err = client.DescribeDomainWhoisInfo(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainWhoisInfoRequest is the request struct for api DescribeDomainWhoisInfo -type DescribeDomainWhoisInfoRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - GroupId string `position:"Query" name:"GroupId"` -} - -// DescribeDomainWhoisInfoResponse is the response struct for api DescribeDomainWhoisInfo -type DescribeDomainWhoisInfoResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RegistrantName string `json:"RegistrantName" xml:"RegistrantName"` - RegistrantEmail string `json:"RegistrantEmail" xml:"RegistrantEmail"` - Registrar string `json:"Registrar" xml:"Registrar"` - RegistrationDate string `json:"RegistrationDate" xml:"RegistrationDate"` - ExpirationDate string `json:"ExpirationDate" xml:"ExpirationDate"` - StatusList StatusList `json:"StatusList" xml:"StatusList"` - DnsServers DnsServersInDescribeDomainWhoisInfo `json:"DnsServers" xml:"DnsServers"` -} - -// CreateDescribeDomainWhoisInfoRequest creates a request to invoke DescribeDomainWhoisInfo API -func CreateDescribeDomainWhoisInfoRequest() (request *DescribeDomainWhoisInfoRequest) { - request = &DescribeDomainWhoisInfoRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainWhoisInfo", "", "") - return -} - -// CreateDescribeDomainWhoisInfoResponse creates a response to parse from DescribeDomainWhoisInfo response -func CreateDescribeDomainWhoisInfoResponse() (response *DescribeDomainWhoisInfoResponse) { - response = &DescribeDomainWhoisInfoResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domains.go deleted file mode 100644 index a49982b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domains.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomains invokes the alidns.DescribeDomains API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomains.html -func (client *Client) DescribeDomains(request *DescribeDomainsRequest) (response *DescribeDomainsResponse, err error) { - response = CreateDescribeDomainsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainsWithChan invokes the alidns.DescribeDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainsWithChan(request *DescribeDomainsRequest) (<-chan *DescribeDomainsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomains(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainsWithCallback invokes the alidns.DescribeDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainsWithCallback(request *DescribeDomainsRequest, callback func(response *DescribeDomainsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainsResponse - var err error - defer close(result) - response, err = client.DescribeDomains(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainsRequest is the request struct for api DescribeDomains -type DescribeDomainsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - KeyWord string `position:"Query" name:"KeyWord"` - GroupId string `position:"Query" name:"GroupId"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` -} - -// DescribeDomainsResponse is the response struct for api DescribeDomains -type DescribeDomainsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - Domains Domains `json:"Domains" xml:"Domains"` -} - -// CreateDescribeDomainsRequest creates a request to invoke DescribeDomains API -func CreateDescribeDomainsRequest() (request *DescribeDomainsRequest) { - request = &DescribeDomainsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomains", "", "") - return -} - -// CreateDescribeDomainsResponse creates a response to parse from DescribeDomains response -func CreateDescribeDomainsResponse() (response *DescribeDomainsResponse) { - response = &DescribeDomainsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_record_logs.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_record_logs.go deleted file mode 100644 index d9cd3e6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_record_logs.go +++ /dev/null @@ -1,114 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeRecordLogs invokes the alidns.DescribeRecordLogs API synchronously -// api document: https://help.aliyun.com/api/alidns/describerecordlogs.html -func (client *Client) DescribeRecordLogs(request *DescribeRecordLogsRequest) (response *DescribeRecordLogsResponse, err error) { - response = CreateDescribeRecordLogsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeRecordLogsWithChan invokes the alidns.DescribeRecordLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describerecordlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeRecordLogsWithChan(request *DescribeRecordLogsRequest) (<-chan *DescribeRecordLogsResponse, <-chan error) { - responseChan := make(chan *DescribeRecordLogsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeRecordLogs(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeRecordLogsWithCallback invokes the alidns.DescribeRecordLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describerecordlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeRecordLogsWithCallback(request *DescribeRecordLogsRequest, callback func(response *DescribeRecordLogsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeRecordLogsResponse - var err error - defer close(result) - response, err = client.DescribeRecordLogs(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeRecordLogsRequest is the request struct for api DescribeRecordLogs -type DescribeRecordLogsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - KeyWord string `position:"Query" name:"KeyWord"` - StartDate string `position:"Query" name:"StartDate"` - EndDate string `position:"Query" name:"endDate"` -} - -// DescribeRecordLogsResponse is the response struct for api DescribeRecordLogs -type DescribeRecordLogsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - RecordLogs RecordLogs `json:"RecordLogs" xml:"RecordLogs"` -} - -// CreateDescribeRecordLogsRequest creates a request to invoke DescribeRecordLogs API -func CreateDescribeRecordLogsRequest() (request *DescribeRecordLogsRequest) { - request = &DescribeRecordLogsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeRecordLogs", "", "") - return -} - -// CreateDescribeRecordLogsResponse creates a response to parse from DescribeRecordLogs response -func CreateDescribeRecordLogsResponse() (response *DescribeRecordLogsResponse) { - response = &DescribeRecordLogsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_sub_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_sub_domain_records.go deleted file mode 100644 index 2b4ae7d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_sub_domain_records.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeSubDomainRecords invokes the alidns.DescribeSubDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/describesubdomainrecords.html -func (client *Client) DescribeSubDomainRecords(request *DescribeSubDomainRecordsRequest) (response *DescribeSubDomainRecordsResponse, err error) { - response = CreateDescribeSubDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeSubDomainRecordsWithChan invokes the alidns.DescribeSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSubDomainRecordsWithChan(request *DescribeSubDomainRecordsRequest) (<-chan *DescribeSubDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DescribeSubDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeSubDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeSubDomainRecordsWithCallback invokes the alidns.DescribeSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSubDomainRecordsWithCallback(request *DescribeSubDomainRecordsRequest, callback func(response *DescribeSubDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeSubDomainRecordsResponse - var err error - defer close(result) - response, err = client.DescribeSubDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeSubDomainRecordsRequest is the request struct for api DescribeSubDomainRecords -type DescribeSubDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - SubDomain string `position:"Query" name:"SubDomain"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - Type string `position:"Query" name:"Type"` -} - -// DescribeSubDomainRecordsResponse is the response struct for api DescribeSubDomainRecords -type DescribeSubDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainRecords DomainRecordsInDescribeSubDomainRecords `json:"DomainRecords" xml:"DomainRecords"` -} - -// CreateDescribeSubDomainRecordsRequest creates a request to invoke DescribeSubDomainRecords API -func CreateDescribeSubDomainRecordsRequest() (request *DescribeSubDomainRecordsRequest) { - request = &DescribeSubDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeSubDomainRecords", "", "") - return -} - -// CreateDescribeSubDomainRecordsResponse creates a response to parse from DescribeSubDomainRecords response -func CreateDescribeSubDomainRecordsResponse() (response *DescribeSubDomainRecordsResponse) { - response = &DescribeSubDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_support_lines.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_support_lines.go deleted file mode 100644 index 3738c3c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_support_lines.go +++ /dev/null @@ -1,105 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeSupportLines invokes the alidns.DescribeSupportLines API synchronously -// api document: https://help.aliyun.com/api/alidns/describesupportlines.html -func (client *Client) DescribeSupportLines(request *DescribeSupportLinesRequest) (response *DescribeSupportLinesResponse, err error) { - response = CreateDescribeSupportLinesResponse() - err = client.DoAction(request, response) - return -} - -// DescribeSupportLinesWithChan invokes the alidns.DescribeSupportLines API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesupportlines.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSupportLinesWithChan(request *DescribeSupportLinesRequest) (<-chan *DescribeSupportLinesResponse, <-chan error) { - responseChan := make(chan *DescribeSupportLinesResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeSupportLines(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeSupportLinesWithCallback invokes the alidns.DescribeSupportLines API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesupportlines.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSupportLinesWithCallback(request *DescribeSupportLinesRequest, callback func(response *DescribeSupportLinesResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeSupportLinesResponse - var err error - defer close(result) - response, err = client.DescribeSupportLines(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeSupportLinesRequest is the request struct for api DescribeSupportLines -type DescribeSupportLinesRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` -} - -// DescribeSupportLinesResponse is the response struct for api DescribeSupportLines -type DescribeSupportLinesResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordLines RecordLinesInDescribeSupportLines `json:"RecordLines" xml:"RecordLines"` -} - -// CreateDescribeSupportLinesRequest creates a request to invoke DescribeSupportLines API -func CreateDescribeSupportLinesRequest() (request *DescribeSupportLinesRequest) { - request = &DescribeSupportLinesRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeSupportLines", "", "") - return -} - -// CreateDescribeSupportLinesResponse creates a response to parse from DescribeSupportLines response -func CreateDescribeSupportLinesResponse() (response *DescribeSupportLinesResponse) { - response = &DescribeSupportLinesResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/get_main_domain_name.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/get_main_domain_name.go deleted file mode 100644 index e519987..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/get_main_domain_name.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// GetMainDomainName invokes the alidns.GetMainDomainName API synchronously -// api document: https://help.aliyun.com/api/alidns/getmaindomainname.html -func (client *Client) GetMainDomainName(request *GetMainDomainNameRequest) (response *GetMainDomainNameResponse, err error) { - response = CreateGetMainDomainNameResponse() - err = client.DoAction(request, response) - return -} - -// GetMainDomainNameWithChan invokes the alidns.GetMainDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/getmaindomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) GetMainDomainNameWithChan(request *GetMainDomainNameRequest) (<-chan *GetMainDomainNameResponse, <-chan error) { - responseChan := make(chan *GetMainDomainNameResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.GetMainDomainName(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// GetMainDomainNameWithCallback invokes the alidns.GetMainDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/getmaindomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) GetMainDomainNameWithCallback(request *GetMainDomainNameRequest, callback func(response *GetMainDomainNameResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *GetMainDomainNameResponse - var err error - defer close(result) - response, err = client.GetMainDomainName(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// GetMainDomainNameRequest is the request struct for api GetMainDomainName -type GetMainDomainNameRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - InputString string `position:"Query" name:"InputString"` -} - -// GetMainDomainNameResponse is the response struct for api GetMainDomainName -type GetMainDomainNameResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` - RR string `json:"RR" xml:"RR"` - DomainLevel int `json:"DomainLevel" xml:"DomainLevel"` -} - -// CreateGetMainDomainNameRequest creates a request to invoke GetMainDomainName API -func CreateGetMainDomainNameRequest() (request *GetMainDomainNameRequest) { - request = &GetMainDomainNameRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "GetMainDomainName", "", "") - return -} - -// CreateGetMainDomainNameResponse creates a response to parse from GetMainDomainName response -func CreateGetMainDomainNameResponse() (response *GetMainDomainNameResponse) { - response = &GetMainDomainNameResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/modify_hichina_domain_dns.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/modify_hichina_domain_dns.go deleted file mode 100644 index 3b452cd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/modify_hichina_domain_dns.go +++ /dev/null @@ -1,107 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ModifyHichinaDomainDNS invokes the alidns.ModifyHichinaDomainDNS API synchronously -// api document: https://help.aliyun.com/api/alidns/modifyhichinadomaindns.html -func (client *Client) ModifyHichinaDomainDNS(request *ModifyHichinaDomainDNSRequest) (response *ModifyHichinaDomainDNSResponse, err error) { - response = CreateModifyHichinaDomainDNSResponse() - err = client.DoAction(request, response) - return -} - -// ModifyHichinaDomainDNSWithChan invokes the alidns.ModifyHichinaDomainDNS API asynchronously -// api document: https://help.aliyun.com/api/alidns/modifyhichinadomaindns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ModifyHichinaDomainDNSWithChan(request *ModifyHichinaDomainDNSRequest) (<-chan *ModifyHichinaDomainDNSResponse, <-chan error) { - responseChan := make(chan *ModifyHichinaDomainDNSResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ModifyHichinaDomainDNS(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ModifyHichinaDomainDNSWithCallback invokes the alidns.ModifyHichinaDomainDNS API asynchronously -// api document: https://help.aliyun.com/api/alidns/modifyhichinadomaindns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ModifyHichinaDomainDNSWithCallback(request *ModifyHichinaDomainDNSRequest, callback func(response *ModifyHichinaDomainDNSResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ModifyHichinaDomainDNSResponse - var err error - defer close(result) - response, err = client.ModifyHichinaDomainDNS(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ModifyHichinaDomainDNSRequest is the request struct for api ModifyHichinaDomainDNS -type ModifyHichinaDomainDNSRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// ModifyHichinaDomainDNSResponse is the response struct for api ModifyHichinaDomainDNS -type ModifyHichinaDomainDNSResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - OriginalDnsServers OriginalDnsServers `json:"OriginalDnsServers" xml:"OriginalDnsServers"` - NewDnsServers NewDnsServers `json:"NewDnsServers" xml:"NewDnsServers"` -} - -// CreateModifyHichinaDomainDNSRequest creates a request to invoke ModifyHichinaDomainDNS API -func CreateModifyHichinaDomainDNSRequest() (request *ModifyHichinaDomainDNSRequest) { - request = &ModifyHichinaDomainDNSRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ModifyHichinaDomainDNS", "", "") - return -} - -// CreateModifyHichinaDomainDNSResponse creates a response to parse from ModifyHichinaDomainDNS response -func CreateModifyHichinaDomainDNSResponse() (response *ModifyHichinaDomainDNSResponse) { - response = &ModifyHichinaDomainDNSResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/retrieval_domain_name.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/retrieval_domain_name.go deleted file mode 100644 index 753b85d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/retrieval_domain_name.go +++ /dev/null @@ -1,107 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// RetrievalDomainName invokes the alidns.RetrievalDomainName API synchronously -// api document: https://help.aliyun.com/api/alidns/retrievaldomainname.html -func (client *Client) RetrievalDomainName(request *RetrievalDomainNameRequest) (response *RetrievalDomainNameResponse, err error) { - response = CreateRetrievalDomainNameResponse() - err = client.DoAction(request, response) - return -} - -// RetrievalDomainNameWithChan invokes the alidns.RetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/retrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) RetrievalDomainNameWithChan(request *RetrievalDomainNameRequest) (<-chan *RetrievalDomainNameResponse, <-chan error) { - responseChan := make(chan *RetrievalDomainNameResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.RetrievalDomainName(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// RetrievalDomainNameWithCallback invokes the alidns.RetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/retrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) RetrievalDomainNameWithCallback(request *RetrievalDomainNameRequest, callback func(response *RetrievalDomainNameResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *RetrievalDomainNameResponse - var err error - defer close(result) - response, err = client.RetrievalDomainName(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// RetrievalDomainNameRequest is the request struct for api RetrievalDomainName -type RetrievalDomainNameRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// RetrievalDomainNameResponse is the response struct for api RetrievalDomainName -type RetrievalDomainNameResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` - WhoisEmail string `json:"WhoisEmail" xml:"WhoisEmail"` -} - -// CreateRetrievalDomainNameRequest creates a request to invoke RetrievalDomainName API -func CreateRetrievalDomainNameRequest() (request *RetrievalDomainNameRequest) { - request = &RetrievalDomainNameRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "RetrievalDomainName", "", "") - return -} - -// CreateRetrievalDomainNameResponse creates a response to parse from RetrievalDomainName response -func CreateRetrievalDomainNameResponse() (response *RetrievalDomainNameResponse) { - response = &RetrievalDomainNameResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_dnsslb_status.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_dnsslb_status.go deleted file mode 100644 index 858d6fe..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_dnsslb_status.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SetDNSSLBStatus invokes the alidns.SetDNSSLBStatus API synchronously -// api document: https://help.aliyun.com/api/alidns/setdnsslbstatus.html -func (client *Client) SetDNSSLBStatus(request *SetDNSSLBStatusRequest) (response *SetDNSSLBStatusResponse, err error) { - response = CreateSetDNSSLBStatusResponse() - err = client.DoAction(request, response) - return -} - -// SetDNSSLBStatusWithChan invokes the alidns.SetDNSSLBStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdnsslbstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDNSSLBStatusWithChan(request *SetDNSSLBStatusRequest) (<-chan *SetDNSSLBStatusResponse, <-chan error) { - responseChan := make(chan *SetDNSSLBStatusResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SetDNSSLBStatus(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SetDNSSLBStatusWithCallback invokes the alidns.SetDNSSLBStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdnsslbstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDNSSLBStatusWithCallback(request *SetDNSSLBStatusRequest, callback func(response *SetDNSSLBStatusResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SetDNSSLBStatusResponse - var err error - defer close(result) - response, err = client.SetDNSSLBStatus(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SetDNSSLBStatusRequest is the request struct for api SetDNSSLBStatus -type SetDNSSLBStatusRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - SubDomain string `position:"Query" name:"SubDomain"` - Open requests.Boolean `position:"Query" name:"Open"` -} - -// SetDNSSLBStatusResponse is the response struct for api SetDNSSLBStatus -type SetDNSSLBStatusResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordCount int `json:"RecordCount" xml:"RecordCount"` - Open bool `json:"Open" xml:"Open"` -} - -// CreateSetDNSSLBStatusRequest creates a request to invoke SetDNSSLBStatus API -func CreateSetDNSSLBStatusRequest() (request *SetDNSSLBStatusRequest) { - request = &SetDNSSLBStatusRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "SetDNSSLBStatus", "", "") - return -} - -// CreateSetDNSSLBStatusResponse creates a response to parse from SetDNSSLBStatus response -func CreateSetDNSSLBStatusResponse() (response *SetDNSSLBStatusResponse) { - response = &SetDNSSLBStatusResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_domain_record_status.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_domain_record_status.go deleted file mode 100644 index 29ba5f7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_domain_record_status.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SetDomainRecordStatus invokes the alidns.SetDomainRecordStatus API synchronously -// api document: https://help.aliyun.com/api/alidns/setdomainrecordstatus.html -func (client *Client) SetDomainRecordStatus(request *SetDomainRecordStatusRequest) (response *SetDomainRecordStatusResponse, err error) { - response = CreateSetDomainRecordStatusResponse() - err = client.DoAction(request, response) - return -} - -// SetDomainRecordStatusWithChan invokes the alidns.SetDomainRecordStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdomainrecordstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDomainRecordStatusWithChan(request *SetDomainRecordStatusRequest) (<-chan *SetDomainRecordStatusResponse, <-chan error) { - responseChan := make(chan *SetDomainRecordStatusResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SetDomainRecordStatus(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SetDomainRecordStatusWithCallback invokes the alidns.SetDomainRecordStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdomainrecordstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDomainRecordStatusWithCallback(request *SetDomainRecordStatusRequest, callback func(response *SetDomainRecordStatusResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SetDomainRecordStatusResponse - var err error - defer close(result) - response, err = client.SetDomainRecordStatus(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SetDomainRecordStatusRequest is the request struct for api SetDomainRecordStatus -type SetDomainRecordStatusRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` - Status string `position:"Query" name:"Status"` -} - -// SetDomainRecordStatusResponse is the response struct for api SetDomainRecordStatus -type SetDomainRecordStatusResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` - Status string `json:"Status" xml:"Status"` -} - -// CreateSetDomainRecordStatusRequest creates a request to invoke SetDomainRecordStatus API -func CreateSetDomainRecordStatusRequest() (request *SetDomainRecordStatusRequest) { - request = &SetDomainRecordStatusRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "SetDomainRecordStatus", "", "") - return -} - -// CreateSetDomainRecordStatusResponse creates a response to parse from SetDomainRecordStatus response -func CreateSetDomainRecordStatusResponse() (response *SetDomainRecordStatusResponse) { - response = &SetDomainRecordStatusResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_available_ttls.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_available_ttls.go deleted file mode 100644 index e1d0ac7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_available_ttls.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// AvailableTtls is a nested struct in alidns response -type AvailableTtls struct { - AvailableTtl []string `json:"AvailableTtl" xml:"AvailableTtl"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_product.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_product.go deleted file mode 100644 index 50a2e86..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_product.go +++ /dev/null @@ -1,48 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsProduct is a nested struct in alidns response -type DnsProduct struct { - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - StartTime string `json:"StartTime" xml:"StartTime"` - EndTime string `json:"EndTime" xml:"EndTime"` - StartTimestamp int `json:"StartTimestamp" xml:"StartTimestamp"` - EndTimestamp int `json:"EndTimestamp" xml:"EndTimestamp"` - Domain string `json:"Domain" xml:"Domain"` - BindCount int `json:"BindCount" xml:"BindCount"` - BindUsedCount int `json:"BindUsedCount" xml:"BindUsedCount"` - TTLMinValue int `json:"TTLMinValue" xml:"TTLMinValue"` - SubDomainLevel int `json:"SubDomainLevel" xml:"SubDomainLevel"` - DnsSLBCount int `json:"DnsSLBCount" xml:"DnsSLBCount"` - URLForwardCount int `json:"URLForwardCount" xml:"URLForwardCount"` - DDosDefendFlow int `json:"DDosDefendFlow" xml:"DDosDefendFlow"` - DDosDefendQuery int `json:"DDosDefendQuery" xml:"DDosDefendQuery"` - OverseaDDosDefendFlow int `json:"OverseaDDosDefendFlow" xml:"OverseaDDosDefendFlow"` - SearchEngineLines string `json:"SearchEngineLines" xml:"SearchEngineLines"` - ISPLines string `json:"ISPLines" xml:"ISPLines"` - ISPRegionLines string `json:"ISPRegionLines" xml:"ISPRegionLines"` - OverseaLine string `json:"OverseaLine" xml:"OverseaLine"` - MonitorNodeCount int `json:"MonitorNodeCount" xml:"MonitorNodeCount"` - MonitorFrequency int `json:"MonitorFrequency" xml:"MonitorFrequency"` - MonitorTaskCount int `json:"MonitorTaskCount" xml:"MonitorTaskCount"` - RegionLines bool `json:"RegionLines" xml:"RegionLines"` - Gslb bool `json:"Gslb" xml:"Gslb"` - InClean bool `json:"InClean" xml:"InClean"` - InBlackHole bool `json:"InBlackHole" xml:"InBlackHole"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_products.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_products.go deleted file mode 100644 index 636a96f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_products.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsProducts is a nested struct in alidns response -type DnsProducts struct { - DnsProduct []DnsProduct `json:"DnsProduct" xml:"DnsProduct"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_add_domain.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_add_domain.go deleted file mode 100644 index d6f5bfb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_add_domain.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInAddDomain is a nested struct in alidns response -type DnsServersInAddDomain struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_dns_product_instance.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_dns_product_instance.go deleted file mode 100644 index 64d0db2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_dns_product_instance.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDnsProductInstance is a nested struct in alidns response -type DnsServersInDescribeDnsProductInstance struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_info.go deleted file mode 100644 index debe648..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_info.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomainInfo is a nested struct in alidns response -type DnsServersInDescribeDomainInfo struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_ns.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_ns.go deleted file mode 100644 index 67d752e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_ns.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomainNs is a nested struct in alidns response -type DnsServersInDescribeDomainNs struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_whois_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_whois_info.go deleted file mode 100644 index fc03ed4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_whois_info.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomainWhoisInfo is a nested struct in alidns response -type DnsServersInDescribeDomainWhoisInfo struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domains.go deleted file mode 100644 index dada40a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomains is a nested struct in alidns response -type DnsServersInDescribeDomains struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain.go deleted file mode 100644 index 0dd46e6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain.go +++ /dev/null @@ -1,35 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Domain is a nested struct in alidns response -type Domain struct { - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - AliDomain bool `json:"AliDomain" xml:"AliDomain"` - RecordCount int `json:"RecordCount" xml:"RecordCount"` - RegistrantEmail string `json:"RegistrantEmail" xml:"RegistrantEmail"` - Remark string `json:"Remark" xml:"Remark"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - InstanceEndTime string `json:"InstanceEndTime" xml:"InstanceEndTime"` - InstanceExpired bool `json:"InstanceExpired" xml:"InstanceExpired"` - DnsServers DnsServersInDescribeDomains `json:"DnsServers" xml:"DnsServers"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_group.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_group.go deleted file mode 100644 index 89646e8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_group.go +++ /dev/null @@ -1,23 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainGroup is a nested struct in alidns response -type DomainGroup struct { - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - DomainCount int `json:"DomainCount" xml:"DomainCount"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_groups.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_groups.go deleted file mode 100644 index ce193d8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_groups.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainGroups is a nested struct in alidns response -type DomainGroups struct { - DomainGroup []DomainGroup `json:"DomainGroup" xml:"DomainGroup"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_log.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_log.go deleted file mode 100644 index 40128f6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_log.go +++ /dev/null @@ -1,26 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainLog is a nested struct in alidns response -type DomainLog struct { - ActionTime string `json:"ActionTime" xml:"ActionTime"` - ActionTimestamp int `json:"ActionTimestamp" xml:"ActionTimestamp"` - DomainName string `json:"DomainName" xml:"DomainName"` - Action string `json:"Action" xml:"Action"` - Message string `json:"Message" xml:"Message"` - ClientIp string `json:"ClientIp" xml:"ClientIp"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_logs.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_logs.go deleted file mode 100644 index 3964d02..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_logs.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainLogs is a nested struct in alidns response -type DomainLogs struct { - DomainLog []DomainLog `json:"DomainLog" xml:"DomainLog"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_domain_records.go deleted file mode 100644 index 5ef9725..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_domain_records.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainRecordsInDescribeDomainRecords is a nested struct in alidns response -type DomainRecordsInDescribeDomainRecords struct { - Record []Record `json:"Record" xml:"Record"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_sub_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_sub_domain_records.go deleted file mode 100644 index 9b64ba0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_sub_domain_records.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainRecordsInDescribeSubDomainRecords is a nested struct in alidns response -type DomainRecordsInDescribeSubDomainRecords struct { - Record []Record `json:"Record" xml:"Record"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domains.go deleted file mode 100644 index aff37f8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Domains is a nested struct in alidns response -type Domains struct { - Domain []Domain `json:"Domain" xml:"Domain"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_expect_dns_servers.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_expect_dns_servers.go deleted file mode 100644 index 9befd95..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_expect_dns_servers.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ExpectDnsServers is a nested struct in alidns response -type ExpectDnsServers struct { - ExpectDnsServer []string `json:"ExpectDnsServer" xml:"ExpectDnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_result.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_result.go deleted file mode 100644 index 0fc2d30..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_result.go +++ /dev/null @@ -1,22 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// FailResult is a nested struct in alidns response -type FailResult struct { - BatchIndex string `json:"BatchIndex" xml:"BatchIndex"` - ErrorCode string `json:"ErrorCode" xml:"ErrorCode"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_results.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_results.go deleted file mode 100644 index 54ee4d1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_results.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// FailResults is a nested struct in alidns response -type FailResults struct { - FailResult []FailResult `json:"FailResult" xml:"FailResult"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_new_dns_servers.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_new_dns_servers.go deleted file mode 100644 index 5fd8b18..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_new_dns_servers.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// NewDnsServers is a nested struct in alidns response -type NewDnsServers struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_original_dns_servers.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_original_dns_servers.go deleted file mode 100644 index b6f90bb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_original_dns_servers.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// OriginalDnsServers is a nested struct in alidns response -type OriginalDnsServers struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record.go deleted file mode 100644 index b4f0f19..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record.go +++ /dev/null @@ -1,32 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Record is a nested struct in alidns response -type Record struct { - Locked bool `json:"Locked" xml:"Locked"` - Type string `json:"Type" xml:"Type"` - Line string `json:"Line" xml:"Line"` - RR string `json:"RR" xml:"RR"` - Remark string `json:"Remark" xml:"Remark"` - Priority int `json:"Priority" xml:"Priority"` - RecordId string `json:"RecordId" xml:"RecordId"` - Value string `json:"Value" xml:"Value"` - DomainName string `json:"DomainName" xml:"DomainName"` - Weight int `json:"Weight" xml:"Weight"` - Status string `json:"Status" xml:"Status"` - TTL int `json:"TTL" xml:"TTL"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_line.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_line.go deleted file mode 100644 index 2219c2d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_line.go +++ /dev/null @@ -1,24 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLine is a nested struct in alidns response -type RecordLine struct { - LineName string `json:"LineName" xml:"LineName"` - FatherCode string `json:"FatherCode" xml:"FatherCode"` - LineDisplayName string `json:"LineDisplayName" xml:"LineDisplayName"` - LineCode string `json:"LineCode" xml:"LineCode"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_domain_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_domain_info.go deleted file mode 100644 index 203f525..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_domain_info.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLinesInDescribeDomainInfo is a nested struct in alidns response -type RecordLinesInDescribeDomainInfo struct { - RecordLine []RecordLine `json:"RecordLine" xml:"RecordLine"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_support_lines.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_support_lines.go deleted file mode 100644 index 5c2e05f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_support_lines.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLinesInDescribeSupportLines is a nested struct in alidns response -type RecordLinesInDescribeSupportLines struct { - RecordLine []RecordLine `json:"RecordLine" xml:"RecordLine"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_log.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_log.go deleted file mode 100644 index ee45835..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_log.go +++ /dev/null @@ -1,25 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLog is a nested struct in alidns response -type RecordLog struct { - ActionTime string `json:"ActionTime" xml:"ActionTime"` - ActionTimestamp int `json:"ActionTimestamp" xml:"ActionTimestamp"` - Action string `json:"Action" xml:"Action"` - Message string `json:"Message" xml:"Message"` - ClientIp string `json:"ClientIp" xml:"ClientIp"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_logs.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_logs.go deleted file mode 100644 index b5a42b5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_logs.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLogs is a nested struct in alidns response -type RecordLogs struct { - RecordLog []RecordLog `json:"RecordLog" xml:"RecordLog"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domain.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domain.go deleted file mode 100644 index 043a447..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domain.go +++ /dev/null @@ -1,24 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// SlbSubDomain is a nested struct in alidns response -type SlbSubDomain struct { - SubDomain string `json:"SubDomain" xml:"SubDomain"` - RecordCount int `json:"RecordCount" xml:"RecordCount"` - Open bool `json:"Open" xml:"Open"` - Type string `json:"Type" xml:"Type"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domains.go deleted file mode 100644 index 4618d59..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// SlbSubDomains is a nested struct in alidns response -type SlbSubDomains struct { - SlbSubDomain []SlbSubDomain `json:"SlbSubDomain" xml:"SlbSubDomain"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_status_list.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_status_list.go deleted file mode 100644 index 341e43d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_status_list.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// StatusList is a nested struct in alidns response -type StatusList struct { - Status []string `json:"Status" xml:"Status"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_batch_domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_batch_domain_records.go deleted file mode 100644 index c90e204..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_batch_domain_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateBatchDomainRecords invokes the alidns.UpdateBatchDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/updatebatchdomainrecords.html -func (client *Client) UpdateBatchDomainRecords(request *UpdateBatchDomainRecordsRequest) (response *UpdateBatchDomainRecordsResponse, err error) { - response = CreateUpdateBatchDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// UpdateBatchDomainRecordsWithChan invokes the alidns.UpdateBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateBatchDomainRecordsWithChan(request *UpdateBatchDomainRecordsRequest) (<-chan *UpdateBatchDomainRecordsResponse, <-chan error) { - responseChan := make(chan *UpdateBatchDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateBatchDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateBatchDomainRecordsWithCallback invokes the alidns.UpdateBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateBatchDomainRecordsWithCallback(request *UpdateBatchDomainRecordsRequest, callback func(response *UpdateBatchDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateBatchDomainRecordsResponse - var err error - defer close(result) - response, err = client.UpdateBatchDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateBatchDomainRecordsRequest is the request struct for api UpdateBatchDomainRecords -type UpdateBatchDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Records string `position:"Query" name:"Records"` -} - -// UpdateBatchDomainRecordsResponse is the response struct for api UpdateBatchDomainRecords -type UpdateBatchDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateUpdateBatchDomainRecordsRequest creates a request to invoke UpdateBatchDomainRecords API -func CreateUpdateBatchDomainRecordsRequest() (request *UpdateBatchDomainRecordsRequest) { - request = &UpdateBatchDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateBatchDomainRecords", "", "") - return -} - -// CreateUpdateBatchDomainRecordsResponse creates a response to parse from UpdateBatchDomainRecords response -func CreateUpdateBatchDomainRecordsResponse() (response *UpdateBatchDomainRecordsResponse) { - response = &UpdateBatchDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_dnsslb_weight.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_dnsslb_weight.go deleted file mode 100644 index ec372a2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_dnsslb_weight.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateDNSSLBWeight invokes the alidns.UpdateDNSSLBWeight API synchronously -// api document: https://help.aliyun.com/api/alidns/updatednsslbweight.html -func (client *Client) UpdateDNSSLBWeight(request *UpdateDNSSLBWeightRequest) (response *UpdateDNSSLBWeightResponse, err error) { - response = CreateUpdateDNSSLBWeightResponse() - err = client.DoAction(request, response) - return -} - -// UpdateDNSSLBWeightWithChan invokes the alidns.UpdateDNSSLBWeight API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatednsslbweight.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDNSSLBWeightWithChan(request *UpdateDNSSLBWeightRequest) (<-chan *UpdateDNSSLBWeightResponse, <-chan error) { - responseChan := make(chan *UpdateDNSSLBWeightResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateDNSSLBWeight(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateDNSSLBWeightWithCallback invokes the alidns.UpdateDNSSLBWeight API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatednsslbweight.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDNSSLBWeightWithCallback(request *UpdateDNSSLBWeightRequest, callback func(response *UpdateDNSSLBWeightResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateDNSSLBWeightResponse - var err error - defer close(result) - response, err = client.UpdateDNSSLBWeight(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateDNSSLBWeightRequest is the request struct for api UpdateDNSSLBWeight -type UpdateDNSSLBWeightRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` - Weight requests.Integer `position:"Query" name:"Weight"` -} - -// UpdateDNSSLBWeightResponse is the response struct for api UpdateDNSSLBWeight -type UpdateDNSSLBWeightResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` - Weight int `json:"Weight" xml:"Weight"` -} - -// CreateUpdateDNSSLBWeightRequest creates a request to invoke UpdateDNSSLBWeight API -func CreateUpdateDNSSLBWeightRequest() (request *UpdateDNSSLBWeightRequest) { - request = &UpdateDNSSLBWeightRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateDNSSLBWeight", "", "") - return -} - -// CreateUpdateDNSSLBWeightResponse creates a response to parse from UpdateDNSSLBWeight response -func CreateUpdateDNSSLBWeightResponse() (response *UpdateDNSSLBWeightResponse) { - response = &UpdateDNSSLBWeightResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_group.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_group.go deleted file mode 100644 index 61f1fb1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_group.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateDomainGroup invokes the alidns.UpdateDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/updatedomaingroup.html -func (client *Client) UpdateDomainGroup(request *UpdateDomainGroupRequest) (response *UpdateDomainGroupResponse, err error) { - response = CreateUpdateDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// UpdateDomainGroupWithChan invokes the alidns.UpdateDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainGroupWithChan(request *UpdateDomainGroupRequest) (<-chan *UpdateDomainGroupResponse, <-chan error) { - responseChan := make(chan *UpdateDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateDomainGroupWithCallback invokes the alidns.UpdateDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainGroupWithCallback(request *UpdateDomainGroupRequest, callback func(response *UpdateDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateDomainGroupResponse - var err error - defer close(result) - response, err = client.UpdateDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateDomainGroupRequest is the request struct for api UpdateDomainGroup -type UpdateDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - GroupId string `position:"Query" name:"GroupId"` - GroupName string `position:"Query" name:"GroupName"` -} - -// UpdateDomainGroupResponse is the response struct for api UpdateDomainGroup -type UpdateDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateUpdateDomainGroupRequest creates a request to invoke UpdateDomainGroup API -func CreateUpdateDomainGroupRequest() (request *UpdateDomainGroupRequest) { - request = &UpdateDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateDomainGroup", "", "") - return -} - -// CreateUpdateDomainGroupResponse creates a response to parse from UpdateDomainGroup response -func CreateUpdateDomainGroupResponse() (response *UpdateDomainGroupResponse) { - response = &UpdateDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_record.go b/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_record.go deleted file mode 100644 index 1e9c0da..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_record.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateDomainRecord invokes the alidns.UpdateDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/updatedomainrecord.html -func (client *Client) UpdateDomainRecord(request *UpdateDomainRecordRequest) (response *UpdateDomainRecordResponse, err error) { - response = CreateUpdateDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// UpdateDomainRecordWithChan invokes the alidns.UpdateDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainRecordWithChan(request *UpdateDomainRecordRequest) (<-chan *UpdateDomainRecordResponse, <-chan error) { - responseChan := make(chan *UpdateDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateDomainRecordWithCallback invokes the alidns.UpdateDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainRecordWithCallback(request *UpdateDomainRecordRequest, callback func(response *UpdateDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateDomainRecordResponse - var err error - defer close(result) - response, err = client.UpdateDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateDomainRecordRequest is the request struct for api UpdateDomainRecord -type UpdateDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` - Value string `position:"Query" name:"Value"` - TTL requests.Integer `position:"Query" name:"TTL"` - Priority requests.Integer `position:"Query" name:"Priority"` - Line string `position:"Query" name:"Line"` -} - -// UpdateDomainRecordResponse is the response struct for api UpdateDomainRecord -type UpdateDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` -} - -// CreateUpdateDomainRecordRequest creates a request to invoke UpdateDomainRecord API -func CreateUpdateDomainRecordRequest() (request *UpdateDomainRecordRequest) { - request = &UpdateDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateDomainRecord", "", "") - return -} - -// CreateUpdateDomainRecordResponse creates a response to parse from UpdateDomainRecord response -func CreateUpdateDomainRecordResponse() (response *UpdateDomainRecordResponse) { - response = &UpdateDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/LICENSE.txt b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/LICENSE.txt deleted file mode 100644 index d645695..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/NOTICE.txt b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/NOTICE.txt deleted file mode 100644 index 5f14d11..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/NOTICE.txt +++ /dev/null @@ -1,3 +0,0 @@ -AWS SDK for Go -Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. -Copyright 2014-2015 Stripe, Inc. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go deleted file mode 100644 index 56fdfc2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go +++ /dev/null @@ -1,145 +0,0 @@ -// Package awserr represents API error interface accessors for the SDK. -package awserr - -// An Error wraps lower level errors with code, message and an original error. -// The underlying concrete error type may also satisfy other interfaces which -// can be to used to obtain more specific information about the error. -// -// Calling Error() or String() will always include the full information about -// an error based on its underlying type. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Get error details -// log.Println("Error:", awsErr.Code(), awsErr.Message()) -// -// // Prints out full error message, including original error if there was one. -// log.Println("Error:", awsErr.Error()) -// -// // Get original error -// if origErr := awsErr.OrigErr(); origErr != nil { -// // operate on original error. -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type Error interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErr() error -} - -// BatchError is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Deprecated: Replaced with BatchedErrors. Only defined for backwards -// compatibility. -type BatchError interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// BatchedErrors is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Replaces BatchError -type BatchedErrors interface { - // Satisfy the base Error interface. - Error - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// New returns an Error object described by the code, message, and origErr. -// -// If origErr satisfies the Error interface it will not be wrapped within a new -// Error object and will instead be returned. -func New(code, message string, origErr error) Error { - var errs []error - if origErr != nil { - errs = append(errs, origErr) - } - return newBaseError(code, message, errs) -} - -// NewBatchError returns an BatchedErrors with a collection of errors as an -// array of errors. -func NewBatchError(code, message string, errs []error) BatchedErrors { - return newBaseError(code, message, errs) -} - -// A RequestFailure is an interface to extract request failure information from -// an Error such as the request ID of the failed request returned by a service. -// RequestFailures may not always have a requestID value if the request failed -// prior to reaching the service such as a connection error. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if reqerr, ok := err.(RequestFailure); ok { -// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID()) -// } else { -// log.Println("Error:", err.Error()) -// } -// } -// -// Combined with awserr.Error: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Generic AWS Error with Code, Message, and original error (if any) -// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) -// -// if reqErr, ok := err.(awserr.RequestFailure); ok { -// // A service error occurred -// fmt.Println(reqErr.StatusCode(), reqErr.RequestID()) -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type RequestFailure interface { - Error - - // The status code of the HTTP response. - StatusCode() int - - // The request ID returned by the service for a request failure. This will - // be empty if no request ID is available such as the request failed due - // to a connection error. - RequestID() string -} - -// NewRequestFailure returns a new request error wrapper for the given Error -// provided. -func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { - return newRequestError(err, statusCode, reqID) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go deleted file mode 100644 index 0202a00..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go +++ /dev/null @@ -1,194 +0,0 @@ -package awserr - -import "fmt" - -// SprintError returns a string of the formatted error code. -// -// Both extra and origErr are optional. If they are included their lines -// will be added, but if they are not included their lines will be ignored. -func SprintError(code, message, extra string, origErr error) string { - msg := fmt.Sprintf("%s: %s", code, message) - if extra != "" { - msg = fmt.Sprintf("%s\n\t%s", msg, extra) - } - if origErr != nil { - msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) - } - return msg -} - -// A baseError wraps the code and message which defines an error. It also -// can be used to wrap an original error object. -// -// Should be used as the root for errors satisfying the awserr.Error. Also -// for any error which does not fit into a specific error wrapper type. -type baseError struct { - // Classification of error - code string - - // Detailed information about error - message string - - // Optional original error this error is based off of. Allows building - // chained errors. - errs []error -} - -// newBaseError returns an error object for the code, message, and errors. -// -// code is a short no whitespace phrase depicting the classification of -// the error that is being created. -// -// message is the free flow string containing detailed information about the -// error. -// -// origErrs is the error objects which will be nested under the new errors to -// be returned. -func newBaseError(code, message string, origErrs []error) *baseError { - b := &baseError{ - code: code, - message: message, - errs: origErrs, - } - - return b -} - -// Error returns the string representation of the error. -// -// See ErrorWithExtra for formatting. -// -// Satisfies the error interface. -func (b baseError) Error() string { - size := len(b.errs) - if size > 0 { - return SprintError(b.code, b.message, "", errorList(b.errs)) - } - - return SprintError(b.code, b.message, "", nil) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (b baseError) String() string { - return b.Error() -} - -// Code returns the short phrase depicting the classification of the error. -func (b baseError) Code() string { - return b.code -} - -// Message returns the error details message. -func (b baseError) Message() string { - return b.message -} - -// OrigErr returns the original error if one was set. Nil is returned if no -// error was set. This only returns the first element in the list. If the full -// list is needed, use BatchedErrors. -func (b baseError) OrigErr() error { - switch len(b.errs) { - case 0: - return nil - case 1: - return b.errs[0] - default: - if err, ok := b.errs[0].(Error); ok { - return NewBatchError(err.Code(), err.Message(), b.errs[1:]) - } - return NewBatchError("BatchedErrors", - "multiple errors occurred", b.errs) - } -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (b baseError) OrigErrs() []error { - return b.errs -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError Error - -// A requestError wraps a request or service error. -// -// Composed of baseError for code, message, and original error. -type requestError struct { - awsError - statusCode int - requestID string -} - -// newRequestError returns a wrapped error with additional information for -// request status code, and service requestID. -// -// Should be used to wrap all request which involve service requests. Even if -// the request failed without a service response, but had an HTTP status code -// that may be meaningful. -// -// Also wraps original errors via the baseError. -func newRequestError(err Error, statusCode int, requestID string) *requestError { - return &requestError{ - awsError: err, - statusCode: statusCode, - requestID: requestID, - } -} - -// Error returns the string representation of the error. -// Satisfies the error interface. -func (r requestError) Error() string { - extra := fmt.Sprintf("status code: %d, request id: %s", - r.statusCode, r.requestID) - return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (r requestError) String() string { - return r.Error() -} - -// StatusCode returns the wrapped status code for the error -func (r requestError) StatusCode() int { - return r.statusCode -} - -// RequestID returns the wrapped requestID -func (r requestError) RequestID() string { - return r.requestID -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (r requestError) OrigErrs() []error { - if b, ok := r.awsError.(BatchedErrors); ok { - return b.OrigErrs() - } - return []error{r.OrigErr()} -} - -// An error list that satisfies the golang interface -type errorList []error - -// Error returns the string representation of the error. -// -// Satisfies the error interface. -func (e errorList) Error() string { - msg := "" - // How do we want to handle the array size being zero - if size := len(e); size > 0 { - for i := 0; i < size; i++ { - msg += fmt.Sprintf("%s", e[i].Error()) - // We check the next index to see if it is within the slice. - // If it is, then we append a newline. We do this, because unit tests - // could be broken with the additional '\n' - if i+1 < size { - msg += "\n" - } - } - } - return msg -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go deleted file mode 100644 index 1a3d106..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go +++ /dev/null @@ -1,108 +0,0 @@ -package awsutil - -import ( - "io" - "reflect" - "time" -) - -// Copy deeply copies a src structure to dst. Useful for copying request and -// response structures. -// -// Can copy between structs of different type, but will only copy fields which -// are assignable, and exist in both structs. Fields which are not assignable, -// or do not exist in both structs are ignored. -func Copy(dst, src interface{}) { - dstval := reflect.ValueOf(dst) - if !dstval.IsValid() { - panic("Copy dst cannot be nil") - } - - rcopy(dstval, reflect.ValueOf(src), true) -} - -// CopyOf returns a copy of src while also allocating the memory for dst. -// src must be a pointer type or this operation will fail. -func CopyOf(src interface{}) (dst interface{}) { - dsti := reflect.New(reflect.TypeOf(src).Elem()) - dst = dsti.Interface() - rcopy(dsti, reflect.ValueOf(src), true) - return -} - -// rcopy performs a recursive copy of values from the source to destination. -// -// root is used to skip certain aspects of the copy which are not valid -// for the root node of a object. -func rcopy(dst, src reflect.Value, root bool) { - if !src.IsValid() { - return - } - - switch src.Kind() { - case reflect.Ptr: - if _, ok := src.Interface().(io.Reader); ok { - if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { - dst.Elem().Set(src) - } else if dst.CanSet() { - dst.Set(src) - } - } else { - e := src.Type().Elem() - if dst.CanSet() && !src.IsNil() { - if _, ok := src.Interface().(*time.Time); !ok { - dst.Set(reflect.New(e)) - } else { - tempValue := reflect.New(e) - tempValue.Elem().Set(src.Elem()) - // Sets time.Time's unexported values - dst.Set(tempValue) - } - } - if src.Elem().IsValid() { - // Keep the current root state since the depth hasn't changed - rcopy(dst.Elem(), src.Elem(), root) - } - } - case reflect.Struct: - t := dst.Type() - for i := 0; i < t.NumField(); i++ { - name := t.Field(i).Name - srcVal := src.FieldByName(name) - dstVal := dst.FieldByName(name) - if srcVal.IsValid() && dstVal.CanSet() { - rcopy(dstVal, srcVal, false) - } - } - case reflect.Slice: - if src.IsNil() { - break - } - - s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) - dst.Set(s) - for i := 0; i < src.Len(); i++ { - rcopy(dst.Index(i), src.Index(i), false) - } - case reflect.Map: - if src.IsNil() { - break - } - - s := reflect.MakeMap(src.Type()) - dst.Set(s) - for _, k := range src.MapKeys() { - v := src.MapIndex(k) - v2 := reflect.New(v.Type()).Elem() - rcopy(v2, v, false) - dst.SetMapIndex(k, v2) - } - default: - // Assign the value if possible. If its not assignable, the value would - // need to be converted and the impact of that may be unexpected, or is - // not compatible with the dst type. - if src.Type().AssignableTo(dst.Type()) { - dst.Set(src) - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go deleted file mode 100644 index 59fa4a5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go +++ /dev/null @@ -1,27 +0,0 @@ -package awsutil - -import ( - "reflect" -) - -// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual. -// In addition to this, this method will also dereference the input values if -// possible so the DeepEqual performed will not fail if one parameter is a -// pointer and the other is not. -// -// DeepEqual will not perform indirection of nested values of the input parameters. -func DeepEqual(a, b interface{}) bool { - ra := reflect.Indirect(reflect.ValueOf(a)) - rb := reflect.Indirect(reflect.ValueOf(b)) - - if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid { - // If the elements are both nil, and of the same type the are equal - // If they are of different types they are not equal - return reflect.TypeOf(a) == reflect.TypeOf(b) - } else if raValid != rbValid { - // Both values must be valid to be equal - return false - } - - return reflect.DeepEqual(ra.Interface(), rb.Interface()) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go deleted file mode 100644 index 11c52c3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go +++ /dev/null @@ -1,222 +0,0 @@ -package awsutil - -import ( - "reflect" - "regexp" - "strconv" - "strings" - - "github.com/jmespath/go-jmespath" -) - -var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) - -// rValuesAtPath returns a slice of values found in value v. The values -// in v are explored recursively so all nested values are collected. -func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value { - pathparts := strings.Split(path, "||") - if len(pathparts) > 1 { - for _, pathpart := range pathparts { - vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm) - if len(vals) > 0 { - return vals - } - } - return nil - } - - values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} - components := strings.Split(path, ".") - for len(values) > 0 && len(components) > 0 { - var index *int64 - var indexStar bool - c := strings.TrimSpace(components[0]) - if c == "" { // no actual component, illegal syntax - return nil - } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] { - // TODO normalize case for user - return nil // don't support unexported fields - } - - // parse this component - if m := indexRe.FindStringSubmatch(c); m != nil { - c = m[1] - if m[2] == "" { - index = nil - indexStar = true - } else { - i, _ := strconv.ParseInt(m[2], 10, 32) - index = &i - indexStar = false - } - } - - nextvals := []reflect.Value{} - for _, value := range values { - // pull component name out of struct member - if value.Kind() != reflect.Struct { - continue - } - - if c == "*" { // pull all members - for i := 0; i < value.NumField(); i++ { - if f := reflect.Indirect(value.Field(i)); f.IsValid() { - nextvals = append(nextvals, f) - } - } - continue - } - - value = value.FieldByNameFunc(func(name string) bool { - if c == name { - return true - } else if !caseSensitive && strings.ToLower(name) == strings.ToLower(c) { - return true - } - return false - }) - - if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 { - if !value.IsNil() { - value.Set(reflect.Zero(value.Type())) - } - return []reflect.Value{value} - } - - if createPath && value.Kind() == reflect.Ptr && value.IsNil() { - // TODO if the value is the terminus it should not be created - // if the value to be set to its position is nil. - value.Set(reflect.New(value.Type().Elem())) - value = value.Elem() - } else { - value = reflect.Indirect(value) - } - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - - if indexStar || index != nil { - nextvals = []reflect.Value{} - for _, valItem := range values { - value := reflect.Indirect(valItem) - if value.Kind() != reflect.Slice { - continue - } - - if indexStar { // grab all indices - for i := 0; i < value.Len(); i++ { - idx := reflect.Indirect(value.Index(i)) - if idx.IsValid() { - nextvals = append(nextvals, idx) - } - } - continue - } - - // pull out index - i := int(*index) - if i >= value.Len() { // check out of bounds - if createPath { - // TODO resize slice - } else { - continue - } - } else if i < 0 { // support negative indexing - i = value.Len() + i - } - value = reflect.Indirect(value.Index(i)) - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - } - - components = components[1:] - } - return values -} - -// ValuesAtPath returns a list of values at the case insensitive lexical -// path inside of a structure. -func ValuesAtPath(i interface{}, path string) ([]interface{}, error) { - result, err := jmespath.Search(path, i) - if err != nil { - return nil, err - } - - v := reflect.ValueOf(result) - if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) { - return nil, nil - } - if s, ok := result.([]interface{}); ok { - return s, err - } - if v.Kind() == reflect.Map && v.Len() == 0 { - return nil, nil - } - if v.Kind() == reflect.Slice { - out := make([]interface{}, v.Len()) - for i := 0; i < v.Len(); i++ { - out[i] = v.Index(i).Interface() - } - return out, nil - } - - return []interface{}{result}, nil -} - -// SetValueAtPath sets a value at the case insensitive lexical path inside -// of a structure. -func SetValueAtPath(i interface{}, path string, v interface{}) { - if rvals := rValuesAtPath(i, path, true, false, v == nil); rvals != nil { - for _, rval := range rvals { - if rval.Kind() == reflect.Ptr && rval.IsNil() { - continue - } - setValue(rval, v) - } - } -} - -func setValue(dstVal reflect.Value, src interface{}) { - if dstVal.Kind() == reflect.Ptr { - dstVal = reflect.Indirect(dstVal) - } - srcVal := reflect.ValueOf(src) - - if !srcVal.IsValid() { // src is literal nil - if dstVal.CanAddr() { - // Convert to pointer so that pointer's value can be nil'ed - // dstVal = dstVal.Addr() - } - dstVal.Set(reflect.Zero(dstVal.Type())) - - } else if srcVal.Kind() == reflect.Ptr { - if srcVal.IsNil() { - srcVal = reflect.Zero(dstVal.Type()) - } else { - srcVal = reflect.ValueOf(src).Elem() - } - dstVal.Set(srcVal) - } else { - dstVal.Set(srcVal) - } - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go deleted file mode 100644 index 710eb43..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go +++ /dev/null @@ -1,113 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" -) - -// Prettify returns the string representation of a value. -func Prettify(i interface{}) string { - var buf bytes.Buffer - prettify(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -// prettify will recursively walk value v to build a textual -// representation of the value. -func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - strtype := v.Type().String() - if strtype == "time.Time" { - fmt.Fprintf(buf, "%s", v.Interface()) - break - } else if strings.HasPrefix(strtype, "io.") { - buf.WriteString("") - break - } - - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - prettify(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - strtype := v.Type().String() - if strtype == "[]uint8" { - fmt.Fprintf(buf, " len %d", v.Len()) - break - } - - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - prettify(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - prettify(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - if !v.IsValid() { - fmt.Fprint(buf, "") - return - } - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - case io.ReadSeeker, io.Reader: - format = "buffer(%p)" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go deleted file mode 100644 index b6432f1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go +++ /dev/null @@ -1,89 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "reflect" - "strings" -) - -// StringValue returns the string representation of a value. -func StringValue(i interface{}) string { - var buf bytes.Buffer - stringValue(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - stringValue(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - stringValue(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - stringValue(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/client.go deleted file mode 100644 index 212fe25..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ /dev/null @@ -1,96 +0,0 @@ -package client - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Config provides configuration to a service client instance. -type Config struct { - Config *aws.Config - Handlers request.Handlers - Endpoint string - SigningRegion string - SigningName string - - // States that the signing name did not come from a modeled source but - // was derived based on other data. Used by service client constructors - // to determine if the signin name can be overriden based on metadata the - // service has. - SigningNameDerived bool -} - -// ConfigProvider provides a generic way for a service client to receive -// the ClientConfig without circular dependencies. -type ConfigProvider interface { - ClientConfig(serviceName string, cfgs ...*aws.Config) Config -} - -// ConfigNoResolveEndpointProvider same as ConfigProvider except it will not -// resolve the endpoint automatically. The service client's endpoint must be -// provided via the aws.Config.Endpoint field. -type ConfigNoResolveEndpointProvider interface { - ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) Config -} - -// A Client implements the base client request and response handling -// used by all service clients. -type Client struct { - request.Retryer - metadata.ClientInfo - - Config aws.Config - Handlers request.Handlers -} - -// New will return a pointer to a new initialized service client. -func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client { - svc := &Client{ - Config: cfg, - ClientInfo: info, - Handlers: handlers.Copy(), - } - - switch retryer, ok := cfg.Retryer.(request.Retryer); { - case ok: - svc.Retryer = retryer - case cfg.Retryer != nil && cfg.Logger != nil: - s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer) - cfg.Logger.Log(s) - fallthrough - default: - maxRetries := aws.IntValue(cfg.MaxRetries) - if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { - maxRetries = 3 - } - svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries} - } - - svc.AddDebugHandlers() - - for _, option := range options { - option(svc) - } - - return svc -} - -// NewRequest returns a new Request pointer for the service API -// operation and parameters. -func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request { - return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data) -} - -// AddDebugHandlers injects debug logging handlers into the service to log request -// debug information. -func (c *Client) AddDebugHandlers() { - if !c.Config.LogLevel.AtLeast(aws.LogDebug) { - return - } - - c.Handlers.Send.PushFrontNamed(LogHTTPRequestHandler) - c.Handlers.Send.PushBackNamed(LogHTTPResponseHandler) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go deleted file mode 100644 index a397b0d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go +++ /dev/null @@ -1,116 +0,0 @@ -package client - -import ( - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkrand" -) - -// DefaultRetryer implements basic retry logic using exponential backoff for -// most services. If you want to implement custom retry logic, implement the -// request.Retryer interface or create a structure type that composes this -// struct and override the specific methods. For example, to override only -// the MaxRetries method: -// -// type retryer struct { -// client.DefaultRetryer -// } -// -// // This implementation always has 100 max retries -// func (d retryer) MaxRetries() int { return 100 } -type DefaultRetryer struct { - NumMaxRetries int -} - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API request. -func (d DefaultRetryer) MaxRetries() int { - return d.NumMaxRetries -} - -// RetryRules returns the delay duration before retrying this request again -func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { - // Set the upper limit of delay in retrying at ~five minutes - minTime := 30 - throttle := d.shouldThrottle(r) - if throttle { - if delay, ok := getRetryDelay(r); ok { - return delay - } - - minTime = 500 - } - - retryCount := r.RetryCount - if throttle && retryCount > 8 { - retryCount = 8 - } else if retryCount > 13 { - retryCount = 13 - } - - delay := (1 << uint(retryCount)) * (sdkrand.SeededRand.Intn(minTime) + minTime) - return time.Duration(delay) * time.Millisecond -} - -// ShouldRetry returns true if the request should be retried. -func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable != nil { - return *r.Retryable - } - - if r.HTTPResponse.StatusCode >= 500 && r.HTTPResponse.StatusCode != 501 { - return true - } - return r.IsErrorRetryable() || d.shouldThrottle(r) -} - -// ShouldThrottle returns true if the request should be throttled. -func (d DefaultRetryer) shouldThrottle(r *request.Request) bool { - switch r.HTTPResponse.StatusCode { - case 429: - case 502: - case 503: - case 504: - default: - return r.IsErrorThrottle() - } - - return true -} - -// This will look in the Retry-After header, RFC 7231, for how long -// it will wait before attempting another request -func getRetryDelay(r *request.Request) (time.Duration, bool) { - if !canUseRetryAfterHeader(r) { - return 0, false - } - - delayStr := r.HTTPResponse.Header.Get("Retry-After") - if len(delayStr) == 0 { - return 0, false - } - - delay, err := strconv.Atoi(delayStr) - if err != nil { - return 0, false - } - - return time.Duration(delay) * time.Second, true -} - -// Will look at the status code to see if the retry header pertains to -// the status code. -func canUseRetryAfterHeader(r *request.Request) bool { - switch r.HTTPResponse.StatusCode { - case 429: - case 503: - default: - return false - } - - return true -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go deleted file mode 100644 index ce9fb89..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go +++ /dev/null @@ -1,184 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http/httputil" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -const logReqMsg = `DEBUG: Request %s/%s Details: ----[ REQUEST POST-SIGN ]----------------------------- -%s ------------------------------------------------------` - -const logReqErrMsg = `DEBUG ERROR: Request %s/%s: ----[ REQUEST DUMP ERROR ]----------------------------- -%s -------------------------------------------------------` - -type logWriter struct { - // Logger is what we will use to log the payload of a response. - Logger aws.Logger - // buf stores the contents of what has been read - buf *bytes.Buffer -} - -func (logger *logWriter) Write(b []byte) (int, error) { - return logger.buf.Write(b) -} - -type teeReaderCloser struct { - // io.Reader will be a tee reader that is used during logging. - // This structure will read from a body and write the contents to a logger. - io.Reader - // Source is used just to close when we are done reading. - Source io.ReadCloser -} - -func (reader *teeReaderCloser) Close() error { - return reader.Source.Close() -} - -// LogHTTPRequestHandler is a SDK request handler to log the HTTP request sent -// to a service. Will include the HTTP request body if the LogLevel of the -// request matches LogDebugWithHTTPBody. -var LogHTTPRequestHandler = request.NamedHandler{ - Name: "awssdk.client.LogRequest", - Fn: logRequest, -} - -func logRequest(r *request.Request) { - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - bodySeekable := aws.IsReaderSeekable(r.Body) - - b, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - if logBody { - if !bodySeekable { - r.SetReaderBody(aws.ReadSeekCloser(r.HTTPRequest.Body)) - } - // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's - // Body as a NoOpCloser and will not be reset after read by the HTTP - // client reader. - r.ResetBody() - } - - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, - r.ClientInfo.ServiceName, r.Operation.Name, string(b))) -} - -// LogHTTPRequestHeaderHandler is a SDK request handler to log the HTTP request sent -// to a service. Will only log the HTTP request's headers. The request payload -// will not be read. -var LogHTTPRequestHeaderHandler = request.NamedHandler{ - Name: "awssdk.client.LogRequestHeader", - Fn: logRequestHeader, -} - -func logRequestHeader(r *request.Request) { - b, err := httputil.DumpRequestOut(r.HTTPRequest, false) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, - r.ClientInfo.ServiceName, r.Operation.Name, string(b))) -} - -const logRespMsg = `DEBUG: Response %s/%s Details: ----[ RESPONSE ]-------------------------------------- -%s ------------------------------------------------------` - -const logRespErrMsg = `DEBUG ERROR: Response %s/%s: ----[ RESPONSE DUMP ERROR ]----------------------------- -%s ------------------------------------------------------` - -// LogHTTPResponseHandler is a SDK request handler to log the HTTP response -// received from a service. Will include the HTTP response body if the LogLevel -// of the request matches LogDebugWithHTTPBody. -var LogHTTPResponseHandler = request.NamedHandler{ - Name: "awssdk.client.LogResponse", - Fn: logResponse, -} - -func logResponse(r *request.Request) { - lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} - - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - if logBody { - r.HTTPResponse.Body = &teeReaderCloser{ - Reader: io.TeeReader(r.HTTPResponse.Body, lw), - Source: r.HTTPResponse.Body, - } - } - - handlerFn := func(req *request.Request) { - b, err := httputil.DumpResponse(req.HTTPResponse, false) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, - req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - - lw.Logger.Log(fmt.Sprintf(logRespMsg, - req.ClientInfo.ServiceName, req.Operation.Name, string(b))) - - if logBody { - b, err := ioutil.ReadAll(lw.buf) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, - req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - - lw.Logger.Log(string(b)) - } - } - - const handlerName = "awsdk.client.LogResponse.ResponseBody" - - r.Handlers.Unmarshal.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) - r.Handlers.UnmarshalError.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) -} - -// LogHTTPResponseHeaderHandler is a SDK request handler to log the HTTP -// response received from a service. Will only log the HTTP response's headers. -// The response payload will not be read. -var LogHTTPResponseHeaderHandler = request.NamedHandler{ - Name: "awssdk.client.LogResponseHeader", - Fn: logResponseHeader, -} - -func logResponseHeader(r *request.Request) { - if r.Config.Logger == nil { - return - } - - b, err := httputil.DumpResponse(r.HTTPResponse, false) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - r.Config.Logger.Log(fmt.Sprintf(logRespMsg, - r.ClientInfo.ServiceName, r.Operation.Name, string(b))) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go deleted file mode 100644 index 920e9fd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go +++ /dev/null @@ -1,13 +0,0 @@ -package metadata - -// ClientInfo wraps immutable data from the client.Client structure. -type ClientInfo struct { - ServiceName string - ServiceID string - APIVersion string - Endpoint string - SigningName string - SigningRegion string - JSONVersion string - TargetPrefix string -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/config.go deleted file mode 100644 index 5421b5d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ /dev/null @@ -1,492 +0,0 @@ -package aws - -import ( - "net/http" - "time" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/endpoints" -) - -// UseServiceDefaultRetries instructs the config to use the service's own -// default number of retries. This will be the default action if -// Config.MaxRetries is nil also. -const UseServiceDefaultRetries = -1 - -// RequestRetryer is an alias for a type that implements the request.Retryer -// interface. -type RequestRetryer interface{} - -// A Config provides service configuration for service clients. By default, -// all clients will use the defaults.DefaultConfig tructure. -// -// // Create Session with MaxRetry configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(&aws.Config{ -// MaxRetries: aws.Int(3), -// })) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String("us-west-2"), -// }) -type Config struct { - // Enables verbose error printing of all credential chain errors. - // Should be used when wanting to see all errors while attempting to - // retrieve credentials. - CredentialsChainVerboseErrors *bool - - // The credentials object to use when signing requests. Defaults to a - // chain of credential providers to search for credentials in environment - // variables, shared credential file, and EC2 Instance Roles. - Credentials *credentials.Credentials - - // An optional endpoint URL (hostname only or fully qualified URI) - // that overrides the default generated endpoint for a client. Set this - // to `""` to use the default generated endpoint. - // - // @note You must still provide a `Region` value when specifying an - // endpoint for a client. - Endpoint *string - - // The resolver to use for looking up endpoints for AWS service clients - // to use based on region. - EndpointResolver endpoints.Resolver - - // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call - // ShouldRetry regardless of whether or not if request.Retryable is set. - // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck - // is not set, then ShouldRetry will only be called if request.Retryable is nil. - // Proper handling of the request.Retryable field is important when setting this field. - EnforceShouldRetryCheck *bool - - // The region to send requests to. This parameter is required and must - // be configured globally or on a per-client basis unless otherwise - // noted. A full list of regions is found in the "Regions and Endpoints" - // document. - // - // @see http://docs.aws.amazon.com/general/latest/gr/rande.html - // AWS Regions and Endpoints - Region *string - - // Set this to `true` to disable SSL when sending requests. Defaults - // to `false`. - DisableSSL *bool - - // The HTTP client to use when sending requests. Defaults to - // `http.DefaultClient`. - HTTPClient *http.Client - - // An integer value representing the logging level. The default log level - // is zero (LogOff), which represents no logging. To enable logging set - // to a LogLevel Value. - LogLevel *LogLevelType - - // The logger writer interface to write logging messages to. Defaults to - // standard out. - Logger Logger - - // The maximum number of times that a request will be retried for failures. - // Defaults to -1, which defers the max retry setting to the service - // specific configuration. - MaxRetries *int - - // Retryer guides how HTTP requests should be retried in case of - // recoverable failures. - // - // When nil or the value does not implement the request.Retryer interface, - // the client.DefaultRetryer will be used. - // - // When both Retryer and MaxRetries are non-nil, the former is used and - // the latter ignored. - // - // To set the Retryer field in a type-safe manner and with chaining, use - // the request.WithRetryer helper function: - // - // cfg := request.WithRetryer(aws.NewConfig(), myRetryer) - // - Retryer RequestRetryer - - // Disables semantic parameter validation, which validates input for - // missing required fields and/or other semantic request input errors. - DisableParamValidation *bool - - // Disables the computation of request and response checksums, e.g., - // CRC32 checksums in Amazon DynamoDB. - DisableComputeChecksums *bool - - // Set this to `true` to force the request to use path-style addressing, - // i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client - // will use virtual hosted bucket addressing when possible - // (`http://BUCKET.s3.amazonaws.com/KEY`). - // - // @note This configuration option is specific to the Amazon S3 service. - // @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html - // Amazon S3: Virtual Hosting of Buckets - S3ForcePathStyle *bool - - // Set this to `true` to disable the SDK adding the `Expect: 100-Continue` - // header to PUT requests over 2MB of content. 100-Continue instructs the - // HTTP client not to send the body until the service responds with a - // `continue` status. This is useful to prevent sending the request body - // until after the request is authenticated, and validated. - // - // http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html - // - // 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s - // `ExpectContinueTimeout` for information on adjusting the continue wait - // timeout. https://golang.org/pkg/net/http/#Transport - // - // You should use this flag to disble 100-Continue if you experience issues - // with proxies or third party S3 compatible services. - S3Disable100Continue *bool - - // Set this to `true` to enable S3 Accelerate feature. For all operations - // compatible with S3 Accelerate will use the accelerate endpoint for - // requests. Requests not compatible will fall back to normal S3 requests. - // - // The bucket must be enable for accelerate to be used with S3 client with - // accelerate enabled. If the bucket is not enabled for accelerate an error - // will be returned. The bucket name must be DNS compatible to also work - // with accelerate. - S3UseAccelerate *bool - - // S3DisableContentMD5Validation config option is temporarily disabled, - // For S3 GetObject API calls, #1837. - // - // Set this to `true` to disable the S3 service client from automatically - // adding the ContentMD5 to S3 Object Put and Upload API calls. This option - // will also disable the SDK from performing object ContentMD5 validation - // on GetObject API calls. - S3DisableContentMD5Validation *bool - - // Set this to `true` to disable the EC2Metadata client from overriding the - // default http.Client's Timeout. This is helpful if you do not want the - // EC2Metadata client to create a new http.Client. This options is only - // meaningful if you're not already using a custom HTTP client with the - // SDK. Enabled by default. - // - // Must be set and provided to the session.NewSession() in order to disable - // the EC2Metadata overriding the timeout for default credentials chain. - // - // Example: - // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataDiableTimeoutOverride(true))) - // - // svc := s3.New(sess) - // - EC2MetadataDisableTimeoutOverride *bool - - // Instructs the endpoint to be generated for a service client to - // be the dual stack endpoint. The dual stack endpoint will support - // both IPv4 and IPv6 addressing. - // - // Setting this for a service which does not support dual stack will fail - // to make requets. It is not recommended to set this value on the session - // as it will apply to all service clients created with the session. Even - // services which don't support dual stack endpoints. - // - // If the Endpoint config value is also provided the UseDualStack flag - // will be ignored. - // - // Only supported with. - // - // sess := session.Must(session.NewSession()) - // - // svc := s3.New(sess, &aws.Config{ - // UseDualStack: aws.Bool(true), - // }) - UseDualStack *bool - - // SleepDelay is an override for the func the SDK will call when sleeping - // during the lifecycle of a request. Specifically this will be used for - // request delays. This value should only be used for testing. To adjust - // the delay of a request see the aws/client.DefaultRetryer and - // aws/request.Retryer. - // - // SleepDelay will prevent any Context from being used for canceling retry - // delay of an API operation. It is recommended to not use SleepDelay at all - // and specify a Retryer instead. - SleepDelay func(time.Duration) - - // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. - // Will default to false. This would only be used for empty directory names in s3 requests. - // - // Example: - // sess := session.Must(session.NewSession(&aws.Config{ - // DisableRestProtocolURICleaning: aws.Bool(true), - // })) - // - // svc := s3.New(sess) - // out, err := svc.GetObject(&s3.GetObjectInput { - // Bucket: aws.String("bucketname"), - // Key: aws.String("//foo//bar//moo"), - // }) - DisableRestProtocolURICleaning *bool -} - -// NewConfig returns a new Config pointer that can be chained with builder -// methods to set multiple configuration values inline without using pointers. -// -// // Create Session with MaxRetry configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(aws.NewConfig(). -// WithMaxRetries(3), -// )) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, aws.NewConfig(). -// WithRegion("us-west-2"), -// ) -func NewConfig() *Config { - return &Config{} -} - -// WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning -// a Config pointer. -func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config { - c.CredentialsChainVerboseErrors = &verboseErrs - return c -} - -// WithCredentials sets a config Credentials value returning a Config pointer -// for chaining. -func (c *Config) WithCredentials(creds *credentials.Credentials) *Config { - c.Credentials = creds - return c -} - -// WithEndpoint sets a config Endpoint value returning a Config pointer for -// chaining. -func (c *Config) WithEndpoint(endpoint string) *Config { - c.Endpoint = &endpoint - return c -} - -// WithEndpointResolver sets a config EndpointResolver value returning a -// Config pointer for chaining. -func (c *Config) WithEndpointResolver(resolver endpoints.Resolver) *Config { - c.EndpointResolver = resolver - return c -} - -// WithRegion sets a config Region value returning a Config pointer for -// chaining. -func (c *Config) WithRegion(region string) *Config { - c.Region = ®ion - return c -} - -// WithDisableSSL sets a config DisableSSL value returning a Config pointer -// for chaining. -func (c *Config) WithDisableSSL(disable bool) *Config { - c.DisableSSL = &disable - return c -} - -// WithHTTPClient sets a config HTTPClient value returning a Config pointer -// for chaining. -func (c *Config) WithHTTPClient(client *http.Client) *Config { - c.HTTPClient = client - return c -} - -// WithMaxRetries sets a config MaxRetries value returning a Config pointer -// for chaining. -func (c *Config) WithMaxRetries(max int) *Config { - c.MaxRetries = &max - return c -} - -// WithDisableParamValidation sets a config DisableParamValidation value -// returning a Config pointer for chaining. -func (c *Config) WithDisableParamValidation(disable bool) *Config { - c.DisableParamValidation = &disable - return c -} - -// WithDisableComputeChecksums sets a config DisableComputeChecksums value -// returning a Config pointer for chaining. -func (c *Config) WithDisableComputeChecksums(disable bool) *Config { - c.DisableComputeChecksums = &disable - return c -} - -// WithLogLevel sets a config LogLevel value returning a Config pointer for -// chaining. -func (c *Config) WithLogLevel(level LogLevelType) *Config { - c.LogLevel = &level - return c -} - -// WithLogger sets a config Logger value returning a Config pointer for -// chaining. -func (c *Config) WithLogger(logger Logger) *Config { - c.Logger = logger - return c -} - -// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config -// pointer for chaining. -func (c *Config) WithS3ForcePathStyle(force bool) *Config { - c.S3ForcePathStyle = &force - return c -} - -// WithS3Disable100Continue sets a config S3Disable100Continue value returning -// a Config pointer for chaining. -func (c *Config) WithS3Disable100Continue(disable bool) *Config { - c.S3Disable100Continue = &disable - return c -} - -// WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config -// pointer for chaining. -func (c *Config) WithS3UseAccelerate(enable bool) *Config { - c.S3UseAccelerate = &enable - return c - -} - -// WithS3DisableContentMD5Validation sets a config -// S3DisableContentMD5Validation value returning a Config pointer for chaining. -func (c *Config) WithS3DisableContentMD5Validation(enable bool) *Config { - c.S3DisableContentMD5Validation = &enable - return c - -} - -// WithUseDualStack sets a config UseDualStack value returning a Config -// pointer for chaining. -func (c *Config) WithUseDualStack(enable bool) *Config { - c.UseDualStack = &enable - return c -} - -// WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value -// returning a Config pointer for chaining. -func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config { - c.EC2MetadataDisableTimeoutOverride = &enable - return c -} - -// WithSleepDelay overrides the function used to sleep while waiting for the -// next retry. Defaults to time.Sleep. -func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { - c.SleepDelay = fn - return c -} - -// MergeIn merges the passed in configs into the existing config object. -func (c *Config) MergeIn(cfgs ...*Config) { - for _, other := range cfgs { - mergeInConfig(c, other) - } -} - -func mergeInConfig(dst *Config, other *Config) { - if other == nil { - return - } - - if other.CredentialsChainVerboseErrors != nil { - dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors - } - - if other.Credentials != nil { - dst.Credentials = other.Credentials - } - - if other.Endpoint != nil { - dst.Endpoint = other.Endpoint - } - - if other.EndpointResolver != nil { - dst.EndpointResolver = other.EndpointResolver - } - - if other.Region != nil { - dst.Region = other.Region - } - - if other.DisableSSL != nil { - dst.DisableSSL = other.DisableSSL - } - - if other.HTTPClient != nil { - dst.HTTPClient = other.HTTPClient - } - - if other.LogLevel != nil { - dst.LogLevel = other.LogLevel - } - - if other.Logger != nil { - dst.Logger = other.Logger - } - - if other.MaxRetries != nil { - dst.MaxRetries = other.MaxRetries - } - - if other.Retryer != nil { - dst.Retryer = other.Retryer - } - - if other.DisableParamValidation != nil { - dst.DisableParamValidation = other.DisableParamValidation - } - - if other.DisableComputeChecksums != nil { - dst.DisableComputeChecksums = other.DisableComputeChecksums - } - - if other.S3ForcePathStyle != nil { - dst.S3ForcePathStyle = other.S3ForcePathStyle - } - - if other.S3Disable100Continue != nil { - dst.S3Disable100Continue = other.S3Disable100Continue - } - - if other.S3UseAccelerate != nil { - dst.S3UseAccelerate = other.S3UseAccelerate - } - - if other.S3DisableContentMD5Validation != nil { - dst.S3DisableContentMD5Validation = other.S3DisableContentMD5Validation - } - - if other.UseDualStack != nil { - dst.UseDualStack = other.UseDualStack - } - - if other.EC2MetadataDisableTimeoutOverride != nil { - dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride - } - - if other.SleepDelay != nil { - dst.SleepDelay = other.SleepDelay - } - - if other.DisableRestProtocolURICleaning != nil { - dst.DisableRestProtocolURICleaning = other.DisableRestProtocolURICleaning - } - - if other.EnforceShouldRetryCheck != nil { - dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck - } -} - -// Copy will return a shallow copy of the Config object. If any additional -// configurations are provided they will be merged into the new config returned. -func (c *Config) Copy(cfgs ...*Config) *Config { - dst := &Config{} - dst.MergeIn(c) - - for _, cfg := range cfgs { - dst.MergeIn(cfg) - } - - return dst -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context.go deleted file mode 100644 index 79f4268..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context.go +++ /dev/null @@ -1,71 +0,0 @@ -package aws - -import ( - "time" -) - -// Context is an copy of the Go v1.7 stdlib's context.Context interface. -// It is represented as a SDK interface to enable you to use the "WithContext" -// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. -// -// See https://golang.org/pkg/context on how to use contexts. -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. - 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. - Value(key interface{}) interface{} -} - -// BackgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func BackgroundContext() Context { - return backgroundCtx -} - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// Expects Context to always return a non-nil error if the Done channel is closed. -func SleepWithContext(ctx Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go deleted file mode 100644 index 8fdda53..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !go1.7 - -package aws - -import "time" - -// An emptyCtx is a copy of the Go 1.7 context.emptyCtx type. This is copied to -// provide a 1.6 and 1.5 safe version of context that is compatible with Go -// 1.7's Context. -// -// 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 backgroundCtx: - return "aws.BackgroundContext" - } - return "unknown empty Context" -} - -var ( - backgroundCtx = new(emptyCtx) -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go deleted file mode 100644 index 064f75c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.7 - -package aws - -import "context" - -var ( - backgroundCtx = context.Background() -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go deleted file mode 100644 index ff5d58e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go +++ /dev/null @@ -1,387 +0,0 @@ -package aws - -import "time" - -// String returns a pointer to the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float64 returns a pointer to the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// SecondsTimeValue converts an int64 pointer to a time.Time value -// representing seconds since Epoch or time.Time{} if the pointer is nil. -func SecondsTimeValue(v *int64) time.Time { - if v != nil { - return time.Unix((*v / 1000), 0) - } - return time.Time{} -} - -// MillisecondsTimeValue converts an int64 pointer to a time.Time value -// representing milliseconds sinch Epoch or time.Time{} if the pointer is nil. -func MillisecondsTimeValue(v *int64) time.Time { - if v != nil { - return time.Unix(0, (*v * 1000000)) - } - return time.Time{} -} - -// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". -// The result is undefined if the Unix time cannot be represented by an int64. -// Which includes calling TimeUnixMilli on a zero Time is undefined. -// -// This utility is useful for service API's such as CloudWatch Logs which require -// their unix time values to be in milliseconds. -// -// See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information. -func TimeUnixMilli(t time.Time) int64 { - return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go deleted file mode 100644 index cfcddf3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ /dev/null @@ -1,228 +0,0 @@ -package corehandlers - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// Interface for matching types which also have a Len method. -type lener interface { - Len() int -} - -// BuildContentLengthHandler builds the content length of a request based on the body, -// or will use the HTTPRequest.Header's "Content-Length" if defined. If unable -// to determine request body length and no "Content-Length" was specified it will panic. -// -// The Content-Length will only be added to the request if the length of the body -// is greater than 0. If the body is empty or the current `Content-Length` -// header is <= 0, the header will also be stripped. -var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) { - var length int64 - - if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { - length, _ = strconv.ParseInt(slength, 10, 64) - } else { - if r.Body != nil { - var err error - length, err = aws.SeekerLen(r.Body) - if err != nil { - r.Error = awserr.New(request.ErrCodeSerialization, "failed to get request body's length", err) - return - } - } - } - - if length > 0 { - r.HTTPRequest.ContentLength = length - r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) - } else { - r.HTTPRequest.ContentLength = 0 - r.HTTPRequest.Header.Del("Content-Length") - } -}} - -var reStatusCode = regexp.MustCompile(`^(\d{3})`) - -// ValidateReqSigHandler is a request handler to ensure that the request's -// signature doesn't expire before it is sent. This can happen when a request -// is built and signed significantly before it is sent. Or significant delays -// occur when retrying requests that would cause the signature to expire. -var ValidateReqSigHandler = request.NamedHandler{ - Name: "core.ValidateReqSigHandler", - Fn: func(r *request.Request) { - // Unsigned requests are not signed - if r.Config.Credentials == credentials.AnonymousCredentials { - return - } - - signedTime := r.Time - if !r.LastSignedAt.IsZero() { - signedTime = r.LastSignedAt - } - - // 10 minutes to allow for some clock skew/delays in transmission. - // Would be improved with aws/aws-sdk-go#423 - if signedTime.Add(10 * time.Minute).After(time.Now()) { - return - } - - fmt.Println("request expired, resigning") - r.Sign() - }, -} - -// SendHandler is a request handler to send service request using HTTP client. -var SendHandler = request.NamedHandler{ - Name: "core.SendHandler", - Fn: func(r *request.Request) { - sender := sendFollowRedirects - if r.DisableFollowRedirects { - sender = sendWithoutFollowRedirects - } - - if request.NoBody == r.HTTPRequest.Body { - // Strip off the request body if the NoBody reader was used as a - // place holder for a request body. This prevents the SDK from - // making requests with a request body when it would be invalid - // to do so. - // - // Use a shallow copy of the http.Request to ensure the race condition - // of transport on Body will not trigger - reqOrig, reqCopy := r.HTTPRequest, *r.HTTPRequest - reqCopy.Body = nil - r.HTTPRequest = &reqCopy - defer func() { - r.HTTPRequest = reqOrig - }() - } - - var err error - r.HTTPResponse, err = sender(r) - if err != nil { - handleSendError(r, err) - } - }, -} - -func sendFollowRedirects(r *request.Request) (*http.Response, error) { - return r.Config.HTTPClient.Do(r.HTTPRequest) -} - -func sendWithoutFollowRedirects(r *request.Request) (*http.Response, error) { - transport := r.Config.HTTPClient.Transport - if transport == nil { - transport = http.DefaultTransport - } - - return transport.RoundTrip(r.HTTPRequest) -} - -func handleSendError(r *request.Request, err error) { - // Prevent leaking if an HTTPResponse was returned. Clean up - // the body. - if r.HTTPResponse != nil { - r.HTTPResponse.Body.Close() - } - // Capture the case where url.Error is returned for error processing - // response. e.g. 301 without location header comes back as string - // error and r.HTTPResponse is nil. Other URL redirect errors will - // comeback in a similar method. - if e, ok := err.(*url.Error); ok && e.Err != nil { - if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { - code, _ := strconv.ParseInt(s[1], 10, 64) - r.HTTPResponse = &http.Response{ - StatusCode: int(code), - Status: http.StatusText(int(code)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - return - } - } - if r.HTTPResponse == nil { - // Add a dummy request response object to ensure the HTTPResponse - // value is consistent. - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - } - // Catch all other request errors. - r.Error = awserr.New("RequestError", "send request failed", err) - r.Retryable = aws.Bool(true) // network errors are retryable - - // Override the error with a context canceled error, if that was canceled. - ctx := r.Context() - select { - case <-ctx.Done(): - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", ctx.Err()) - r.Retryable = aws.Bool(false) - default: - } -} - -// ValidateResponseHandler is a request handler to validate service response. -var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) { - if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { - // this may be replaced by an UnmarshalError handler - r.Error = awserr.New("UnknownError", "unknown error", nil) - } -}} - -// AfterRetryHandler performs final checks to determine if the request should -// be retried and how long to delay. -var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: func(r *request.Request) { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable == nil || aws.BoolValue(r.Config.EnforceShouldRetryCheck) { - r.Retryable = aws.Bool(r.ShouldRetry(r)) - } - - if r.WillRetry() { - r.RetryDelay = r.RetryRules(r) - - if sleepFn := r.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(r.RetryDelay) - } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", err) - r.Retryable = aws.Bool(false) - return - } - - // when the expired token exception occurs the credentials - // need to be expired locally so that the next request to - // get credentials will trigger a credentials refresh. - if r.IsErrorExpired() { - r.Config.Credentials.Expire() - } - - r.RetryCount++ - r.Error = nil - } -}} - -// ValidateEndpointHandler is a request handler to validate a request had the -// appropriate Region and Endpoint set. Will set r.Error if the endpoint or -// region is not valid. -var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointHandler", Fn: func(r *request.Request) { - if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { - r.Error = aws.ErrMissingRegion - } else if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -}} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go deleted file mode 100644 index 7d50b15..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go +++ /dev/null @@ -1,17 +0,0 @@ -package corehandlers - -import "github.com/aws/aws-sdk-go/aws/request" - -// ValidateParametersHandler is a request handler to validate the input parameters. -// Validating parameters only has meaning if done prior to the request being sent. -var ValidateParametersHandler = request.NamedHandler{Name: "core.ValidateParametersHandler", Fn: func(r *request.Request) { - if !r.ParamsFilled() { - return - } - - if v, ok := r.Params.(request.Validator); ok { - if err := v.Validate(); err != nil { - r.Error = err - } - } -}} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go deleted file mode 100644 index a15f496..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go +++ /dev/null @@ -1,37 +0,0 @@ -package corehandlers - -import ( - "os" - "runtime" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// SDKVersionUserAgentHandler is a request handler for adding the SDK Version -// to the user agent. -var SDKVersionUserAgentHandler = request.NamedHandler{ - Name: "core.SDKVersionUserAgentHandler", - Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, - runtime.Version(), runtime.GOOS, runtime.GOARCH), -} - -const execEnvVar = `AWS_EXECUTION_ENV` -const execEnvUAKey = `exec_env` - -// AddHostExecEnvUserAgentHander is a request handler appending the SDK's -// execution environment to the user agent. -// -// If the environment variable AWS_EXECUTION_ENV is set, its value will be -// appended to the user agent string. -var AddHostExecEnvUserAgentHander = request.NamedHandler{ - Name: "core.AddHostExecEnvUserAgentHander", - Fn: func(r *request.Request) { - v := os.Getenv(execEnvVar) - if len(v) == 0 { - return - } - - request.AddToUserAgent(r, execEnvUAKey+"/"+v) - }, -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go deleted file mode 100644 index f298d65..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ /dev/null @@ -1,102 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var ( - // ErrNoValidProvidersFoundInChain Is returned when there are no valid - // providers in the ChainProvider. - // - // This has been deprecated. For verbose error messaging set - // aws.Config.CredentialsChainVerboseErrors to true - // - // @readonly - ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", - `no valid providers in chain. Deprecated. - For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, - nil) -) - -// A ChainProvider will search for a provider which returns credentials -// and cache that provider until Retrieve is called again. -// -// The ChainProvider provides a way of chaining multiple providers together -// which will pick the first available using priority order of the Providers -// in the list. -// -// If none of the Providers retrieve valid credentials Value, ChainProvider's -// Retrieve() will return the error ErrNoValidProvidersFoundInChain. -// -// If a Provider is found which returns valid credentials Value ChainProvider -// will cache that Provider for all calls to IsExpired(), until Retrieve is -// called again. -// -// Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider. -// In this example EnvProvider will first check if any credentials are available -// via the environment variables. If there are none ChainProvider will check -// the next Provider in the list, EC2RoleProvider in this case. If EC2RoleProvider -// does not return any credentials ChainProvider will return the error -// ErrNoValidProvidersFoundInChain -// -// creds := credentials.NewChainCredentials( -// []credentials.Provider{ -// &credentials.EnvProvider{}, -// &ec2rolecreds.EC2RoleProvider{ -// Client: ec2metadata.New(sess), -// }, -// }) -// -// // Usage of ChainCredentials with aws.Config -// svc := ec2.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: creds, -// }))) -// -type ChainProvider struct { - Providers []Provider - curr Provider - VerboseErrors bool -} - -// NewChainCredentials returns a pointer to a new Credentials object -// wrapping a chain of providers. -func NewChainCredentials(providers []Provider) *Credentials { - return NewCredentials(&ChainProvider{ - Providers: append([]Provider{}, providers...), - }) -} - -// Retrieve returns the credentials value or error if no provider returned -// without error. -// -// If a provider is found it will be cached and any calls to IsExpired() -// will return the expired state of the cached provider. -func (c *ChainProvider) Retrieve() (Value, error) { - var errs []error - for _, p := range c.Providers { - creds, err := p.Retrieve() - if err == nil { - c.curr = p - return creds, nil - } - errs = append(errs, err) - } - c.curr = nil - - var err error - err = ErrNoValidProvidersFoundInChain - if c.VerboseErrors { - err = awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) - } - return Value{}, err -} - -// IsExpired will returned the expired state of the currently cached provider -// if there is one. If there is no current provider, true will be returned. -func (c *ChainProvider) IsExpired() bool { - if c.curr != nil { - return c.curr.IsExpired() - } - - return true -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go deleted file mode 100644 index a270844..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ /dev/null @@ -1,259 +0,0 @@ -// Package credentials provides credential retrieval and management -// -// The Credentials is the primary method of getting access to and managing -// credentials Values. Using dependency injection retrieval of the credential -// values is handled by a object which satisfies the Provider interface. -// -// By default the Credentials.Get() will cache the successful result of a -// Provider's Retrieve() until Provider.IsExpired() returns true. At which -// point Credentials will call Provider's Retrieve() to get new credential Value. -// -// The Provider is responsible for determining when credentials Value have expired. -// It is also important to note that Credentials will always call Retrieve the -// first time Credentials.Get() is called. -// -// Example of using the environment variable credentials. -// -// creds := credentials.NewEnvCredentials() -// -// // Retrieve the credentials value -// credValue, err := creds.Get() -// if err != nil { -// // handle error -// } -// -// Example of forcing credentials to expire and be refreshed on the next Get(). -// This may be helpful to proactively expire credentials and refresh them sooner -// than they would naturally expire on their own. -// -// creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{}) -// creds.Expire() -// credsValue, err := creds.Get() -// // New credentials will be retrieved instead of from cache. -// -// -// Custom Provider -// -// Each Provider built into this package also provides a helper method to generate -// a Credentials pointer setup with the provider. To use a custom Provider just -// create a type which satisfies the Provider interface and pass it to the -// NewCredentials method. -// -// type MyProvider struct{} -// func (m *MyProvider) Retrieve() (Value, error) {...} -// func (m *MyProvider) IsExpired() bool {...} -// -// creds := credentials.NewCredentials(&MyProvider{}) -// credValue, err := creds.Get() -// -package credentials - -import ( - "sync" - "time" -) - -// AnonymousCredentials is an empty Credential object that can be used as -// dummy placeholder credentials for requests that do not need signed. -// -// This Credentials can be used to configure a service to not sign requests -// when making service API calls. For example, when accessing public -// s3 buckets. -// -// svc := s3.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: credentials.AnonymousCredentials, -// }))) -// // Access public S3 buckets. -// -// @readonly -var AnonymousCredentials = NewStaticCredentials("", "", "") - -// A Value is the AWS credentials value for individual credential fields. -type Value struct { - // AWS Access key ID - AccessKeyID string - - // AWS Secret Access Key - SecretAccessKey string - - // AWS Session Token - SessionToken string - - // Provider used to get credentials - ProviderName string -} - -// A Provider is the interface for any component which will provide credentials -// Value. A provider is required to manage its own Expired state, and what to -// be expired means. -// -// The Provider should not need to implement its own mutexes, because -// that will be managed by Credentials. -type Provider interface { - // Retrieve returns nil if it successfully retrieved the value. - // Error is returned if the value were not obtainable, or empty. - Retrieve() (Value, error) - - // IsExpired returns if the credentials are no longer valid, and need - // to be retrieved. - IsExpired() bool -} - -// An ErrorProvider is a stub credentials provider that always returns an error -// this is used by the SDK when construction a known provider is not possible -// due to an error. -type ErrorProvider struct { - // The error to be returned from Retrieve - Err error - - // The provider name to set on the Retrieved returned Value - ProviderName string -} - -// Retrieve will always return the error that the ErrorProvider was created with. -func (p ErrorProvider) Retrieve() (Value, error) { - return Value{ProviderName: p.ProviderName}, p.Err -} - -// IsExpired will always return not expired. -func (p ErrorProvider) IsExpired() bool { - return false -} - -// A Expiry provides shared expiration logic to be used by credentials -// providers to implement expiry functionality. -// -// The best method to use this struct is as an anonymous field within the -// provider's struct. -// -// Example: -// type EC2RoleProvider struct { -// Expiry -// ... -// } -type Expiry struct { - // The date/time when to expire on - expiration time.Time - - // If set will be used by IsExpired to determine the current time. - // Defaults to time.Now if CurrentTime is not set. Available for testing - // to be able to mock out the current time. - CurrentTime func() time.Time -} - -// SetExpiration sets the expiration IsExpired will check when called. -// -// If window is greater than 0 the expiration time will be reduced by the -// window value. -// -// Using a window is helpful to trigger credentials to expire sooner than -// the expiration time given to ensure no requests are made with expired -// tokens. -func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { - e.expiration = expiration - if window > 0 { - e.expiration = e.expiration.Add(-window) - } -} - -// IsExpired returns if the credentials are expired. -func (e *Expiry) IsExpired() bool { - curTime := e.CurrentTime - if curTime == nil { - curTime = time.Now - } - return e.expiration.Before(curTime()) -} - -// A Credentials provides concurrency safe retrieval of AWS credentials Value. -// Credentials will cache the credentials value until they expire. Once the value -// expires the next Get will attempt to retrieve valid credentials. -// -// Credentials is safe to use across multiple goroutines and will manage the -// synchronous state so the Providers do not need to implement their own -// synchronization. -// -// The first Credentials.Get() will always call Provider.Retrieve() to get the -// first instance of the credentials Value. All calls to Get() after that -// will return the cached credentials Value until IsExpired() returns true. -type Credentials struct { - creds Value - forceRefresh bool - - m sync.RWMutex - - provider Provider -} - -// NewCredentials returns a pointer to a new Credentials with the provider set. -func NewCredentials(provider Provider) *Credentials { - return &Credentials{ - provider: provider, - forceRefresh: true, - } -} - -// Get returns the credentials value, or error if the credentials Value failed -// to be retrieved. -// -// Will return the cached credentials Value if it has not expired. If the -// credentials Value has expired the Provider's Retrieve() will be called -// to refresh the credentials. -// -// If Credentials.Expire() was called the credentials Value will be force -// expired, and the next call to Get() will cause them to be refreshed. -func (c *Credentials) Get() (Value, error) { - // Check the cached credentials first with just the read lock. - c.m.RLock() - if !c.isExpired() { - creds := c.creds - c.m.RUnlock() - return creds, nil - } - c.m.RUnlock() - - // Credentials are expired need to retrieve the credentials taking the full - // lock. - c.m.Lock() - defer c.m.Unlock() - - if c.isExpired() { - creds, err := c.provider.Retrieve() - if err != nil { - return Value{}, err - } - c.creds = creds - c.forceRefresh = false - } - - return c.creds, nil -} - -// Expire expires the credentials and forces them to be retrieved on the -// next call to Get(). -// -// This will override the Provider's expired state, and force Credentials -// to call the Provider's Retrieve(). -func (c *Credentials) Expire() { - c.m.Lock() - defer c.m.Unlock() - - c.forceRefresh = true -} - -// IsExpired returns if the credentials are no longer valid, and need -// to be retrieved. -// -// If the Credentials were forced to be expired with Expire() this will -// reflect that override. -func (c *Credentials) IsExpired() bool { - c.m.RLock() - defer c.m.RUnlock() - - return c.isExpired() -} - -// isExpired helper method wrapping the definition of expired credentials. -func (c *Credentials) isExpired() bool { - return c.forceRefresh || c.provider.IsExpired() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go deleted file mode 100644 index 0ed791b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go +++ /dev/null @@ -1,178 +0,0 @@ -package ec2rolecreds - -import ( - "bufio" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/internal/sdkuri" -) - -// ProviderName provides a name of EC2Role provider -const ProviderName = "EC2RoleProvider" - -// A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if -// those credentials are expired. -// -// Example how to configure the EC2RoleProvider with custom http Client, Endpoint -// or ExpiryWindow -// -// p := &ec2rolecreds.EC2RoleProvider{ -// // Pass in a custom timeout to be used when requesting -// // IAM EC2 Role credentials. -// Client: ec2metadata.New(sess, aws.Config{ -// HTTPClient: &http.Client{Timeout: 10 * time.Second}, -// }), -// -// // Do not use early expiry of credentials. If a non zero value is -// // specified the credentials will be expired early -// ExpiryWindow: 0, -// } -type EC2RoleProvider struct { - credentials.Expiry - - // Required EC2Metadata client to use when connecting to EC2 metadata service. - Client *ec2metadata.EC2Metadata - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a ConfigProvider to create a EC2Metadata client. -// The ConfigProvider is satisfied by the session.Session type. -func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: ec2metadata.New(c), - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2 -// metadata service. -func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: client, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve retrieves credentials from the EC2 service. -// Error will be returned if the request fails, or unable to extract -// the desired credentials. -func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) { - credsList, err := requestCredList(m.Client) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - if len(credsList) == 0 { - return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) - } - credsName := credsList[0] - - roleCreds, err := requestCred(m.Client, credsName) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: roleCreds.AccessKeyID, - SecretAccessKey: roleCreds.SecretAccessKey, - SessionToken: roleCreds.Token, - ProviderName: ProviderName, - }, nil -} - -// A ec2RoleCredRespBody provides the shape for unmarshaling credential -// request responses. -type ec2RoleCredRespBody struct { - // Success State - Expiration time.Time - AccessKeyID string - SecretAccessKey string - Token string - - // Error state - Code string - Message string -} - -const iamSecurityCredsPath = "iam/security-credentials/" - -// requestCredList requests a list of credentials from the EC2 service. -// If there are no credentials, or there is an error making or receiving the request -func requestCredList(client *ec2metadata.EC2Metadata) ([]string, error) { - resp, err := client.GetMetadata(iamSecurityCredsPath) - if err != nil { - return nil, awserr.New("EC2RoleRequestError", "no EC2 instance role found", err) - } - - credsList := []string{} - s := bufio.NewScanner(strings.NewReader(resp)) - for s.Scan() { - credsList = append(credsList, s.Text()) - } - - if err := s.Err(); err != nil { - return nil, awserr.New("SerializationError", "failed to read EC2 instance role from metadata service", err) - } - - return credsList, nil -} - -// requestCred requests the credentials for a specific credentials from the EC2 service. -// -// If the credentials cannot be found, or there is an error reading the response -// and error will be returned. -func requestCred(client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadata(sdkuri.PathJoin(iamSecurityCredsPath, credsName)) - if err != nil { - return ec2RoleCredRespBody{}, - awserr.New("EC2RoleRequestError", - fmt.Sprintf("failed to get %s EC2 instance role credentials", credsName), - err) - } - - respCreds := ec2RoleCredRespBody{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil { - return ec2RoleCredRespBody{}, - awserr.New("SerializationError", - fmt.Sprintf("failed to decode %s EC2 instance role credentials", credsName), - err) - } - - if respCreds.Code != "Success" { - // If an error code was returned something failed requesting the role. - return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil) - } - - return respCreds, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go deleted file mode 100644 index a4cec5c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go +++ /dev/null @@ -1,191 +0,0 @@ -// Package endpointcreds provides support for retrieving credentials from an -// arbitrary HTTP endpoint. -// -// The credentials endpoint Provider can receive both static and refreshable -// credentials that will expire. Credentials are static when an "Expiration" -// value is not provided in the endpoint's response. -// -// Static credentials will never expire once they have been retrieved. The format -// of the static credentials response: -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// } -// -// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration -// value in the response. The format of the refreshable credentials response: -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// "Token" : "AQoDY....=", -// "Expiration" : "2016-02-25T06:03:31Z" -// } -// -// Errors should be returned in the following format and only returned with 400 -// or 500 HTTP status codes. -// { -// "code": "ErrorCode", -// "message": "Helpful error message." -// } -package endpointcreds - -import ( - "encoding/json" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// ProviderName is the name of the credentials provider. -const ProviderName = `CredentialsEndpointProvider` - -// Provider satisfies the credentials.Provider interface, and is a client to -// retrieve credentials from an arbitrary endpoint. -type Provider struct { - staticCreds bool - credentials.Expiry - - // Requires a AWS Client to make HTTP requests to the endpoint with. - // the Endpoint the request will be made to is provided by the aws.Config's - // Endpoint value. - Client *client.Client - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewProviderClient returns a credentials Provider for retrieving AWS credentials -// from arbitrary endpoint. -func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider { - p := &Provider{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "CredentialsEndpoint", - Endpoint: endpoint, - }, - handlers, - ), - } - - p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler) - p.Client.Handlers.UnmarshalError.PushBack(unmarshalError) - p.Client.Handlers.Validate.Clear() - p.Client.Handlers.Validate.PushBack(validateEndpointHandler) - - for _, option := range options { - option(p) - } - - return p -} - -// NewCredentialsClient returns a Credentials wrapper for retrieving credentials -// from an arbitrary endpoint concurrently. The client will request the -func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials { - return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...)) -} - -// IsExpired returns true if the credentials retrieved are expired, or not yet -// retrieved. -func (p *Provider) IsExpired() bool { - if p.staticCreds { - return false - } - return p.Expiry.IsExpired() -} - -// Retrieve will attempt to request the credentials from the endpoint the Provider -// was configured for. And error will be returned if the retrieval fails. -func (p *Provider) Retrieve() (credentials.Value, error) { - resp, err := p.getCredentials() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("CredentialsEndpointError", "failed to load credentials", err) - } - - if resp.Expiration != nil { - p.SetExpiration(*resp.Expiration, p.ExpiryWindow) - } else { - p.staticCreds = true - } - - return credentials.Value{ - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.Token, - ProviderName: ProviderName, - }, nil -} - -type getCredentialsOutput struct { - Expiration *time.Time - AccessKeyID string - SecretAccessKey string - Token string -} - -type errorOutput struct { - Code string `json:"code"` - Message string `json:"message"` -} - -func (p *Provider) getCredentials() (*getCredentialsOutput, error) { - op := &request.Operation{ - Name: "GetCredentials", - HTTPMethod: "GET", - } - - out := &getCredentialsOutput{} - req := p.Client.NewRequest(op, nil, out) - req.HTTPRequest.Header.Set("Accept", "application/json") - - return out, req.Send() -} - -func validateEndpointHandler(r *request.Request) { - if len(r.ClientInfo.Endpoint) == 0 { - r.Error = aws.ErrMissingEndpoint - } -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - out := r.Data.(*getCredentialsOutput) - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil { - r.Error = awserr.New("SerializationError", - "failed to decode endpoint credentials", - err, - ) - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - var errOut errorOutput - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&errOut); err != nil { - r.Error = awserr.New("SerializationError", - "failed to decode endpoint credentials", - err, - ) - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New(errOut.Code, errOut.Message, nil) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go deleted file mode 100644 index c14231a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ /dev/null @@ -1,78 +0,0 @@ -package credentials - -import ( - "os" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// EnvProviderName provides a name of Env provider -const EnvProviderName = "EnvProvider" - -var ( - // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be - // found in the process's environment. - // - // @readonly - ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) - - // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key - // can't be found in the process's environment. - // - // @readonly - ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) -) - -// A EnvProvider retrieves credentials from the environment variables of the -// running process. Environment credentials never expire. -// -// Environment variables used: -// -// * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY -// -// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY -type EnvProvider struct { - retrieved bool -} - -// NewEnvCredentials returns a pointer to a new Credentials object -// wrapping the environment variable provider. -func NewEnvCredentials() *Credentials { - return NewCredentials(&EnvProvider{}) -} - -// Retrieve retrieves the keys from the environment. -func (e *EnvProvider) Retrieve() (Value, error) { - e.retrieved = false - - id := os.Getenv("AWS_ACCESS_KEY_ID") - if id == "" { - id = os.Getenv("AWS_ACCESS_KEY") - } - - secret := os.Getenv("AWS_SECRET_ACCESS_KEY") - if secret == "" { - secret = os.Getenv("AWS_SECRET_KEY") - } - - if id == "" { - return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound - } - - if secret == "" { - return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound - } - - e.retrieved = true - return Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: os.Getenv("AWS_SESSION_TOKEN"), - ProviderName: EnvProviderName, - }, nil -} - -// IsExpired returns if the credentials have been retrieved. -func (e *EnvProvider) IsExpired() bool { - return !e.retrieved -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go deleted file mode 100644 index 51e21e0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ /dev/null @@ -1,150 +0,0 @@ -package credentials - -import ( - "fmt" - "os" - - "github.com/go-ini/ini" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredsProviderName provides a name of SharedCreds provider -const SharedCredsProviderName = "SharedCredentialsProvider" - -var ( - // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. - ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) -) - -// A SharedCredentialsProvider retrieves credentials from the current user's home -// directory, and keeps track if those credentials are expired. -// -// Profile ini file example: $HOME/.aws/credentials -type SharedCredentialsProvider struct { - // Path to the shared credentials file. - // - // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the - // env value is empty will default to current user's home directory. - // Linux/OSX: "$HOME/.aws/credentials" - // Windows: "%USERPROFILE%\.aws\credentials" - Filename string - - // AWS Profile to extract credentials from the shared credentials file. If empty - // will default to environment variable "AWS_PROFILE" or "default" if - // environment variable is also not set. - Profile string - - // retrieved states if the credentials have been successfully retrieved. - retrieved bool -} - -// NewSharedCredentials returns a pointer to a new Credentials object -// wrapping the Profile file provider. -func NewSharedCredentials(filename, profile string) *Credentials { - return NewCredentials(&SharedCredentialsProvider{ - Filename: filename, - Profile: profile, - }) -} - -// Retrieve reads and extracts the shared credentials from the current -// users home directory. -func (p *SharedCredentialsProvider) Retrieve() (Value, error) { - p.retrieved = false - - filename, err := p.filename() - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - creds, err := loadProfile(filename, p.profile()) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - p.retrieved = true - return creds, nil -} - -// IsExpired returns if the shared credentials have expired. -func (p *SharedCredentialsProvider) IsExpired() bool { - return !p.retrieved -} - -// loadProfiles loads from the file pointed to by shared credentials filename for profile. -// The credentials retrieved from the profile will be returned or error. Error will be -// returned if it fails to read from the file, or the data is invalid. -func loadProfile(filename, profile string) (Value, error) { - config, err := ini.Load(filename) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) - } - iniProfile, err := config.GetSection(profile) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", err) - } - - id, err := iniProfile.GetKey("aws_access_key_id") - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey", - fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), - err) - } - - secret, err := iniProfile.GetKey("aws_secret_access_key") - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret", - fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), - nil) - } - - // Default to empty string if not found - token := iniProfile.Key("aws_session_token") - - return Value{ - AccessKeyID: id.String(), - SecretAccessKey: secret.String(), - SessionToken: token.String(), - ProviderName: SharedCredsProviderName, - }, nil -} - -// filename returns the filename to use to read AWS shared credentials. -// -// Will return an error if the user's home directory path cannot be found. -func (p *SharedCredentialsProvider) filename() (string, error) { - if len(p.Filename) != 0 { - return p.Filename, nil - } - - if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); len(p.Filename) != 0 { - return p.Filename, nil - } - - if home := shareddefaults.UserHomeDir(); len(home) == 0 { - // Backwards compatibility of home directly not found error being returned. - // This error is too verbose, failure when opening the file would of been - // a better error to return. - return "", ErrSharedCredentialsHomeNotFound - } - - p.Filename = shareddefaults.SharedCredentialsFilename() - - return p.Filename, nil -} - -// profile returns the AWS shared credentials profile. If empty will read -// environment variable "AWS_PROFILE". If that is not set profile will -// return "default". -func (p *SharedCredentialsProvider) profile() string { - if p.Profile == "" { - p.Profile = os.Getenv("AWS_PROFILE") - } - if p.Profile == "" { - p.Profile = "default" - } - - return p.Profile -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go deleted file mode 100644 index 4f5dab3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go +++ /dev/null @@ -1,57 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// StaticProviderName provides a name of Static provider -const StaticProviderName = "StaticProvider" - -var ( - // ErrStaticCredentialsEmpty is emitted when static credentials are empty. - // - // @readonly - ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) -) - -// A StaticProvider is a set of credentials which are set programmatically, -// and will never expire. -type StaticProvider struct { - Value -} - -// NewStaticCredentials returns a pointer to a new Credentials object -// wrapping a static credentials value provider. -func NewStaticCredentials(id, secret, token string) *Credentials { - return NewCredentials(&StaticProvider{Value: Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: token, - }}) -} - -// NewStaticCredentialsFromCreds returns a pointer to a new Credentials object -// wrapping the static credentials value provide. Same as NewStaticCredentials -// but takes the creds Value instead of individual fields -func NewStaticCredentialsFromCreds(creds Value) *Credentials { - return NewCredentials(&StaticProvider{Value: creds}) -} - -// Retrieve returns the credentials or error if the credentials are invalid. -func (s *StaticProvider) Retrieve() (Value, error) { - if s.AccessKeyID == "" || s.SecretAccessKey == "" { - return Value{ProviderName: StaticProviderName}, ErrStaticCredentialsEmpty - } - - if len(s.Value.ProviderName) == 0 { - s.Value.ProviderName = StaticProviderName - } - return s.Value, nil -} - -// IsExpired returns if the credentials are expired. -// -// For StaticProvider, the credentials never expired. -func (s *StaticProvider) IsExpired() bool { - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go deleted file mode 100644 index 4108e43..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ /dev/null @@ -1,298 +0,0 @@ -/* -Package stscreds are credential Providers to retrieve STS AWS credentials. - -STS provides multiple ways to retrieve credentials which can be used when making -future AWS service API operation calls. - -The SDK will ensure that per instance of credentials.Credentials all requests -to refresh the credentials will be synchronized. But, the SDK is unable to -ensure synchronous usage of the AssumeRoleProvider if the value is shared -between multiple Credentials, Sessions or service clients. - -Assume Role - -To assume an IAM role using STS with the SDK you can create a new Credentials -with the SDKs's stscreds package. - - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -Assume Role with static MFA Token - -To assume an IAM role with a MFA token you can either specify a MFA token code -directly or provide a function to prompt the user each time the credentials -need to refresh the role's credentials. Specifying the TokenCode should be used -for short lived operations that will not need to be refreshed, and when you do -not want to have direct control over the user provides their MFA token. - -With TokenCode the AssumeRoleProvider will be not be able to refresh the role's -credentials. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN using the MFA token code provided. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenCode = aws.String("00000000") - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -Assume Role with MFA Token Provider - -To assume an IAM role with MFA for longer running tasks where the credentials -may need to be refreshed setting the TokenProvider field of AssumeRoleProvider -will allow the credential provider to prompt for new MFA token code when the -role's credentials need to be refreshed. - -The StdinTokenProvider function is available to prompt on stdin to retrieve -the MFA token code from the user. You can also implement custom prompts by -satisfing the TokenProvider function signature. - -Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -have undesirable results as the StdinTokenProvider will not be synchronized. A -single Credentials with an AssumeRoleProvider can be shared safely. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. Prompting for MFA token from stdin. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenProvider = stscreds.StdinTokenProvider - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -*/ -package stscreds - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/service/sts" -) - -// StdinTokenProvider will prompt on stdout and read from stdin for a string value. -// An error is returned if reading from stdin fails. -// -// Use this function go read MFA tokens from stdin. The function makes no attempt -// to make atomic prompts from stdin across multiple gorouties. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely -// -// Will wait forever until something is provided on the stdin. -func StdinTokenProvider() (string, error) { - var v string - fmt.Printf("Assume Role MFA token code: ") - _, err := fmt.Scanln(&v) - - return v, err -} - -// ProviderName provides a name of AssumeRole provider -const ProviderName = "AssumeRoleProvider" - -// AssumeRoler represents the minimal subset of the STS client API used by this provider. -type AssumeRoler interface { - AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) -} - -// DefaultDuration is the default amount of time in minutes that the credentials -// will be valid for. -var DefaultDuration = time.Duration(15) * time.Minute - -// AssumeRoleProvider retrieves temporary credentials from the STS service, and -// keeps track of their expiration time. -// -// This credential provider will be used by the SDKs default credential change -// when shared configuration is enabled, and the shared config or shared credentials -// file configure assume role. See Session docs for how to do this. -// -// AssumeRoleProvider does not provide any synchronization and it is not safe -// to share this value across multiple Credentials, Sessions, or service clients -// without also sharing the same Credentials instance. -type AssumeRoleProvider struct { - credentials.Expiry - - // STS client to make assume role request with. - Client AssumeRoler - - // Role to be assumed. - RoleARN string - - // Session name, if you wish to reuse the credentials elsewhere. - RoleSessionName string - - // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. - Duration time.Duration - - // Optional ExternalID to pass along, defaults to nil if not set. - ExternalID *string - - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - SerialNumber *string - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // If SerialNumber is set and neither TokenCode nor TokenProvider are also - // set an error will be returned. - TokenCode *string - - // Async method of providing MFA token code for assuming an IAM role with MFA. - // The value returned by the function will be used as the TokenCode in the Retrieve - // call. See StdinTokenProvider for a provider that prompts and reads from stdin. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed when SerialNumber is also set and - // TokenCode is not set. - // - // If both TokenCode and TokenProvider is set, TokenProvider will be used and - // TokenCode is ignored. - TokenProvider func() (string, error) - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. -// -// Takes a Config provider to create the STS client. The ConfigProvider is -// satisfied by the session.Session type. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: sts.New(c), - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. -// -// Takes an AssumeRoler which can be satisfied by the STS client. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: svc, - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { - - // Apply defaults where parameters are not set. - if p.RoleSessionName == "" { - // Try to work out a role name that will hopefully end up unique. - p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano()) - } - if p.Duration == 0 { - // Expire as often as AWS permits. - p.Duration = DefaultDuration - } - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int64(int64(p.Duration / time.Second)), - RoleArn: aws.String(p.RoleARN), - RoleSessionName: aws.String(p.RoleSessionName), - ExternalId: p.ExternalID, - } - if p.Policy != nil { - input.Policy = p.Policy - } - if p.SerialNumber != nil { - if p.TokenCode != nil { - input.SerialNumber = p.SerialNumber - input.TokenCode = p.TokenCode - } else if p.TokenProvider != nil { - input.SerialNumber = p.SerialNumber - code, err := p.TokenProvider() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - input.TokenCode = aws.String(code) - } else { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("AssumeRoleTokenNotAvailable", - "assume role with MFA enabled, but neither TokenCode nor TokenProvider are set", nil) - } - } - - roleOutput, err := p.Client.AssumeRole(input) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - // We will proactively generate new credentials before they expire. - p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: *roleOutput.Credentials.AccessKeyId, - SecretAccessKey: *roleOutput.Credentials.SecretAccessKey, - SessionToken: *roleOutput.Credentials.SessionToken, - ProviderName: ProviderName, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go deleted file mode 100644 index 152d785..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go +++ /dev/null @@ -1,46 +0,0 @@ -// Package csm provides Client Side Monitoring (CSM) which enables sending metrics -// via UDP connection. Using the Start function will enable the reporting of -// metrics on a given port. If Start is called, with different parameters, again, -// a panic will occur. -// -// Pause can be called to pause any metrics publishing on a given port. Sessions -// that have had their handlers modified via InjectHandlers may still be used. -// However, the handlers will act as a no-op meaning no metrics will be published. -// -// Example: -// r, err := csm.Start("clientID", ":31000") -// if err != nil { -// panic(fmt.Errorf("failed starting CSM: %v", err)) -// } -// -// sess, err := session.NewSession(&aws.Config{}) -// if err != nil { -// panic(fmt.Errorf("failed loading session: %v", err)) -// } -// -// r.InjectHandlers(&sess.Handlers) -// -// client := s3.New(sess) -// resp, err := client.GetObject(&s3.GetObjectInput{ -// Bucket: aws.String("bucket"), -// Key: aws.String("key"), -// }) -// -// // Will pause monitoring -// r.Pause() -// resp, err = client.GetObject(&s3.GetObjectInput{ -// Bucket: aws.String("bucket"), -// Key: aws.String("key"), -// }) -// -// // Resume monitoring -// r.Continue() -// -// Start returns a Reporter that is used to enable or disable monitoring. If -// access to the Reporter is required later, calling Get will return the Reporter -// singleton. -// -// Example: -// r := csm.Get() -// r.Continue() -package csm diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go deleted file mode 100644 index 2f0c6ea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go +++ /dev/null @@ -1,67 +0,0 @@ -package csm - -import ( - "fmt" - "sync" -) - -var ( - lock sync.Mutex -) - -// Client side metric handler names -const ( - APICallMetricHandlerName = "awscsm.SendAPICallMetric" - APICallAttemptMetricHandlerName = "awscsm.SendAPICallAttemptMetric" -) - -// Start will start the a long running go routine to capture -// client side metrics. Calling start multiple time will only -// start the metric listener once and will panic if a different -// client ID or port is passed in. -// -// Example: -// r, err := csm.Start("clientID", "127.0.0.1:8094") -// if err != nil { -// panic(fmt.Errorf("expected no error, but received %v", err)) -// } -// sess := session.NewSession() -// r.InjectHandlers(sess.Handlers) -// -// svc := s3.New(sess) -// out, err := svc.GetObject(&s3.GetObjectInput{ -// Bucket: aws.String("bucket"), -// Key: aws.String("key"), -// }) -func Start(clientID string, url string) (*Reporter, error) { - lock.Lock() - defer lock.Unlock() - - if sender == nil { - sender = newReporter(clientID, url) - } else { - if sender.clientID != clientID { - panic(fmt.Errorf("inconsistent client IDs. %q was expected, but received %q", sender.clientID, clientID)) - } - - if sender.url != url { - panic(fmt.Errorf("inconsistent URLs. %q was expected, but received %q", sender.url, url)) - } - } - - if err := connect(url); err != nil { - sender = nil - return nil, err - } - - return sender, nil -} - -// Get will return a reporter if one exists, if one does not exist, nil will -// be returned. -func Get() *Reporter { - lock.Lock() - defer lock.Unlock() - - return sender -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go deleted file mode 100644 index 4b0d630..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go +++ /dev/null @@ -1,51 +0,0 @@ -package csm - -import ( - "strconv" - "time" -) - -type metricTime time.Time - -func (t metricTime) MarshalJSON() ([]byte, error) { - ns := time.Duration(time.Time(t).UnixNano()) - return []byte(strconv.FormatInt(int64(ns/time.Millisecond), 10)), nil -} - -type metric struct { - ClientID *string `json:"ClientId,omitempty"` - API *string `json:"Api,omitempty"` - Service *string `json:"Service,omitempty"` - Timestamp *metricTime `json:"Timestamp,omitempty"` - Type *string `json:"Type,omitempty"` - Version *int `json:"Version,omitempty"` - - AttemptCount *int `json:"AttemptCount,omitempty"` - Latency *int `json:"Latency,omitempty"` - - Fqdn *string `json:"Fqdn,omitempty"` - UserAgent *string `json:"UserAgent,omitempty"` - AttemptLatency *int `json:"AttemptLatency,omitempty"` - - SessionToken *string `json:"SessionToken,omitempty"` - Region *string `json:"Region,omitempty"` - AccessKey *string `json:"AccessKey,omitempty"` - HTTPStatusCode *int `json:"HttpStatusCode,omitempty"` - XAmzID2 *string `json:"XAmzId2,omitempty"` - XAmzRequestID *string `json:"XAmznRequestId,omitempty"` - - AWSException *string `json:"AwsException,omitempty"` - AWSExceptionMessage *string `json:"AwsExceptionMessage,omitempty"` - SDKException *string `json:"SdkException,omitempty"` - SDKExceptionMessage *string `json:"SdkExceptionMessage,omitempty"` - - DestinationIP *string `json:"DestinationIp,omitempty"` - ConnectionReused *int `json:"ConnectionReused,omitempty"` - - AcquireConnectionLatency *int `json:"AcquireConnectionLatency,omitempty"` - ConnectLatency *int `json:"ConnectLatency,omitempty"` - RequestLatency *int `json:"RequestLatency,omitempty"` - DNSLatency *int `json:"DnsLatency,omitempty"` - TCPLatency *int `json:"TcpLatency,omitempty"` - SSLLatency *int `json:"SslLatency,omitempty"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go deleted file mode 100644 index 514fc37..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go +++ /dev/null @@ -1,54 +0,0 @@ -package csm - -import ( - "sync/atomic" -) - -const ( - runningEnum = iota - pausedEnum -) - -var ( - // MetricsChannelSize of metrics to hold in the channel - MetricsChannelSize = 100 -) - -type metricChan struct { - ch chan metric - paused int64 -} - -func newMetricChan(size int) metricChan { - return metricChan{ - ch: make(chan metric, size), - } -} - -func (ch *metricChan) Pause() { - atomic.StoreInt64(&ch.paused, pausedEnum) -} - -func (ch *metricChan) Continue() { - atomic.StoreInt64(&ch.paused, runningEnum) -} - -func (ch *metricChan) IsPaused() bool { - v := atomic.LoadInt64(&ch.paused) - return v == pausedEnum -} - -// Push will push metrics to the metric channel if the channel -// is not paused -func (ch *metricChan) Push(m metric) bool { - if ch.IsPaused() { - return false - } - - select { - case ch.ch <- m: - return true - default: - return false - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go deleted file mode 100644 index 11082e5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go +++ /dev/null @@ -1,231 +0,0 @@ -package csm - -import ( - "encoding/json" - "net" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -const ( - // DefaultPort is used when no port is specified - DefaultPort = "31000" -) - -// Reporter will gather metrics of API requests made and -// send those metrics to the CSM endpoint. -type Reporter struct { - clientID string - url string - conn net.Conn - metricsCh metricChan - done chan struct{} -} - -var ( - sender *Reporter -) - -func connect(url string) error { - const network = "udp" - if err := sender.connect(network, url); err != nil { - return err - } - - if sender.done == nil { - sender.done = make(chan struct{}) - go sender.start() - } - - return nil -} - -func newReporter(clientID, url string) *Reporter { - return &Reporter{ - clientID: clientID, - url: url, - metricsCh: newMetricChan(MetricsChannelSize), - } -} - -func (rep *Reporter) sendAPICallAttemptMetric(r *request.Request) { - if rep == nil { - return - } - - now := time.Now() - creds, _ := r.Config.Credentials.Get() - - m := metric{ - ClientID: aws.String(rep.clientID), - API: aws.String(r.Operation.Name), - Service: aws.String(r.ClientInfo.ServiceID), - Timestamp: (*metricTime)(&now), - UserAgent: aws.String(r.HTTPRequest.Header.Get("User-Agent")), - Region: r.Config.Region, - Type: aws.String("ApiCallAttempt"), - Version: aws.Int(1), - - XAmzRequestID: aws.String(r.RequestID), - - AttemptCount: aws.Int(r.RetryCount + 1), - AttemptLatency: aws.Int(int(now.Sub(r.AttemptTime).Nanoseconds() / int64(time.Millisecond))), - AccessKey: aws.String(creds.AccessKeyID), - } - - if r.HTTPResponse != nil { - m.HTTPStatusCode = aws.Int(r.HTTPResponse.StatusCode) - } - - if r.Error != nil { - if awserr, ok := r.Error.(awserr.Error); ok { - setError(&m, awserr) - } - } - - rep.metricsCh.Push(m) -} - -func setError(m *metric, err awserr.Error) { - msg := err.Error() - code := err.Code() - - switch code { - case "RequestError", - "SerializationError", - request.CanceledErrorCode: - m.SDKException = &code - m.SDKExceptionMessage = &msg - default: - m.AWSException = &code - m.AWSExceptionMessage = &msg - } -} - -func (rep *Reporter) sendAPICallMetric(r *request.Request) { - if rep == nil { - return - } - - now := time.Now() - m := metric{ - ClientID: aws.String(rep.clientID), - API: aws.String(r.Operation.Name), - Service: aws.String(r.ClientInfo.ServiceID), - Timestamp: (*metricTime)(&now), - Type: aws.String("ApiCall"), - AttemptCount: aws.Int(r.RetryCount + 1), - Latency: aws.Int(int(time.Now().Sub(r.Time) / time.Millisecond)), - XAmzRequestID: aws.String(r.RequestID), - } - - // TODO: Probably want to figure something out for logging dropped - // metrics - rep.metricsCh.Push(m) -} - -func (rep *Reporter) connect(network, url string) error { - if rep.conn != nil { - rep.conn.Close() - } - - conn, err := net.Dial(network, url) - if err != nil { - return awserr.New("UDPError", "Could not connect", err) - } - - rep.conn = conn - - return nil -} - -func (rep *Reporter) close() { - if rep.done != nil { - close(rep.done) - } - - rep.metricsCh.Pause() -} - -func (rep *Reporter) start() { - defer func() { - rep.metricsCh.Pause() - }() - - for { - select { - case <-rep.done: - rep.done = nil - return - case m := <-rep.metricsCh.ch: - // TODO: What to do with this error? Probably should just log - b, err := json.Marshal(m) - if err != nil { - continue - } - - rep.conn.Write(b) - } - } -} - -// Pause will pause the metric channel preventing any new metrics from -// being added. -func (rep *Reporter) Pause() { - lock.Lock() - defer lock.Unlock() - - if rep == nil { - return - } - - rep.close() -} - -// Continue will reopen the metric channel and allow for monitoring -// to be resumed. -func (rep *Reporter) Continue() { - lock.Lock() - defer lock.Unlock() - if rep == nil { - return - } - - if !rep.metricsCh.IsPaused() { - return - } - - rep.metricsCh.Continue() -} - -// InjectHandlers will will enable client side metrics and inject the proper -// handlers to handle how metrics are sent. -// -// Example: -// // Start must be called in order to inject the correct handlers -// r, err := csm.Start("clientID", "127.0.0.1:8094") -// if err != nil { -// panic(fmt.Errorf("expected no error, but received %v", err)) -// } -// -// sess := session.NewSession() -// r.InjectHandlers(&sess.Handlers) -// -// // create a new service client with our client side metric session -// svc := s3.New(sess) -func (rep *Reporter) InjectHandlers(handlers *request.Handlers) { - if rep == nil { - return - } - - apiCallHandler := request.NamedHandler{Name: APICallMetricHandlerName, Fn: rep.sendAPICallMetric} - apiCallAttemptHandler := request.NamedHandler{Name: APICallAttemptMetricHandlerName, Fn: rep.sendAPICallAttemptMetric} - - handlers.Complete.PushFrontNamed(apiCallHandler) - handlers.Complete.PushFrontNamed(apiCallAttemptHandler) - - handlers.AfterRetry.PushFrontNamed(apiCallAttemptHandler) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go deleted file mode 100644 index 5040a2f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ /dev/null @@ -1,205 +0,0 @@ -// Package defaults is a collection of helpers to retrieve the SDK's default -// configuration and handlers. -// -// Generally this package shouldn't be used directly, but session.Session -// instead. This package is useful when you need to reset the defaults -// of a session or service client to the SDK defaults before setting -// additional parameters. -package defaults - -import ( - "fmt" - "net" - "net/http" - "net/url" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Defaults provides a collection of default values for SDK clients. -type Defaults struct { - Config *aws.Config - Handlers request.Handlers -} - -// Get returns the SDK's default values with Config and handlers pre-configured. -func Get() Defaults { - cfg := Config() - handlers := Handlers() - cfg.Credentials = CredChain(cfg, handlers) - - return Defaults{ - Config: cfg, - Handlers: handlers, - } -} - -// Config returns the default configuration without credentials. -// To retrieve a config with credentials also included use -// `defaults.Get().Config` instead. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the configuration of an -// existing service client or session. -func Config() *aws.Config { - return aws.NewConfig(). - WithCredentials(credentials.AnonymousCredentials). - WithRegion(os.Getenv("AWS_REGION")). - WithHTTPClient(http.DefaultClient). - WithMaxRetries(aws.UseServiceDefaultRetries). - WithLogger(aws.NewDefaultLogger()). - WithLogLevel(aws.LogOff). - WithEndpointResolver(endpoints.DefaultResolver()) -} - -// Handlers returns the default request handlers. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the request handlers of an -// existing service client or session. -func Handlers() request.Handlers { - var handlers request.Handlers - - handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - handlers.Validate.AfterEachFn = request.HandlerListStopOnError - handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) - handlers.Build.PushBackNamed(corehandlers.AddHostExecEnvUserAgentHander) - handlers.Build.AfterEachFn = request.HandlerListStopOnError - handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) - handlers.Send.PushBackNamed(corehandlers.ValidateReqSigHandler) - handlers.Send.PushBackNamed(corehandlers.SendHandler) - handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler) - - return handlers -} - -// CredChain returns the default credential chain. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the credentials of an -// existing service client or session's Config. -func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { - return credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: CredProviders(cfg, handlers), - }) -} - -// CredProviders returns the slice of providers used in -// the default credential chain. -// -// For applications that need to use some other provider (for example use -// different environment variables for legacy reasons) but still fall back -// on the default chain of providers. This allows that default chaint to be -// automatically updated -func CredProviders(cfg *aws.Config, handlers request.Handlers) []credentials.Provider { - return []credentials.Provider{ - &credentials.EnvProvider{}, - &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, - RemoteCredProvider(*cfg, handlers), - } -} - -const ( - httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - ecsCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" -) - -// RemoteCredProvider returns a credentials provider for the default remote -// endpoints such as EC2 or ECS Roles. -func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - if u := os.Getenv(httpProviderEnvVar); len(u) > 0 { - return localHTTPCredProvider(cfg, handlers, u) - } - - if uri := os.Getenv(ecsCredsProviderEnvVar); len(uri) > 0 { - u := fmt.Sprintf("http://169.254.170.2%s", uri) - return httpCredProvider(cfg, handlers, u) - } - - return ec2RoleProvider(cfg, handlers) -} - -var lookupHostFn = net.LookupHost - -func isLoopbackHost(host string) (bool, error) { - ip := net.ParseIP(host) - if ip != nil { - return ip.IsLoopback(), nil - } - - // Host is not an ip, perform lookup - addrs, err := lookupHostFn(host) - if err != nil { - return false, err - } - for _, addr := range addrs { - if !net.ParseIP(addr).IsLoopback() { - return false, nil - } - } - - return true, nil -} - -func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - var errMsg string - - parsed, err := url.Parse(u) - if err != nil { - errMsg = fmt.Sprintf("invalid URL, %v", err) - } else { - host := aws.URLHostname(parsed) - if len(host) == 0 { - errMsg = "unable to parse host from local HTTP cred provider URL" - } else if isLoopback, loopbackErr := isLoopbackHost(host); loopbackErr != nil { - errMsg = fmt.Sprintf("failed to resolve host %q, %v", host, loopbackErr) - } else if !isLoopback { - errMsg = fmt.Sprintf("invalid endpoint host, %q, only loopback hosts are allowed.", host) - } - } - - if len(errMsg) > 0 { - if cfg.Logger != nil { - cfg.Logger.Log("Ignoring, HTTP credential provider", errMsg, err) - } - return credentials.ErrorProvider{ - Err: awserr.New("CredentialsEndpointError", errMsg, err), - ProviderName: endpointcreds.ProviderName, - } - } - - return httpCredProvider(cfg, handlers, u) -} - -func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - return endpointcreds.NewProviderClient(cfg, handlers, u, - func(p *endpointcreds.Provider) { - p.ExpiryWindow = 5 * time.Minute - }, - ) -} - -func ec2RoleProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - resolver := cfg.EndpointResolver - if resolver == nil { - resolver = endpoints.DefaultResolver() - } - - e, _ := resolver.EndpointFor(endpoints.Ec2metadataServiceID, "") - return &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.NewClient(cfg, handlers, e.URL, e.SigningRegion), - ExpiryWindow: 5 * time.Minute, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go deleted file mode 100644 index ca0ee1d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go +++ /dev/null @@ -1,27 +0,0 @@ -package defaults - -import ( - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return shareddefaults.SharedCredentialsFilename() -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return shareddefaults.SharedConfigFilename() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/doc.go deleted file mode 100644 index 4fcb616..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/doc.go +++ /dev/null @@ -1,56 +0,0 @@ -// Package aws provides the core SDK's utilities and shared types. Use this package's -// utilities to simplify setting and reading API operations parameters. -// -// Value and Pointer Conversion Utilities -// -// This package includes a helper conversion utility for each scalar type the SDK's -// API use. These utilities make getting a pointer of the scalar, and dereferencing -// a pointer easier. -// -// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. -// The Pointer to value will safely dereference the pointer and return its value. -// If the pointer was nil, the scalar's zero value will be returned. -// -// The value to pointer functions will be named after the scalar type. So get a -// *string from a string value use the "String" function. This makes it easy to -// to get pointer of a literal string value, because getting the address of a -// literal requires assigning the value to a variable first. -// -// var strPtr *string -// -// // Without the SDK's conversion functions -// str := "my string" -// strPtr = &str -// -// // With the SDK's conversion functions -// strPtr = aws.String("my string") -// -// // Convert *string to string value -// str = aws.StringValue(strPtr) -// -// In addition to scalars the aws package also includes conversion utilities for -// map and slice for commonly types used in API parameters. The map and slice -// conversion functions use similar naming pattern as the scalar conversion -// functions. -// -// var strPtrs []*string -// var strs []string = []string{"Go", "Gophers", "Go"} -// -// // Convert []string to []*string -// strPtrs = aws.StringSlice(strs) -// -// // Convert []*string to []string -// strs = aws.StringValueSlice(strPtrs) -// -// SDK Default HTTP Client -// -// The SDK will use the http.DefaultClient if a HTTP client is not provided to -// the SDK's Session, or service client constructor. This means that if the -// http.DefaultClient is modified by other components of your application the -// modifications will be picked up by the SDK as well. -// -// In some cases this might be intended, but it is a better practice to create -// a custom HTTP Client to share explicitly through your application. You can -// configure the SDK to use the custom HTTP Client by setting the HTTPClient -// value of the SDK's Config type when creating a Session or service client. -package aws diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go deleted file mode 100644 index c215cd3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ /dev/null @@ -1,162 +0,0 @@ -package ec2metadata - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkuri" -) - -// GetMetadata uses the path provided to request information from the EC2 -// instance metdata service. The content will be returned as a string, or -// error if the request failed. -func (c *EC2Metadata) GetMetadata(p string) (string, error) { - op := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: sdkuri.PathJoin("/meta-data", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - - return output.Content, req.Send() -} - -// GetUserData returns the userdata that was configured for the service. If -// there is no user-data setup for the EC2 instance a "NotFoundError" error -// code will be returned. -func (c *EC2Metadata) GetUserData() (string, error) { - op := &request.Operation{ - Name: "GetUserData", - HTTPMethod: "GET", - HTTPPath: "/user-data", - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - req.Handlers.UnmarshalError.PushBack(func(r *request.Request) { - if r.HTTPResponse.StatusCode == http.StatusNotFound { - r.Error = awserr.New("NotFoundError", "user-data not found", r.Error) - } - }) - - return output.Content, req.Send() -} - -// GetDynamicData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *EC2Metadata) GetDynamicData(p string) (string, error) { - op := &request.Operation{ - Name: "GetDynamicData", - HTTPMethod: "GET", - HTTPPath: sdkuri.PathJoin("/dynamic", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - - return output.Content, req.Send() -} - -// GetInstanceIdentityDocument retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *EC2Metadata) GetInstanceIdentityDocument() (EC2InstanceIdentityDocument, error) { - resp, err := c.GetDynamicData("instance-identity/document") - if err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 instance identity document", err) - } - - doc := EC2InstanceIdentityDocument{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&doc); err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("SerializationError", - "failed to decode EC2 instance identity document", err) - } - - return doc, nil -} - -// IAMInfo retrieves IAM info from the metadata API -func (c *EC2Metadata) IAMInfo() (EC2IAMInfo, error) { - resp, err := c.GetMetadata("iam/info") - if err != nil { - return EC2IAMInfo{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 IAM info", err) - } - - info := EC2IAMInfo{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&info); err != nil { - return EC2IAMInfo{}, - awserr.New("SerializationError", - "failed to decode EC2 IAM info", err) - } - - if info.Code != "Success" { - errMsg := fmt.Sprintf("failed to get EC2 IAM Info (%s)", info.Code) - return EC2IAMInfo{}, - awserr.New("EC2MetadataError", errMsg, nil) - } - - return info, nil -} - -// Region returns the region the instance is running in. -func (c *EC2Metadata) Region() (string, error) { - resp, err := c.GetMetadata("placement/availability-zone") - if err != nil { - return "", err - } - - // returns region without the suffix. Eg: us-west-2a becomes us-west-2 - return resp[:len(resp)-1], nil -} - -// Available returns if the application has access to the EC2 Metadata service. -// Can be used to determine if application is running within an EC2 Instance and -// the metadata service is available. -func (c *EC2Metadata) Available() bool { - if _, err := c.GetMetadata("instance-id"); err != nil { - return false - } - - return true -} - -// An EC2IAMInfo provides the shape for unmarshaling -// an IAM info from the metadata API -type EC2IAMInfo struct { - Code string - LastUpdated time.Time - InstanceProfileArn string - InstanceProfileID string -} - -// An EC2InstanceIdentityDocument provides the shape for unmarshaling -// an instance identity document -type EC2InstanceIdentityDocument struct { - DevpayProductCodes []string `json:"devpayProductCodes"` - AvailabilityZone string `json:"availabilityZone"` - PrivateIP string `json:"privateIp"` - Version string `json:"version"` - Region string `json:"region"` - InstanceID string `json:"instanceId"` - BillingProducts []string `json:"billingProducts"` - InstanceType string `json:"instanceType"` - AccountID string `json:"accountId"` - PendingTime time.Time `json:"pendingTime"` - ImageID string `json:"imageId"` - KernelID string `json:"kernelId"` - RamdiskID string `json:"ramdiskId"` - Architecture string `json:"architecture"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go deleted file mode 100644 index ef5f732..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ /dev/null @@ -1,148 +0,0 @@ -// Package ec2metadata provides the client for making API calls to the -// EC2 Metadata service. -// -// This package's client can be disabled completely by setting the environment -// variable "AWS_EC2_METADATA_DISABLED=true". This environment variable set to -// true instructs the SDK to disable the EC2 Metadata client. The client cannot -// be used while the environemnt variable is set to true, (case insensitive). -package ec2metadata - -import ( - "bytes" - "errors" - "io" - "net/http" - "os" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" -) - -// ServiceName is the name of the service. -const ServiceName = "ec2metadata" -const disableServiceEnvVar = "AWS_EC2_METADATA_DISABLED" - -// A EC2Metadata is an EC2 Metadata service Client. -type EC2Metadata struct { - *client.Client -} - -// New creates a new instance of the EC2Metadata client with a session. -// This client is safe to use across multiple goroutines. -// -// -// Example: -// // Create a EC2Metadata client from just a session. -// svc := ec2metadata.New(mySession) -// -// // Create a EC2Metadata client with additional configuration -// svc := ec2metadata.New(mySession, aws.NewConfig().WithLogLevel(aws.LogDebugHTTPBody)) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata { - c := p.ClientConfig(ServiceName, cfgs...) - return NewClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion) -} - -// NewClient returns a new EC2Metadata client. Should be used to create -// a client when not using a session. Generally using just New with a session -// is preferred. -// -// If an unmodified HTTP client is provided from the stdlib default, or no client -// the EC2RoleProvider's EC2Metadata HTTP client's timeout will be shortened. -// To disable this set Config.EC2MetadataDisableTimeoutOverride to false. Enabled by default. -func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata { - if !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) { - // If the http client is unmodified and this feature is not disabled - // set custom timeouts for EC2Metadata requests. - cfg.HTTPClient = &http.Client{ - // use a shorter timeout than default because the metadata - // service is local if it is running, and to fail faster - // if not running on an ec2 instance. - Timeout: 5 * time.Second, - } - } - - svc := &EC2Metadata{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - Endpoint: endpoint, - APIVersion: "latest", - }, - handlers, - ), - } - - svc.Handlers.Unmarshal.PushBack(unmarshalHandler) - svc.Handlers.UnmarshalError.PushBack(unmarshalError) - svc.Handlers.Validate.Clear() - svc.Handlers.Validate.PushBack(validateEndpointHandler) - - // Disable the EC2 Metadata service if the environment variable is set. - // This shortcirctes the service's functionality to always fail to send - // requests. - if strings.ToLower(os.Getenv(disableServiceEnvVar)) == "true" { - svc.Handlers.Send.SwapNamed(request.NamedHandler{ - Name: corehandlers.SendHandler.Name, - Fn: func(r *request.Request) { - r.Error = awserr.New( - request.CanceledErrorCode, - "EC2 IMDS access disabled via "+disableServiceEnvVar+" env var", - nil) - }, - }) - } - - // Add additional options to the service config - for _, option := range opts { - option(svc.Client) - } - - return svc -} - -func httpClientZero(c *http.Client) bool { - return c == nil || (c.Transport == nil && c.CheckRedirect == nil && c.Jar == nil && c.Timeout == 0) -} - -type metadataOutput struct { - Content string -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - b := &bytes.Buffer{} - if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata respose", err) - return - } - - if data, ok := r.Data.(*metadataOutput); ok { - data.Content = b.String() - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - b := &bytes.Buffer{} - if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata error respose", err) - return - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New("EC2MetadataError", "failed to make EC2Metadata request", errors.New(b.String())) -} - -func validateEndpointHandler(r *request.Request) { - if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go deleted file mode 100644 index c04ba06..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ /dev/null @@ -1,155 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -type modelDefinition map[string]json.RawMessage - -// A DecodeModelOptions are the options for how the endpoints model definition -// are decoded. -type DecodeModelOptions struct { - SkipCustomizations bool -} - -// Set combines all of the option functions together. -func (d *DecodeModelOptions) Set(optFns ...func(*DecodeModelOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// DecodeModel unmarshals a Regions and Endpoint model definition file into -// a endpoint Resolver. If the file format is not supported, or an error occurs -// when unmarshaling the model an error will be returned. -// -// Casting the return value of this func to a EnumPartitions will -// allow you to get a list of the partitions in the order the endpoints -// will be resolved in. -// -// resolver, err := endpoints.DecodeModel(reader) -// -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// for _, p := range partitions { -// // ... inspect partitions -// } -func DecodeModel(r io.Reader, optFns ...func(*DecodeModelOptions)) (Resolver, error) { - var opts DecodeModelOptions - opts.Set(optFns...) - - // Get the version of the partition file to determine what - // unmarshaling model to use. - modelDef := modelDefinition{} - if err := json.NewDecoder(r).Decode(&modelDef); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - var version string - if b, ok := modelDef["version"]; ok { - version = string(b) - } else { - return nil, newDecodeModelError("endpoints version not found in model", nil) - } - - if version == "3" { - return decodeV3Endpoints(modelDef, opts) - } - - return nil, newDecodeModelError( - fmt.Sprintf("endpoints version %s, not supported", version), nil) -} - -func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resolver, error) { - b, ok := modelDef["partitions"] - if !ok { - return nil, newDecodeModelError("endpoints model missing partitions", nil) - } - - ps := partitions{} - if err := json.Unmarshal(b, &ps); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - if opts.SkipCustomizations { - return ps, nil - } - - // Customization - for i := 0; i < len(ps); i++ { - p := &ps[i] - custAddEC2Metadata(p) - custAddS3DualStack(p) - custRmIotDataService(p) - custFixAppAutoscalingChina(p) - } - - return ps, nil -} - -func custAddS3DualStack(p *partition) { - if p.ID != "aws" { - return - } - - s, ok := p.Services["s3"] - if !ok { - return - } - - s.Defaults.HasDualStack = boxedTrue - s.Defaults.DualStackHostname = "{service}.dualstack.{region}.{dnsSuffix}" - - p.Services["s3"] = s -} - -func custAddEC2Metadata(p *partition) { - p.Services["ec2metadata"] = service{ - IsRegionalized: boxedFalse, - PartitionEndpoint: "aws-global", - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - } -} - -func custRmIotDataService(p *partition) { - delete(p.Services, "data.iot") -} - -func custFixAppAutoscalingChina(p *partition) { - if p.ID != "aws-cn" { - return - } - - const serviceName = "application-autoscaling" - s, ok := p.Services[serviceName] - if !ok { - return - } - - const expectHostname = `autoscaling.{region}.amazonaws.com` - if e, a := s.Defaults.Hostname, expectHostname; e != a { - fmt.Printf("custFixAppAutoscalingChina: ignoring customization, expected %s, got %s\n", e, a) - return - } - - s.Defaults.Hostname = expectHostname + ".cn" - p.Services[serviceName] = s -} - -type decodeModelError struct { - awsError -} - -func newDecodeModelError(msg string, err error) decodeModelError { - return decodeModelError{ - awsError: awserr.New("DecodeEndpointsModelError", msg, err), - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go deleted file mode 100644 index 8678810..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ /dev/null @@ -1,3253 +0,0 @@ -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - -// Partition identifiers -const ( - AwsPartitionID = "aws" // AWS Standard partition. - AwsCnPartitionID = "aws-cn" // AWS China partition. - AwsUsGovPartitionID = "aws-us-gov" // AWS GovCloud (US) partition. -) - -// AWS Standard partition's regions. -const ( - ApNortheast1RegionID = "ap-northeast-1" // Asia Pacific (Tokyo). - ApNortheast2RegionID = "ap-northeast-2" // Asia Pacific (Seoul). - ApSouth1RegionID = "ap-south-1" // Asia Pacific (Mumbai). - ApSoutheast1RegionID = "ap-southeast-1" // Asia Pacific (Singapore). - ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). - CaCentral1RegionID = "ca-central-1" // Canada (Central). - EuCentral1RegionID = "eu-central-1" // EU (Frankfurt). - EuWest1RegionID = "eu-west-1" // EU (Ireland). - EuWest2RegionID = "eu-west-2" // EU (London). - EuWest3RegionID = "eu-west-3" // EU (Paris). - SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). - UsEast1RegionID = "us-east-1" // US East (N. Virginia). - UsEast2RegionID = "us-east-2" // US East (Ohio). - UsWest1RegionID = "us-west-1" // US West (N. California). - UsWest2RegionID = "us-west-2" // US West (Oregon). -) - -// AWS China partition's regions. -const ( - CnNorth1RegionID = "cn-north-1" // China (Beijing). - CnNorthwest1RegionID = "cn-northwest-1" // China (Ningxia). -) - -// AWS GovCloud (US) partition's regions. -const ( - UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US). -) - -// Service identifiers -const ( - A4bServiceID = "a4b" // A4b. - AcmServiceID = "acm" // Acm. - AcmPcaServiceID = "acm-pca" // AcmPca. - ApiMediatailorServiceID = "api.mediatailor" // ApiMediatailor. - ApiPricingServiceID = "api.pricing" // ApiPricing. - ApiSagemakerServiceID = "api.sagemaker" // ApiSagemaker. - ApigatewayServiceID = "apigateway" // Apigateway. - ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. - Appstream2ServiceID = "appstream2" // Appstream2. - AthenaServiceID = "athena" // Athena. - AutoscalingServiceID = "autoscaling" // Autoscaling. - AutoscalingPlansServiceID = "autoscaling-plans" // AutoscalingPlans. - BatchServiceID = "batch" // Batch. - BudgetsServiceID = "budgets" // Budgets. - CeServiceID = "ce" // Ce. - Cloud9ServiceID = "cloud9" // Cloud9. - ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. - CloudformationServiceID = "cloudformation" // Cloudformation. - CloudfrontServiceID = "cloudfront" // Cloudfront. - CloudhsmServiceID = "cloudhsm" // Cloudhsm. - Cloudhsmv2ServiceID = "cloudhsmv2" // Cloudhsmv2. - CloudsearchServiceID = "cloudsearch" // Cloudsearch. - CloudtrailServiceID = "cloudtrail" // Cloudtrail. - CodebuildServiceID = "codebuild" // Codebuild. - CodecommitServiceID = "codecommit" // Codecommit. - CodedeployServiceID = "codedeploy" // Codedeploy. - CodepipelineServiceID = "codepipeline" // Codepipeline. - CodestarServiceID = "codestar" // Codestar. - CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. - CognitoIdpServiceID = "cognito-idp" // CognitoIdp. - CognitoSyncServiceID = "cognito-sync" // CognitoSync. - ComprehendServiceID = "comprehend" // Comprehend. - ConfigServiceID = "config" // Config. - CurServiceID = "cur" // Cur. - DatapipelineServiceID = "datapipeline" // Datapipeline. - DaxServiceID = "dax" // Dax. - DevicefarmServiceID = "devicefarm" // Devicefarm. - DirectconnectServiceID = "directconnect" // Directconnect. - DiscoveryServiceID = "discovery" // Discovery. - DmsServiceID = "dms" // Dms. - DsServiceID = "ds" // Ds. - DynamodbServiceID = "dynamodb" // Dynamodb. - Ec2ServiceID = "ec2" // Ec2. - Ec2metadataServiceID = "ec2metadata" // Ec2metadata. - EcrServiceID = "ecr" // Ecr. - EcsServiceID = "ecs" // Ecs. - ElasticacheServiceID = "elasticache" // Elasticache. - ElasticbeanstalkServiceID = "elasticbeanstalk" // Elasticbeanstalk. - ElasticfilesystemServiceID = "elasticfilesystem" // Elasticfilesystem. - ElasticloadbalancingServiceID = "elasticloadbalancing" // Elasticloadbalancing. - ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. - ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. - EmailServiceID = "email" // Email. - EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. - EsServiceID = "es" // Es. - EventsServiceID = "events" // Events. - FirehoseServiceID = "firehose" // Firehose. - FmsServiceID = "fms" // Fms. - GameliftServiceID = "gamelift" // Gamelift. - GlacierServiceID = "glacier" // Glacier. - GlueServiceID = "glue" // Glue. - GreengrassServiceID = "greengrass" // Greengrass. - GuarddutyServiceID = "guardduty" // Guardduty. - HealthServiceID = "health" // Health. - IamServiceID = "iam" // Iam. - ImportexportServiceID = "importexport" // Importexport. - InspectorServiceID = "inspector" // Inspector. - IotServiceID = "iot" // Iot. - IotanalyticsServiceID = "iotanalytics" // Iotanalytics. - KinesisServiceID = "kinesis" // Kinesis. - KinesisanalyticsServiceID = "kinesisanalytics" // Kinesisanalytics. - KinesisvideoServiceID = "kinesisvideo" // Kinesisvideo. - KmsServiceID = "kms" // Kms. - LambdaServiceID = "lambda" // Lambda. - LightsailServiceID = "lightsail" // Lightsail. - LogsServiceID = "logs" // Logs. - MachinelearningServiceID = "machinelearning" // Machinelearning. - MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. - MediaconvertServiceID = "mediaconvert" // Mediaconvert. - MedialiveServiceID = "medialive" // Medialive. - MediapackageServiceID = "mediapackage" // Mediapackage. - MediastoreServiceID = "mediastore" // Mediastore. - MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. - MghServiceID = "mgh" // Mgh. - MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. - ModelsLexServiceID = "models.lex" // ModelsLex. - MonitoringServiceID = "monitoring" // Monitoring. - MturkRequesterServiceID = "mturk-requester" // MturkRequester. - NeptuneServiceID = "neptune" // Neptune. - OpsworksServiceID = "opsworks" // Opsworks. - OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. - OrganizationsServiceID = "organizations" // Organizations. - PinpointServiceID = "pinpoint" // Pinpoint. - PollyServiceID = "polly" // Polly. - RdsServiceID = "rds" // Rds. - RedshiftServiceID = "redshift" // Redshift. - RekognitionServiceID = "rekognition" // Rekognition. - ResourceGroupsServiceID = "resource-groups" // ResourceGroups. - Route53ServiceID = "route53" // Route53. - Route53domainsServiceID = "route53domains" // Route53domains. - RuntimeLexServiceID = "runtime.lex" // RuntimeLex. - RuntimeSagemakerServiceID = "runtime.sagemaker" // RuntimeSagemaker. - S3ServiceID = "s3" // S3. - SdbServiceID = "sdb" // Sdb. - SecretsmanagerServiceID = "secretsmanager" // Secretsmanager. - ServerlessrepoServiceID = "serverlessrepo" // Serverlessrepo. - ServicecatalogServiceID = "servicecatalog" // Servicecatalog. - ServicediscoveryServiceID = "servicediscovery" // Servicediscovery. - ShieldServiceID = "shield" // Shield. - SmsServiceID = "sms" // Sms. - SnowballServiceID = "snowball" // Snowball. - SnsServiceID = "sns" // Sns. - SqsServiceID = "sqs" // Sqs. - SsmServiceID = "ssm" // Ssm. - StatesServiceID = "states" // States. - StoragegatewayServiceID = "storagegateway" // Storagegateway. - StreamsDynamodbServiceID = "streams.dynamodb" // StreamsDynamodb. - StsServiceID = "sts" // Sts. - SupportServiceID = "support" // Support. - SwfServiceID = "swf" // Swf. - TaggingServiceID = "tagging" // Tagging. - TranslateServiceID = "translate" // Translate. - WafServiceID = "waf" // Waf. - WafRegionalServiceID = "waf-regional" // WafRegional. - WorkdocsServiceID = "workdocs" // Workdocs. - WorkmailServiceID = "workmail" // Workmail. - WorkspacesServiceID = "workspaces" // Workspaces. - XrayServiceID = "xray" // Xray. -) - -// DefaultResolver returns an Endpoint resolver that will be able -// to resolve endpoints for: AWS Standard, AWS China, and AWS GovCloud (US). -// -// Use DefaultPartitions() to get the list of the default partitions. -func DefaultResolver() Resolver { - return defaultPartitions -} - -// DefaultPartitions returns a list of the partitions the SDK is bundled -// with. The available partitions are: AWS Standard, AWS China, and AWS GovCloud (US). -// -// partitions := endpoints.DefaultPartitions -// for _, p := range partitions { -// // ... inspect partitions -// } -func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() -} - -var defaultPartitions = partitions{ - awsPartition, - awscnPartition, - awsusgovPartition, -} - -// AwsPartition returns the Resolver for AWS Standard. -func AwsPartition() Partition { - return awsPartition.Partition() -} - -var awsPartition = partition{ - ID: "aws", - Name: "AWS Standard", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "ap-northeast-1": region{ - Description: "Asia Pacific (Tokyo)", - }, - "ap-northeast-2": region{ - Description: "Asia Pacific (Seoul)", - }, - "ap-south-1": region{ - Description: "Asia Pacific (Mumbai)", - }, - "ap-southeast-1": region{ - Description: "Asia Pacific (Singapore)", - }, - "ap-southeast-2": region{ - Description: "Asia Pacific (Sydney)", - }, - "ca-central-1": region{ - Description: "Canada (Central)", - }, - "eu-central-1": region{ - Description: "EU (Frankfurt)", - }, - "eu-west-1": region{ - Description: "EU (Ireland)", - }, - "eu-west-2": region{ - Description: "EU (London)", - }, - "eu-west-3": region{ - Description: "EU (Paris)", - }, - "sa-east-1": region{ - Description: "South America (Sao Paulo)", - }, - "us-east-1": region{ - Description: "US East (N. Virginia)", - }, - "us-east-2": region{ - Description: "US East (Ohio)", - }, - "us-west-1": region{ - Description: "US West (N. California)", - }, - "us-west-2": region{ - Description: "US West (Oregon)", - }, - }, - Services: services{ - "a4b": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "acm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "acm-pca": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "api.mediatailor": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "api.pricing": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "pricing", - }, - }, - Endpoints: endpoints{ - "ap-south-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "api.sagemaker": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "apigateway": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "appstream2": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "appstream", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "athena": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "autoscaling-plans": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "autoscaling-plans", - }, - }, - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "batch": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "budgets": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "budgets.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "ce": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "ce.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cloud9": service{ - - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "clouddirectory": service{ - - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudfront": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "cloudfront.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cloudhsm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudhsmv2": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "cloudhsm", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudsearch": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codebuild": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-1-fips": endpoint{ - Hostname: "codebuild-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{}, - "us-east-2-fips": endpoint{ - Hostname: "codebuild-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{}, - "us-west-1-fips": endpoint{ - Hostname: "codebuild-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{}, - "us-west-2-fips": endpoint{ - Hostname: "codebuild-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "codecommit": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codepipeline": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codestar": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-identity": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-idp": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-sync": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "comprehend": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cur": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "datapipeline": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "dax": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "devicefarm": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "discovery": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "dms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ds": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "fips": endpoint{ - Hostname: "elasticache-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticfilesystem": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.{service}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elastictranscoder": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "email": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "entitlement.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "firehose": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "fms": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "gamelift": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "glue": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "greengrass": service{ - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "guardduty": service{ - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "health": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "iam.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "importexport": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "importexport.amazonaws.com", - SignatureVersions: []string{"v2", "v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - Service: "IngestionService", - }, - }, - }, - }, - "inspector": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "iot": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "iotanalytics": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesisanalytics": service{ - - Endpoints: endpoints{ - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesisvideo": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "lightsail": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "machinelearning": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "marketplacecommerceanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "mediaconvert": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "medialive": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mediapackage": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mediastore": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "metering.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mgh": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "mobileanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "models.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mturk-requester": service{ - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "sandbox": endpoint{ - Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", - }, - "us-east-1": endpoint{}, - }, - }, - "neptune": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{ - Hostname: "rds.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - "us-east-1": endpoint{ - Hostname: "rds.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{ - Hostname: "rds.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-2": endpoint{ - Hostname: "rds.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "opsworks": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "opsworks-cm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "organizations": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "organizations.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "pinpoint": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "mobiletargeting", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "polly": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "rekognition": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "resource-groups": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "route53.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "route53domains": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "runtime.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "runtime.sagemaker": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "s3": service{ - PartitionEndpoint: "us-east-1", - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - - HasDualStack: boxedTrue, - DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Hostname: "s3.ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{ - Hostname: "s3.ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ap-southeast-2": endpoint{ - Hostname: "s3.ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{ - Hostname: "s3.eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "s3-external-1": endpoint{ - Hostname: "s3-external-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{ - Hostname: "s3.sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-east-1": endpoint{ - Hostname: "s3.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{ - Hostname: "s3.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-west-2": endpoint{ - Hostname: "s3.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - }, - }, - "sdb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v2"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - Hostname: "sdb.amazonaws.com", - }, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "secretsmanager": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "serverlessrepo": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Protocols: []string{"https"}, - }, - "ap-northeast-2": endpoint{ - Protocols: []string{"https"}, - }, - "ap-south-1": endpoint{ - Protocols: []string{"https"}, - }, - "ap-southeast-1": endpoint{ - Protocols: []string{"https"}, - }, - "ap-southeast-2": endpoint{ - Protocols: []string{"https"}, - }, - "ca-central-1": endpoint{ - Protocols: []string{"https"}, - }, - "eu-central-1": endpoint{ - Protocols: []string{"https"}, - }, - "eu-west-1": endpoint{ - Protocols: []string{"https"}, - }, - "eu-west-2": endpoint{ - Protocols: []string{"https"}, - }, - "sa-east-1": endpoint{ - Protocols: []string{"https"}, - }, - "us-east-1": endpoint{ - Protocols: []string{"https"}, - }, - "us-east-2": endpoint{ - Protocols: []string{"https"}, - }, - "us-west-1": endpoint{ - Protocols: []string{"https"}, - }, - "us-west-2": endpoint{ - Protocols: []string{"https"}, - }, - }, - }, - "servicecatalog": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "servicediscovery": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "shield": service{ - IsRegionalized: boxedFalse, - Defaults: endpoint{ - SSLCommonName: "Shield.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sns": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "fips-us-east-1": endpoint{ - Hostname: "sqs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "fips-us-east-2": endpoint{ - Hostname: "sqs-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "fips-us-west-1": endpoint{ - Hostname: "sqs-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "fips-us-west-2": endpoint{ - Hostname: "sqs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "queue.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "states": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sts": service{ - PartitionEndpoint: "aws-global", - Defaults: endpoint{ - Hostname: "sts.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{ - Hostname: "sts.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "aws-global": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-1-fips": endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{}, - "us-east-2-fips": endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{}, - "us-west-1-fips": endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{}, - "us-west-2-fips": endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "support": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "translate": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "waf": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "waf.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "waf-regional": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workdocs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workmail": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workspaces": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "xray": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - }, -} - -// AwsCnPartition returns the Resolver for AWS China. -func AwsCnPartition() Partition { - return awscnPartition.Partition() -} - -var awscnPartition = partition{ - ID: "aws-cn", - Name: "AWS China", - DNSSuffix: "amazonaws.com.cn", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^cn\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "cn-north-1": region{ - Description: "China (Beijing)", - }, - "cn-northwest-1": region{ - Description: "China (Ningxia)", - }, - }, - Services: services{ - "apigateway": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com.cn", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "cognito-identity": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ds": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "cn-northwest-1": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-cn-global": endpoint{ - Hostname: "iam.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "iot": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "s3": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "sns": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "sts": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - }, -} - -// AwsUsGovPartition returns the Resolver for AWS GovCloud (US). -func AwsUsGovPartition() Partition { - return awsusgovPartition.Partition() -} - -var awsusgovPartition = partition{ - ID: "aws-us-gov", - Name: "AWS GovCloud (US)", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-gov\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "us-gov-west-1": region{ - Description: "AWS GovCloud (US)", - }, - }, - Services: services{ - "acm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "apigateway": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "autoscaling": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudhsm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudhsmv2": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "cloudhsm", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "dms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "dynamodb": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - "us-gov-west-1-fips": endpoint{ - Hostname: "dynamodb.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "ec2": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "fips": endpoint{ - Hostname: "elasticache-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - "us-gov-west-1": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "elasticmapreduce": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"https"}, - }, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "glacier": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-us-gov-global": endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "inspector": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "iot": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "kms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "metering.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "monitoring": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "polly": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "rekognition": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "s3": service{ - Defaults: endpoint{ - SignatureVersions: []string{"s3", "s3v4"}, - }, - Endpoints: endpoints{ - "fips-us-gov-west-1": endpoint{ - Hostname: "s3-fips-us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - "us-gov-west-1": endpoint{ - Hostname: "s3.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "sns": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "sqs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "states": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - "us-gov-west-1-fips": endpoint{ - Hostname: "dynamodb.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "sts": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "translate": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - }, -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go deleted file mode 100644 index 84316b9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package endpoints provides the types and functionality for defining regions -// and endpoints, as well as querying those definitions. -// -// The SDK's Regions and Endpoints metadata is code generated into the endpoints -// package, and is accessible via the DefaultResolver function. This function -// returns a endpoint Resolver will search the metadata and build an associated -// endpoint if one is found. The default resolver will search all partitions -// known by the SDK. e.g AWS Standard (aws), AWS China (aws-cn), and -// AWS GovCloud (US) (aws-us-gov). -// . -// -// Enumerating Regions and Endpoint Metadata -// -// Casting the Resolver returned by DefaultResolver to a EnumPartitions interface -// will allow you to get access to the list of underlying Partitions with the -// Partitions method. This is helpful if you want to limit the SDK's endpoint -// resolving to a single partition, or enumerate regions, services, and endpoints -// in the partition. -// -// resolver := endpoints.DefaultResolver() -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// -// for _, p := range partitions { -// fmt.Println("Regions for", p.ID()) -// for id, _ := range p.Regions() { -// fmt.Println("*", id) -// } -// -// fmt.Println("Services for", p.ID()) -// for id, _ := range p.Services() { -// fmt.Println("*", id) -// } -// } -// -// Using Custom Endpoints -// -// The endpoints package also gives you the ability to use your own logic how -// endpoints are resolved. This is a great way to define a custom endpoint -// for select services, without passing that logic down through your code. -// -// If a type implements the Resolver interface it can be used to resolve -// endpoints. To use this with the SDK's Session and Config set the value -// of the type to the EndpointsResolver field of aws.Config when initializing -// the session, or service client. -// -// In addition the ResolverFunc is a wrapper for a func matching the signature -// of Resolver.EndpointFor, converting it to a type that satisfies the -// Resolver interface. -// -// -// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { -// if service == endpoints.S3ServiceID { -// return endpoints.ResolvedEndpoint{ -// URL: "s3.custom.endpoint.com", -// SigningRegion: "custom-signing-region", -// }, nil -// } -// -// return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) -// } -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String("us-west-2"), -// EndpointResolver: endpoints.ResolverFunc(myCustomResolver), -// })) -package endpoints diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go deleted file mode 100644 index e29c095..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ /dev/null @@ -1,449 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Options provide the configuration needed to direct how the -// endpoints will be resolved. -type Options struct { - // DisableSSL forces the endpoint to be resolved as HTTP. - // instead of HTTPS if the service supports it. - DisableSSL bool - - // Sets the resolver to resolve the endpoint as a dualstack endpoint - // for the service. If dualstack support for a service is not known and - // StrictMatching is not enabled a dualstack endpoint for the service will - // be returned. This endpoint may not be valid. If StrictMatching is - // enabled only services that are known to support dualstack will return - // dualstack endpoints. - UseDualStack bool - - // Enables strict matching of services and regions resolved endpoints. - // If the partition doesn't enumerate the exact service and region an - // error will be returned. This option will prevent returning endpoints - // that look valid, but may not resolve to any real endpoint. - StrictMatching bool - - // Enables resolving a service endpoint based on the region provided if the - // service does not exist. The service endpoint ID will be used as the service - // domain name prefix. By default the endpoint resolver requires the service - // to be known when resolving endpoints. - // - // If resolving an endpoint on the partition list the provided region will - // be used to determine which partition's domain name pattern to the service - // endpoint ID with. If both the service and region are unkonwn and resolving - // the endpoint on partition list an UnknownEndpointError error will be returned. - // - // If resolving and endpoint on a partition specific resolver that partition's - // domain name pattern will be used with the service endpoint ID. If both - // region and service do not exist when resolving an endpoint on a specific - // partition the partition's domain pattern will be used to combine the - // endpoint and region together. - // - // This option is ignored if StrictMatching is enabled. - ResolveUnknownService bool -} - -// Set combines all of the option functions together. -func (o *Options) Set(optFns ...func(*Options)) { - for _, fn := range optFns { - fn(o) - } -} - -// DisableSSLOption sets the DisableSSL options. Can be used as a functional -// option when resolving endpoints. -func DisableSSLOption(o *Options) { - o.DisableSSL = true -} - -// UseDualStackOption sets the UseDualStack option. Can be used as a functional -// option when resolving endpoints. -func UseDualStackOption(o *Options) { - o.UseDualStack = true -} - -// StrictMatchingOption sets the StrictMatching option. Can be used as a functional -// option when resolving endpoints. -func StrictMatchingOption(o *Options) { - o.StrictMatching = true -} - -// ResolveUnknownServiceOption sets the ResolveUnknownService option. Can be used -// as a functional option when resolving endpoints. -func ResolveUnknownServiceOption(o *Options) { - o.ResolveUnknownService = true -} - -// A Resolver provides the interface for functionality to resolve endpoints. -// The build in Partition and DefaultResolver return value satisfy this interface. -type Resolver interface { - EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) -} - -// ResolverFunc is a helper utility that wraps a function so it satisfies the -// Resolver interface. This is useful when you want to add additional endpoint -// resolving logic, or stub out specific endpoints with custom values. -type ResolverFunc func(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) - -// EndpointFor wraps the ResolverFunc function to satisfy the Resolver interface. -func (fn ResolverFunc) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return fn(service, region, opts...) -} - -var schemeRE = regexp.MustCompile("^([^:]+)://") - -// AddScheme adds the HTTP or HTTPS schemes to a endpoint URL if there is no -// scheme. If disableSSL is true HTTP will set HTTP instead of the default HTTPS. -// -// If disableSSL is set, it will only set the URL's scheme if the URL does not -// contain a scheme. -func AddScheme(endpoint string, disableSSL bool) string { - if !schemeRE.MatchString(endpoint) { - scheme := "https" - if disableSSL { - scheme = "http" - } - endpoint = fmt.Sprintf("%s://%s", scheme, endpoint) - } - - return endpoint -} - -// EnumPartitions a provides a way to retrieve the underlying partitions that -// make up the SDK's default Resolver, or any resolver decoded from a model -// file. -// -// Use this interface with DefaultResolver and DecodeModels to get the list of -// Partitions. -type EnumPartitions interface { - Partitions() []Partition -} - -// RegionsForService returns a map of regions for the partition and service. -// If either the partition or service does not exist false will be returned -// as the second parameter. -// -// This example shows how to get the regions for DynamoDB in the AWS partition. -// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID) -// -// This is equivalent to using the partition directly. -// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions() -func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) { - for _, p := range ps { - if p.ID() != partitionID { - continue - } - if _, ok := p.p.Services[serviceID]; !ok { - break - } - - s := Service{ - id: serviceID, - p: p.p, - } - return s.Regions(), true - } - - return map[string]Region{}, false -} - -// PartitionForRegion returns the first partition which includes the region -// passed in. This includes both known regions and regions which match -// a pattern supported by the partition which may include regions that are -// not explicitly known by the partition. Use the Regions method of the -// returned Partition if explicit support is needed. -func PartitionForRegion(ps []Partition, regionID string) (Partition, bool) { - for _, p := range ps { - if _, ok := p.p.Regions[regionID]; ok || p.p.RegionRegex.MatchString(regionID) { - return p, true - } - } - - return Partition{}, false -} - -// A Partition provides the ability to enumerate the partition's regions -// and services. -type Partition struct { - id string - p *partition -} - -// ID returns the identifier of the partition. -func (p Partition) ID() string { return p.id } - -// EndpointFor attempts to resolve the endpoint based on service and region. -// See Options for information on configuring how the endpoint is resolved. -// -// If the service cannot be found in the metadata the UnknownServiceError -// error will be returned. This validation will occur regardless if -// StrictMatching is enabled. To enable resolving unknown services set the -// "ResolveUnknownService" option to true. When StrictMatching is disabled -// this option allows the partition resolver to resolve a endpoint based on -// the service endpoint ID provided. -// -// When resolving endpoints you can choose to enable StrictMatching. This will -// require the provided service and region to be known by the partition. -// If the endpoint cannot be strictly resolved an error will be returned. This -// mode is useful to ensure the endpoint resolved is valid. Without -// StrictMatching enabled the endpoint returned my look valid but may not work. -// StrictMatching requires the SDK to be updated if you want to take advantage -// of new regions and services expansions. -// -// Errors that can be returned. -// * UnknownServiceError -// * UnknownEndpointError -func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return p.p.EndpointFor(service, region, opts...) -} - -// Regions returns a map of Regions indexed by their ID. This is useful for -// enumerating over the regions in a partition. -func (p Partition) Regions() map[string]Region { - rs := map[string]Region{} - for id, r := range p.p.Regions { - rs[id] = Region{ - id: id, - desc: r.Description, - p: p.p, - } - } - - return rs -} - -// Services returns a map of Service indexed by their ID. This is useful for -// enumerating over the services in a partition. -func (p Partition) Services() map[string]Service { - ss := map[string]Service{} - for id := range p.p.Services { - ss[id] = Service{ - id: id, - p: p.p, - } - } - - return ss -} - -// A Region provides information about a region, and ability to resolve an -// endpoint from the context of a region, given a service. -type Region struct { - id, desc string - p *partition -} - -// ID returns the region's identifier. -func (r Region) ID() string { return r.id } - -// Description returns the region's description. The region description -// is free text, it can be empty, and it may change between SDK releases. -func (r Region) Description() string { return r.desc } - -// ResolveEndpoint resolves an endpoint from the context of the region given -// a service. See Partition.EndpointFor for usage and errors that can be returned. -func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return r.p.EndpointFor(service, r.id, opts...) -} - -// Services returns a list of all services that are known to be in this region. -func (r Region) Services() map[string]Service { - ss := map[string]Service{} - for id, s := range r.p.Services { - if _, ok := s.Endpoints[r.id]; ok { - ss[id] = Service{ - id: id, - p: r.p, - } - } - } - - return ss -} - -// A Service provides information about a service, and ability to resolve an -// endpoint from the context of a service, given a region. -type Service struct { - id string - p *partition -} - -// ID returns the identifier for the service. -func (s Service) ID() string { return s.id } - -// ResolveEndpoint resolves an endpoint from the context of a service given -// a region. See Partition.EndpointFor for usage and errors that can be returned. -func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return s.p.EndpointFor(s.id, region, opts...) -} - -// Regions returns a map of Regions that the service is present in. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Regions() map[string]Region { - rs := map[string]Region{} - for id := range s.p.Services[s.id].Endpoints { - if r, ok := s.p.Regions[id]; ok { - rs[id] = Region{ - id: id, - desc: r.Description, - p: s.p, - } - } - } - - return rs -} - -// Endpoints returns a map of Endpoints indexed by their ID for all known -// endpoints for a service. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Endpoints() map[string]Endpoint { - es := map[string]Endpoint{} - for id := range s.p.Services[s.id].Endpoints { - es[id] = Endpoint{ - id: id, - serviceID: s.id, - p: s.p, - } - } - - return es -} - -// A Endpoint provides information about endpoints, and provides the ability -// to resolve that endpoint for the service, and the region the endpoint -// represents. -type Endpoint struct { - id string - serviceID string - p *partition -} - -// ID returns the identifier for an endpoint. -func (e Endpoint) ID() string { return e.id } - -// ServiceID returns the identifier the endpoint belongs to. -func (e Endpoint) ServiceID() string { return e.serviceID } - -// ResolveEndpoint resolves an endpoint from the context of a service and -// region the endpoint represents. See Partition.EndpointFor for usage and -// errors that can be returned. -func (e Endpoint) ResolveEndpoint(opts ...func(*Options)) (ResolvedEndpoint, error) { - return e.p.EndpointFor(e.serviceID, e.id, opts...) -} - -// A ResolvedEndpoint is an endpoint that has been resolved based on a partition -// service, and region. -type ResolvedEndpoint struct { - // The endpoint URL - URL string - - // The region that should be used for signing requests. - SigningRegion string - - // The service name that should be used for signing requests. - SigningName string - - // States that the signing name for this endpoint was derived from metadata - // passed in, but was not explicitly modeled. - SigningNameDerived bool - - // The signing method that should be used for signing requests. - SigningMethod string -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError awserr.Error - -// A EndpointNotFoundError is returned when in StrictMatching mode, and the -// endpoint for the service and region cannot be found in any of the partitions. -type EndpointNotFoundError struct { - awsError - Partition string - Service string - Region string -} - -// A UnknownServiceError is returned when the service does not resolve to an -// endpoint. Includes a list of all known services for the partition. Returned -// when a partition does not support the service. -type UnknownServiceError struct { - awsError - Partition string - Service string - Known []string -} - -// NewUnknownServiceError builds and returns UnknownServiceError. -func NewUnknownServiceError(p, s string, known []string) UnknownServiceError { - return UnknownServiceError{ - awsError: awserr.New("UnknownServiceError", - "could not resolve endpoint for unknown service", nil), - Partition: p, - Service: s, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownServiceError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q", - e.Partition, e.Service) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownServiceError) String() string { - return e.Error() -} - -// A UnknownEndpointError is returned when in StrictMatching mode and the -// service is valid, but the region does not resolve to an endpoint. Includes -// a list of all known endpoints for the service. -type UnknownEndpointError struct { - awsError - Partition string - Service string - Region string - Known []string -} - -// NewUnknownEndpointError builds and returns UnknownEndpointError. -func NewUnknownEndpointError(p, s, r string, known []string) UnknownEndpointError { - return UnknownEndpointError{ - awsError: awserr.New("UnknownEndpointError", - "could not resolve endpoint", nil), - Partition: p, - Service: s, - Region: r, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q, region: %q", - e.Partition, e.Service, e.Region) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) String() string { - return e.Error() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go deleted file mode 100644 index ff6f76d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ /dev/null @@ -1,307 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -type partitions []partition - -func (ps partitions) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - var opt Options - opt.Set(opts...) - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(service, region, opt.StrictMatching) { - continue - } - - return ps[i].EndpointFor(service, region, opts...) - } - - // If loose matching fallback to first partition format to use - // when resolving the endpoint. - if !opt.StrictMatching && len(ps) > 0 { - return ps[0].EndpointFor(service, region, opts...) - } - - return ResolvedEndpoint{}, NewUnknownEndpointError("all partitions", service, region, []string{}) -} - -// Partitions satisfies the EnumPartitions interface and returns a list -// of Partitions representing each partition represented in the SDK's -// endpoints model. -func (ps partitions) Partitions() []Partition { - parts := make([]Partition, 0, len(ps)) - for i := 0; i < len(ps); i++ { - parts = append(parts, ps[i].Partition()) - } - - return parts -} - -type partition struct { - ID string `json:"partition"` - Name string `json:"partitionName"` - DNSSuffix string `json:"dnsSuffix"` - RegionRegex regionRegex `json:"regionRegex"` - Defaults endpoint `json:"defaults"` - Regions regions `json:"regions"` - Services services `json:"services"` -} - -func (p partition) Partition() Partition { - return Partition{ - id: p.ID, - p: &p, - } -} - -func (p partition) canResolveEndpoint(service, region string, strictMatch bool) bool { - s, hasService := p.Services[service] - _, hasEndpoint := s.Endpoints[region] - - if hasEndpoint && hasService { - return true - } - - if strictMatch { - return false - } - - return p.RegionRegex.MatchString(region) -} - -func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (resolved ResolvedEndpoint, err error) { - var opt Options - opt.Set(opts...) - - s, hasService := p.Services[service] - if !(hasService || opt.ResolveUnknownService) { - // Only return error if the resolver will not fallback to creating - // endpoint based on service endpoint ID passed in. - return resolved, NewUnknownServiceError(p.ID, service, serviceList(p.Services)) - } - - e, hasEndpoint := s.endpointForRegion(region) - if !hasEndpoint && opt.StrictMatching { - return resolved, NewUnknownEndpointError(p.ID, service, region, endpointList(s.Endpoints)) - } - - defs := []endpoint{p.Defaults, s.Defaults} - return e.resolve(service, region, p.DNSSuffix, defs, opt), nil -} - -func serviceList(ss services) []string { - list := make([]string, 0, len(ss)) - for k := range ss { - list = append(list, k) - } - return list -} -func endpointList(es endpoints) []string { - list := make([]string, 0, len(es)) - for k := range es { - list = append(list, k) - } - return list -} - -type regionRegex struct { - *regexp.Regexp -} - -func (rr *regionRegex) UnmarshalJSON(b []byte) (err error) { - // Strip leading and trailing quotes - regex, err := strconv.Unquote(string(b)) - if err != nil { - return fmt.Errorf("unable to strip quotes from regex, %v", err) - } - - rr.Regexp, err = regexp.Compile(regex) - if err != nil { - return fmt.Errorf("unable to unmarshal region regex, %v", err) - } - return nil -} - -type regions map[string]region - -type region struct { - Description string `json:"description"` -} - -type services map[string]service - -type service struct { - PartitionEndpoint string `json:"partitionEndpoint"` - IsRegionalized boxedBool `json:"isRegionalized,omitempty"` - Defaults endpoint `json:"defaults"` - Endpoints endpoints `json:"endpoints"` -} - -func (s *service) endpointForRegion(region string) (endpoint, bool) { - if s.IsRegionalized == boxedFalse { - return s.Endpoints[s.PartitionEndpoint], region == s.PartitionEndpoint - } - - if e, ok := s.Endpoints[region]; ok { - return e, true - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return endpoint{}, false -} - -type endpoints map[string]endpoint - -type endpoint struct { - Hostname string `json:"hostname"` - Protocols []string `json:"protocols"` - CredentialScope credentialScope `json:"credentialScope"` - - // Custom fields not modeled - HasDualStack boxedBool `json:"-"` - DualStackHostname string `json:"-"` - - // Signature Version not used - SignatureVersions []string `json:"signatureVersions"` - - // SSLCommonName not used. - SSLCommonName string `json:"sslCommonName"` -} - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4", "v2"} -) - -func getByPriority(s []string, p []string, def string) string { - if len(s) == 0 { - return def - } - - for i := 0; i < len(p); i++ { - for j := 0; j < len(s); j++ { - if s[j] == p[i] { - return s[j] - } - } - } - - return s[0] -} - -func (e endpoint) resolve(service, region, dnsSuffix string, defs []endpoint, opts Options) ResolvedEndpoint { - var merged endpoint - for _, def := range defs { - merged.mergeIn(def) - } - merged.mergeIn(e) - e = merged - - hostname := e.Hostname - - // Offset the hostname for dualstack if enabled - if opts.UseDualStack && e.HasDualStack == boxedTrue { - hostname = e.DualStackHostname - } - - u := strings.Replace(hostname, "{service}", service, 1) - u = strings.Replace(u, "{region}", region, 1) - u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1) - - scheme := getEndpointScheme(e.Protocols, opts.DisableSSL) - u = fmt.Sprintf("%s://%s", scheme, u) - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - - signingName := e.CredentialScope.Service - var signingNameDerived bool - if len(signingName) == 0 { - signingName = service - signingNameDerived = true - } - - return ResolvedEndpoint{ - URL: u, - SigningRegion: signingRegion, - SigningName: signingName, - SigningNameDerived: signingNameDerived, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - } -} - -func getEndpointScheme(protocols []string, disableSSL bool) string { - if disableSSL { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func (e *endpoint) mergeIn(other endpoint) { - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } - if len(other.CredentialScope.Region) > 0 { - e.CredentialScope.Region = other.CredentialScope.Region - } - if len(other.CredentialScope.Service) > 0 { - e.CredentialScope.Service = other.CredentialScope.Service - } - if len(other.SSLCommonName) > 0 { - e.SSLCommonName = other.SSLCommonName - } - if other.HasDualStack != boxedBoolUnset { - e.HasDualStack = other.HasDualStack - } - if len(other.DualStackHostname) > 0 { - e.DualStackHostname = other.DualStackHostname - } -} - -type credentialScope struct { - Region string `json:"region"` - Service string `json:"service"` -} - -type boxedBool int - -func (b *boxedBool) UnmarshalJSON(buf []byte) error { - v, err := strconv.ParseBool(string(buf)) - if err != nil { - return err - } - - if v { - *b = boxedTrue - } else { - *b = boxedFalse - } - - return nil -} - -const ( - boxedBoolUnset boxedBool = iota - boxedFalse - boxedTrue -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go deleted file mode 100644 index 05e92df..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ /dev/null @@ -1,337 +0,0 @@ -// +build codegen - -package endpoints - -import ( - "fmt" - "io" - "reflect" - "strings" - "text/template" - "unicode" -) - -// A CodeGenOptions are the options for code generating the endpoints into -// Go code from the endpoints model definition. -type CodeGenOptions struct { - // Options for how the model will be decoded. - DecodeModelOptions DecodeModelOptions -} - -// Set combines all of the option functions together -func (d *CodeGenOptions) Set(optFns ...func(*CodeGenOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// CodeGenModel given a endpoints model file will decode it and attempt to -// generate Go code from the model definition. Error will be returned if -// the code is unable to be generated, or decoded. -func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGenOptions)) error { - var opts CodeGenOptions - opts.Set(optFns...) - - resolver, err := DecodeModel(modelFile, func(d *DecodeModelOptions) { - *d = opts.DecodeModelOptions - }) - if err != nil { - return err - } - - tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl)) - if err := tmpl.ExecuteTemplate(outFile, "defaults", resolver); err != nil { - return fmt.Errorf("failed to execute template, %v", err) - } - - return nil -} - -func toSymbol(v string) string { - out := []rune{} - for _, c := range strings.Title(v) { - if !(unicode.IsNumber(c) || unicode.IsLetter(c)) { - continue - } - - out = append(out, c) - } - - return string(out) -} - -func quoteString(v string) string { - return fmt.Sprintf("%q", v) -} - -func regionConstName(p, r string) string { - return toSymbol(p) + toSymbol(r) -} - -func partitionGetter(id string) string { - return fmt.Sprintf("%sPartition", toSymbol(id)) -} - -func partitionVarName(id string) string { - return fmt.Sprintf("%sPartition", strings.ToLower(toSymbol(id))) -} - -func listPartitionNames(ps partitions) string { - names := []string{} - switch len(ps) { - case 1: - return ps[0].Name - case 2: - return fmt.Sprintf("%s and %s", ps[0].Name, ps[1].Name) - default: - for i, p := range ps { - if i == len(ps)-1 { - names = append(names, "and "+p.Name) - } else { - names = append(names, p.Name) - } - } - return strings.Join(names, ", ") - } -} - -func boxedBoolIfSet(msg string, v boxedBool) string { - switch v { - case boxedTrue: - return fmt.Sprintf(msg, "boxedTrue") - case boxedFalse: - return fmt.Sprintf(msg, "boxedFalse") - default: - return "" - } -} - -func stringIfSet(msg, v string) string { - if len(v) == 0 { - return "" - } - - return fmt.Sprintf(msg, v) -} - -func stringSliceIfSet(msg string, vs []string) string { - if len(vs) == 0 { - return "" - } - - names := []string{} - for _, v := range vs { - names = append(names, `"`+v+`"`) - } - - return fmt.Sprintf(msg, strings.Join(names, ",")) -} - -func endpointIsSet(v endpoint) bool { - return !reflect.DeepEqual(v, endpoint{}) -} - -func serviceSet(ps partitions) map[string]struct{} { - set := map[string]struct{}{} - for _, p := range ps { - for id := range p.Services { - set[id] = struct{}{} - } - } - - return set -} - -var funcMap = template.FuncMap{ - "ToSymbol": toSymbol, - "QuoteString": quoteString, - "RegionConst": regionConstName, - "PartitionGetter": partitionGetter, - "PartitionVarName": partitionVarName, - "ListPartitionNames": listPartitionNames, - "BoxedBoolIfSet": boxedBoolIfSet, - "StringIfSet": stringIfSet, - "StringSliceIfSet": stringSliceIfSet, - "EndpointIsSet": endpointIsSet, - "ServicesSet": serviceSet, -} - -const v3Tmpl = ` -{{ define "defaults" -}} -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - - {{ template "partition consts" . }} - - {{ range $_, $partition := . }} - {{ template "partition region consts" $partition }} - {{ end }} - - {{ template "service consts" . }} - - {{ template "endpoint resolvers" . }} -{{- end }} - -{{ define "partition consts" }} - // Partition identifiers - const ( - {{ range $_, $p := . -}} - {{ ToSymbol $p.ID }}PartitionID = {{ QuoteString $p.ID }} // {{ $p.Name }} partition. - {{ end -}} - ) -{{- end }} - -{{ define "partition region consts" }} - // {{ .Name }} partition's regions. - const ( - {{ range $id, $region := .Regions -}} - {{ ToSymbol $id }}RegionID = {{ QuoteString $id }} // {{ $region.Description }}. - {{ end -}} - ) -{{- end }} - -{{ define "service consts" }} - // Service identifiers - const ( - {{ $serviceSet := ServicesSet . -}} - {{ range $id, $_ := $serviceSet -}} - {{ ToSymbol $id }}ServiceID = {{ QuoteString $id }} // {{ ToSymbol $id }}. - {{ end -}} - ) -{{- end }} - -{{ define "endpoint resolvers" }} - // DefaultResolver returns an Endpoint resolver that will be able - // to resolve endpoints for: {{ ListPartitionNames . }}. - // - // Use DefaultPartitions() to get the list of the default partitions. - func DefaultResolver() Resolver { - return defaultPartitions - } - - // DefaultPartitions returns a list of the partitions the SDK is bundled - // with. The available partitions are: {{ ListPartitionNames . }}. - // - // partitions := endpoints.DefaultPartitions - // for _, p := range partitions { - // // ... inspect partitions - // } - func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() - } - - var defaultPartitions = partitions{ - {{ range $_, $partition := . -}} - {{ PartitionVarName $partition.ID }}, - {{ end }} - } - - {{ range $_, $partition := . -}} - {{ $name := PartitionGetter $partition.ID -}} - // {{ $name }} returns the Resolver for {{ $partition.Name }}. - func {{ $name }}() Partition { - return {{ PartitionVarName $partition.ID }}.Partition() - } - var {{ PartitionVarName $partition.ID }} = {{ template "gocode Partition" $partition }} - {{ end }} -{{ end }} - -{{ define "default partitions" }} - func DefaultPartitions() []Partition { - return []partition{ - {{ range $_, $partition := . -}} - // {{ ToSymbol $partition.ID}}Partition(), - {{ end }} - } - } -{{ end }} - -{{ define "gocode Partition" -}} -partition{ - {{ StringIfSet "ID: %q,\n" .ID -}} - {{ StringIfSet "Name: %q,\n" .Name -}} - {{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}} - RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }}, - {{ if EndpointIsSet .Defaults -}} - Defaults: {{ template "gocode Endpoint" .Defaults }}, - {{- end }} - Regions: {{ template "gocode Regions" .Regions }}, - Services: {{ template "gocode Services" .Services }}, -} -{{- end }} - -{{ define "gocode RegionRegex" -}} -regionRegex{ - Regexp: func() *regexp.Regexp{ - reg, _ := regexp.Compile({{ QuoteString .Regexp.String }}) - return reg - }(), -} -{{- end }} - -{{ define "gocode Regions" -}} -regions{ - {{ range $id, $region := . -}} - "{{ $id }}": {{ template "gocode Region" $region }}, - {{ end -}} -} -{{- end }} - -{{ define "gocode Region" -}} -region{ - {{ StringIfSet "Description: %q,\n" .Description -}} -} -{{- end }} - -{{ define "gocode Services" -}} -services{ - {{ range $id, $service := . -}} - "{{ $id }}": {{ template "gocode Service" $service }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Service" -}} -service{ - {{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}} - {{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}} - {{ if EndpointIsSet .Defaults -}} - Defaults: {{ template "gocode Endpoint" .Defaults -}}, - {{- end }} - {{ if .Endpoints -}} - Endpoints: {{ template "gocode Endpoints" .Endpoints }}, - {{- end }} -} -{{- end }} - -{{ define "gocode Endpoints" -}} -endpoints{ - {{ range $id, $endpoint := . -}} - "{{ $id }}": {{ template "gocode Endpoint" $endpoint }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Endpoint" -}} -endpoint{ - {{ StringIfSet "Hostname: %q,\n" .Hostname -}} - {{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}} - {{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}} - {{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}} - {{ if or .CredentialScope.Region .CredentialScope.Service -}} - CredentialScope: credentialScope{ - {{ StringIfSet "Region: %q,\n" .CredentialScope.Region -}} - {{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}} - }, - {{- end }} - {{ BoxedBoolIfSet "HasDualStack: %s,\n" .HasDualStack -}} - {{ StringIfSet "DualStackHostname: %q,\n" .DualStackHostname -}} - -} -{{- end }} -` diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/errors.go deleted file mode 100644 index 5766361..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -package aws - -import "github.com/aws/aws-sdk-go/aws/awserr" - -var ( - // ErrMissingRegion is an error that is returned if region configuration is - // not found. - // - // @readonly - ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) - - // ErrMissingEndpoint is an error that is returned if an endpoint cannot be - // resolved for a service. - // - // @readonly - ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go deleted file mode 100644 index 91a6f27..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go +++ /dev/null @@ -1,12 +0,0 @@ -package aws - -// JSONValue is a representation of a grab bag type that will be marshaled -// into a json string. This type can be used just like any other map. -// -// Example: -// -// values := aws.JSONValue{ -// "Foo": "Bar", -// } -// values["Baz"] = "Qux" -type JSONValue map[string]interface{} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/logger.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/logger.go deleted file mode 100644 index 6ed15b2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/logger.go +++ /dev/null @@ -1,118 +0,0 @@ -package aws - -import ( - "log" - "os" -) - -// A LogLevelType defines the level logging should be performed at. Used to instruct -// the SDK which statements should be logged. -type LogLevelType uint - -// LogLevel returns the pointer to a LogLevel. Should be used to workaround -// not being able to take the address of a non-composite literal. -func LogLevel(l LogLevelType) *LogLevelType { - return &l -} - -// Value returns the LogLevel value or the default value LogOff if the LogLevel -// is nil. Safe to use on nil value LogLevelTypes. -func (l *LogLevelType) Value() LogLevelType { - if l != nil { - return *l - } - return LogOff -} - -// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be -// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If -// LogLevel is nil, will default to LogOff comparison. -func (l *LogLevelType) Matches(v LogLevelType) bool { - c := l.Value() - return c&v == v -} - -// AtLeast returns true if this LogLevel is at least high enough to satisfies v. -// Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default -// to LogOff comparison. -func (l *LogLevelType) AtLeast(v LogLevelType) bool { - c := l.Value() - return c >= v -} - -const ( - // LogOff states that no logging should be performed by the SDK. This is the - // default state of the SDK, and should be use to disable all logging. - LogOff LogLevelType = iota * 0x1000 - - // LogDebug state that debug output should be logged by the SDK. This should - // be used to inspect request made and responses received. - LogDebug -) - -// Debug Logging Sub Levels -const ( - // LogDebugWithSigning states that the SDK should log request signing and - // presigning events. This should be used to log the signing details of - // requests for debugging. Will also enable LogDebug. - LogDebugWithSigning LogLevelType = LogDebug | (1 << iota) - - // LogDebugWithHTTPBody states the SDK should log HTTP request and response - // HTTP bodys in addition to the headers and path. This should be used to - // see the body content of requests and responses made while using the SDK - // Will also enable LogDebug. - LogDebugWithHTTPBody - - // LogDebugWithRequestRetries states the SDK should log when service requests will - // be retried. This should be used to log when you want to log when service - // requests are being retried. Will also enable LogDebug. - LogDebugWithRequestRetries - - // LogDebugWithRequestErrors states the SDK should log when service requests fail - // to build, send, validate, or unmarshal. - LogDebugWithRequestErrors - - // LogDebugWithEventStreamBody states the SDK should log EventStream - // request and response bodys. This should be used to log the EventStream - // wire unmarshaled message content of requests and responses made while - // using the SDK Will also enable LogDebug. - LogDebugWithEventStreamBody -) - -// A Logger is a minimalistic interface for the SDK to log messages to. Should -// be used to provide custom logging writers for the SDK to use. -type Logger interface { - Log(...interface{}) -} - -// A LoggerFunc is a convenience type to convert a function taking a variadic -// list of arguments and wrap it so the Logger interface can be used. -// -// Example: -// s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { -// fmt.Fprintln(os.Stdout, args...) -// })}) -type LoggerFunc func(...interface{}) - -// Log calls the wrapped function with the arguments provided -func (f LoggerFunc) Log(args ...interface{}) { - f(args...) -} - -// NewDefaultLogger returns a Logger which will write log messages to stdout, and -// use same formatting runes as the stdlib log.Logger -func NewDefaultLogger() Logger { - return &defaultLogger{ - logger: log.New(os.Stdout, "", log.LstdFlags), - } -} - -// A defaultLogger provides a minimalistic logger satisfying the Logger interface. -type defaultLogger struct { - logger *log.Logger -} - -// Log logs the parameters to the stdlib logger. See log.Println. -func (l defaultLogger) Log(args ...interface{}) { - l.logger.Println(args...) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go deleted file mode 100644 index 271da43..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !appengine,!plan9 - -package request - -import ( - "net" - "os" - "syscall" -) - -func isErrConnectionReset(err error) bool { - if opErr, ok := err.(*net.OpError); ok { - if sysErr, ok := opErr.Err.(*os.SyscallError); ok { - return sysErr.Err == syscall.ECONNRESET - } - } - - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go deleted file mode 100644 index daf9eca..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build appengine plan9 - -package request - -import ( - "strings" -) - -func isErrConnectionReset(err error) bool { - return strings.Contains(err.Error(), "connection reset") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go deleted file mode 100644 index 605a72d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ /dev/null @@ -1,274 +0,0 @@ -package request - -import ( - "fmt" - "strings" -) - -// A Handlers provides a collection of request handlers for various -// stages of handling requests. -type Handlers struct { - Validate HandlerList - Build HandlerList - Sign HandlerList - Send HandlerList - ValidateResponse HandlerList - Unmarshal HandlerList - UnmarshalStream HandlerList - UnmarshalMeta HandlerList - UnmarshalError HandlerList - Retry HandlerList - AfterRetry HandlerList - Complete HandlerList -} - -// Copy returns of this handler's lists. -func (h *Handlers) Copy() Handlers { - return Handlers{ - Validate: h.Validate.copy(), - Build: h.Build.copy(), - Sign: h.Sign.copy(), - Send: h.Send.copy(), - ValidateResponse: h.ValidateResponse.copy(), - Unmarshal: h.Unmarshal.copy(), - UnmarshalStream: h.UnmarshalStream.copy(), - UnmarshalError: h.UnmarshalError.copy(), - UnmarshalMeta: h.UnmarshalMeta.copy(), - Retry: h.Retry.copy(), - AfterRetry: h.AfterRetry.copy(), - Complete: h.Complete.copy(), - } -} - -// Clear removes callback functions for all handlers -func (h *Handlers) Clear() { - h.Validate.Clear() - h.Build.Clear() - h.Send.Clear() - h.Sign.Clear() - h.Unmarshal.Clear() - h.UnmarshalStream.Clear() - h.UnmarshalMeta.Clear() - h.UnmarshalError.Clear() - h.ValidateResponse.Clear() - h.Retry.Clear() - h.AfterRetry.Clear() - h.Complete.Clear() -} - -// A HandlerListRunItem represents an entry in the HandlerList which -// is being run. -type HandlerListRunItem struct { - Index int - Handler NamedHandler - Request *Request -} - -// A HandlerList manages zero or more handlers in a list. -type HandlerList struct { - list []NamedHandler - - // Called after each request handler in the list is called. If set - // and the func returns true the HandlerList will continue to iterate - // over the request handlers. If false is returned the HandlerList - // will stop iterating. - // - // Should be used if extra logic to be performed between each handler - // in the list. This can be used to terminate a list's iteration - // based on a condition such as error like, HandlerListStopOnError. - // Or for logging like HandlerListLogItem. - AfterEachFn func(item HandlerListRunItem) bool -} - -// A NamedHandler is a struct that contains a name and function callback. -type NamedHandler struct { - Name string - Fn func(*Request) -} - -// copy creates a copy of the handler list. -func (l *HandlerList) copy() HandlerList { - n := HandlerList{ - AfterEachFn: l.AfterEachFn, - } - if len(l.list) == 0 { - return n - } - - n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) - return n -} - -// Clear clears the handler list. -func (l *HandlerList) Clear() { - l.list = l.list[0:0] -} - -// Len returns the number of handlers in the list. -func (l *HandlerList) Len() int { - return len(l.list) -} - -// PushBack pushes handler f to the back of the handler list. -func (l *HandlerList) PushBack(f func(*Request)) { - l.PushBackNamed(NamedHandler{"__anonymous", f}) -} - -// PushBackNamed pushes named handler f to the back of the handler list. -func (l *HandlerList) PushBackNamed(n NamedHandler) { - if cap(l.list) == 0 { - l.list = make([]NamedHandler, 0, 5) - } - l.list = append(l.list, n) -} - -// PushFront pushes handler f to the front of the handler list. -func (l *HandlerList) PushFront(f func(*Request)) { - l.PushFrontNamed(NamedHandler{"__anonymous", f}) -} - -// PushFrontNamed pushes named handler f to the front of the handler list. -func (l *HandlerList) PushFrontNamed(n NamedHandler) { - if cap(l.list) == len(l.list) { - // Allocating new list required - l.list = append([]NamedHandler{n}, l.list...) - } else { - // Enough room to prepend into list. - l.list = append(l.list, NamedHandler{}) - copy(l.list[1:], l.list) - l.list[0] = n - } -} - -// Remove removes a NamedHandler n -func (l *HandlerList) Remove(n NamedHandler) { - l.RemoveByName(n.Name) -} - -// RemoveByName removes a NamedHandler by name. -func (l *HandlerList) RemoveByName(name string) { - for i := 0; i < len(l.list); i++ { - m := l.list[i] - if m.Name == name { - // Shift array preventing creating new arrays - copy(l.list[i:], l.list[i+1:]) - l.list[len(l.list)-1] = NamedHandler{} - l.list = l.list[:len(l.list)-1] - - // decrement list so next check to length is correct - i-- - } - } -} - -// SwapNamed will swap out any existing handlers with the same name as the -// passed in NamedHandler returning true if handlers were swapped. False is -// returned otherwise. -func (l *HandlerList) SwapNamed(n NamedHandler) (swapped bool) { - for i := 0; i < len(l.list); i++ { - if l.list[i].Name == n.Name { - l.list[i].Fn = n.Fn - swapped = true - } - } - - return swapped -} - -// Swap will swap out all handlers matching the name passed in. The matched -// handlers will be swapped in. True is returned if the handlers were swapped. -func (l *HandlerList) Swap(name string, replace NamedHandler) bool { - var swapped bool - - for i := 0; i < len(l.list); i++ { - if l.list[i].Name == name { - l.list[i] = replace - swapped = true - } - } - - return swapped -} - -// SetBackNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the end of the list. -func (l *HandlerList) SetBackNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushBackNamed(n) - } -} - -// SetFrontNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the beginning of -// the list. -func (l *HandlerList) SetFrontNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushFrontNamed(n) - } -} - -// Run executes all handlers in the list with a given request object. -func (l *HandlerList) Run(r *Request) { - for i, h := range l.list { - h.Fn(r) - item := HandlerListRunItem{ - Index: i, Handler: h, Request: r, - } - if l.AfterEachFn != nil && !l.AfterEachFn(item) { - return - } - } -} - -// HandlerListLogItem logs the request handler and the state of the -// request's Error value. Always returns true to continue iterating -// request handlers in a HandlerList. -func HandlerListLogItem(item HandlerListRunItem) bool { - if item.Request.Config.Logger == nil { - return true - } - item.Request.Config.Logger.Log("DEBUG: RequestHandler", - item.Index, item.Handler.Name, item.Request.Error) - - return true -} - -// HandlerListStopOnError returns false to stop the HandlerList iterating -// over request handlers if Request.Error is not nil. True otherwise -// to continue iterating. -func HandlerListStopOnError(item HandlerListRunItem) bool { - return item.Request.Error == nil -} - -// WithAppendUserAgent will add a string to the user agent prefixed with a -// single white space. -func WithAppendUserAgent(s string) Option { - return func(r *Request) { - r.Handlers.Build.PushBack(func(r2 *Request) { - AddToUserAgent(r, s) - }) - } -} - -// MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request -// header. If the extra parameters are provided they will be added as metadata to the -// name/version pair resulting in the following format. -// "name/version (extra0; extra1; ...)" -// The user agent part will be concatenated with this current request's user agent string. -func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request) { - ua := fmt.Sprintf("%s/%s", name, version) - if len(extra) > 0 { - ua += fmt.Sprintf(" (%s)", strings.Join(extra, "; ")) - } - return func(r *Request) { - AddToUserAgent(r, ua) - } -} - -// MakeAddToUserAgentFreeFormHandler adds the input to the User-Agent request header. -// The input string will be concatenated with the current request's user agent string. -func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) { - return func(r *Request) { - AddToUserAgent(r, s) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go deleted file mode 100644 index 79f7960..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go +++ /dev/null @@ -1,24 +0,0 @@ -package request - -import ( - "io" - "net/http" - "net/url" -) - -func copyHTTPRequest(r *http.Request, body io.ReadCloser) *http.Request { - req := new(http.Request) - *req = *r - req.URL = &url.URL{} - *req.URL = *r.URL - req.Body = body - - req.Header = http.Header{} - for k, v := range r.Header { - for _, vv := range v { - req.Header.Add(k, vv) - } - } - - return req -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go deleted file mode 100644 index b0c2ef4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go +++ /dev/null @@ -1,60 +0,0 @@ -package request - -import ( - "io" - "sync" - - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -// offsetReader is a thread-safe io.ReadCloser to prevent racing -// with retrying requests -type offsetReader struct { - buf io.ReadSeeker - lock sync.Mutex - closed bool -} - -func newOffsetReader(buf io.ReadSeeker, offset int64) *offsetReader { - reader := &offsetReader{} - buf.Seek(offset, sdkio.SeekStart) - - reader.buf = buf - return reader -} - -// Close will close the instance of the offset reader's access to -// the underlying io.ReadSeeker. -func (o *offsetReader) Close() error { - o.lock.Lock() - defer o.lock.Unlock() - o.closed = true - return nil -} - -// Read is a thread-safe read of the underlying io.ReadSeeker -func (o *offsetReader) Read(p []byte) (int, error) { - o.lock.Lock() - defer o.lock.Unlock() - - if o.closed { - return 0, io.EOF - } - - return o.buf.Read(p) -} - -// Seek is a thread-safe seeking operation. -func (o *offsetReader) Seek(offset int64, whence int) (int64, error) { - o.lock.Lock() - defer o.lock.Unlock() - - return o.buf.Seek(offset, whence) -} - -// CloseAndCopy will return a new offsetReader with a copy of the old buffer -// and close the old buffer. -func (o *offsetReader) CloseAndCopy(offset int64) *offsetReader { - o.Close() - return newOffsetReader(o.buf, offset) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request.go deleted file mode 100644 index 75f0fe0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ /dev/null @@ -1,657 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - "io" - "net" - "net/http" - "net/url" - "reflect" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -const ( - // ErrCodeSerialization is the serialization error code that is received - // during protocol unmarshaling. - ErrCodeSerialization = "SerializationError" - - // ErrCodeRead is an error that is returned during HTTP reads. - ErrCodeRead = "ReadError" - - // ErrCodeResponseTimeout is the connection timeout error that is received - // during body reads. - ErrCodeResponseTimeout = "ResponseTimeout" - - // ErrCodeInvalidPresignExpire is returned when the expire time provided to - // presign is invalid - ErrCodeInvalidPresignExpire = "InvalidPresignExpireError" - - // CanceledErrorCode is the error code that will be returned by an - // API request that was canceled. Requests given a aws.Context may - // return this error when canceled. - CanceledErrorCode = "RequestCanceled" -) - -// A Request is the service request to be made. -type Request struct { - Config aws.Config - ClientInfo metadata.ClientInfo - Handlers Handlers - - Retryer - AttemptTime time.Time - Time time.Time - Operation *Operation - HTTPRequest *http.Request - HTTPResponse *http.Response - Body io.ReadSeeker - BodyStart int64 // offset from beginning of Body that the request body starts - Params interface{} - Error error - Data interface{} - RequestID string - RetryCount int - Retryable *bool - RetryDelay time.Duration - NotHoist bool - SignedHeaderVals http.Header - LastSignedAt time.Time - DisableFollowRedirects bool - - // A value greater than 0 instructs the request to be signed as Presigned URL - // You should not set this field directly. Instead use Request's - // Presign or PresignRequest methods. - ExpireTime time.Duration - - context aws.Context - - built bool - - // Need to persist an intermediate body between the input Body and HTTP - // request body because the HTTP Client's transport can maintain a reference - // to the HTTP request's body after the client has returned. This value is - // safe to use concurrently and wrap the input Body for each HTTP request. - safeBody *offsetReader -} - -// An Operation is the service API operation to be made. -type Operation struct { - Name string - HTTPMethod string - HTTPPath string - *Paginator - - BeforePresignFn func(r *Request) error -} - -// New returns a new Request pointer for the service API -// operation and parameters. -// -// Params is any value of input parameters to be the request payload. -// Data is pointer value to an object which the request's response -// payload will be deserialized to. -func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, - retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { - - method := operation.HTTPMethod - if method == "" { - method = "POST" - } - - httpReq, _ := http.NewRequest(method, "", nil) - - var err error - httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath) - if err != nil { - httpReq.URL = &url.URL{} - err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) - } - - SanitizeHostForHeader(httpReq) - - r := &Request{ - Config: cfg, - ClientInfo: clientInfo, - Handlers: handlers.Copy(), - - Retryer: retryer, - AttemptTime: time.Now(), - Time: time.Now(), - ExpireTime: 0, - Operation: operation, - HTTPRequest: httpReq, - Body: nil, - Params: params, - Error: err, - Data: data, - } - r.SetBufferBody([]byte{}) - - return r -} - -// A Option is a functional option that can augment or modify a request when -// using a WithContext API operation method. -type Option func(*Request) - -// WithGetResponseHeader builds a request Option which will retrieve a single -// header value from the HTTP Response. If there are multiple values for the -// header key use WithGetResponseHeaders instead to access the http.Header -// map directly. The passed in val pointer must be non-nil. -// -// This Option can be used multiple times with a single API operation. -// -// var id2, versionID string -// svc.PutObjectWithContext(ctx, params, -// request.WithGetResponseHeader("x-amz-id-2", &id2), -// request.WithGetResponseHeader("x-amz-version-id", &versionID), -// ) -func WithGetResponseHeader(key string, val *string) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *val = req.HTTPResponse.Header.Get(key) - }) - } -} - -// WithGetResponseHeaders builds a request Option which will retrieve the -// headers from the HTTP response and assign them to the passed in headers -// variable. The passed in headers pointer must be non-nil. -// -// var headers http.Header -// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) -func WithGetResponseHeaders(headers *http.Header) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *headers = req.HTTPResponse.Header - }) - } -} - -// WithLogLevel is a request option that will set the request to use a specific -// log level when the request is made. -// -// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody) -func WithLogLevel(l aws.LogLevelType) Option { - return func(r *Request) { - r.Config.LogLevel = aws.LogLevel(l) - } -} - -// ApplyOptions will apply each option to the request calling them in the order -// the were provided. -func (r *Request) ApplyOptions(opts ...Option) { - for _, opt := range opts { - opt(r) - } -} - -// Context will always returns a non-nil context. If Request does not have a -// context aws.BackgroundContext will be returned. -func (r *Request) Context() aws.Context { - if r.context != nil { - return r.context - } - return aws.BackgroundContext() -} - -// SetContext adds a Context to the current request that can be used to cancel -// a in-flight request. The Context value must not be nil, or this method will -// panic. -// -// Unlike http.Request.WithContext, SetContext does not return a copy of the -// Request. It is not safe to use use a single Request value for multiple -// requests. A new Request should be created for each API operation request. -// -// Go 1.6 and below: -// The http.Request's Cancel field will be set to the Done() value of -// the context. This will overwrite the Cancel field's value. -// -// Go 1.7 and above: -// The http.Request.WithContext will be used to set the context on the underlying -// http.Request. This will create a shallow copy of the http.Request. The SDK -// may create sub contexts in the future for nested requests such as retries. -func (r *Request) SetContext(ctx aws.Context) { - if ctx == nil { - panic("context cannot be nil") - } - setRequestContext(r, ctx) -} - -// WillRetry returns if the request's can be retried. -func (r *Request) WillRetry() bool { - if !aws.IsReaderSeekable(r.Body) && r.HTTPRequest.Body != NoBody { - return false - } - return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() -} - -// ParamsFilled returns if the request's parameters have been populated -// and the parameters are valid. False is returned if no parameters are -// provided or invalid. -func (r *Request) ParamsFilled() bool { - return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid() -} - -// DataFilled returns true if the request's data for response deserialization -// target has been set and is a valid. False is returned if data is not -// set, or is invalid. -func (r *Request) DataFilled() bool { - return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid() -} - -// SetBufferBody will set the request's body bytes that will be sent to -// the service API. -func (r *Request) SetBufferBody(buf []byte) { - r.SetReaderBody(bytes.NewReader(buf)) -} - -// SetStringBody sets the body of the request to be backed by a string. -func (r *Request) SetStringBody(s string) { - r.SetReaderBody(strings.NewReader(s)) -} - -// SetReaderBody will set the request's body reader. -func (r *Request) SetReaderBody(reader io.ReadSeeker) { - r.Body = reader - r.BodyStart, _ = reader.Seek(0, sdkio.SeekCurrent) // Get the Bodies current offset. - r.ResetBody() -} - -// Presign returns the request's signed URL. Error will be returned -// if the signing fails. -// -// It is invalid to create a presigned URL with a expire duration 0 or less. An -// error is returned if expire duration is 0 or less. -func (r *Request) Presign(expire time.Duration) (string, error) { - r = r.copy() - - // Presign requires all headers be hoisted. There is no way to retrieve - // the signed headers not hoisted without this. Making the presigned URL - // useless. - r.NotHoist = false - - u, _, err := getPresignedURL(r, expire) - return u, err -} - -// PresignRequest behaves just like presign, with the addition of returning a -// set of headers that were signed. -// -// It is invalid to create a presigned URL with a expire duration 0 or less. An -// error is returned if expire duration is 0 or less. -// -// Returns the URL string for the API operation with signature in the query string, -// and the HTTP headers that were included in the signature. These headers must -// be included in any HTTP request made with the presigned URL. -// -// To prevent hoisting any headers to the query string set NotHoist to true on -// this Request value prior to calling PresignRequest. -func (r *Request) PresignRequest(expire time.Duration) (string, http.Header, error) { - r = r.copy() - return getPresignedURL(r, expire) -} - -// IsPresigned returns true if the request represents a presigned API url. -func (r *Request) IsPresigned() bool { - return r.ExpireTime != 0 -} - -func getPresignedURL(r *Request, expire time.Duration) (string, http.Header, error) { - if expire <= 0 { - return "", nil, awserr.New( - ErrCodeInvalidPresignExpire, - "presigned URL requires an expire duration greater than 0", - nil, - ) - } - - r.ExpireTime = expire - - if r.Operation.BeforePresignFn != nil { - if err := r.Operation.BeforePresignFn(r); err != nil { - return "", nil, err - } - } - - if err := r.Sign(); err != nil { - return "", nil, err - } - - return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil -} - -func debugLogReqError(r *Request, stage string, retrying bool, err error) { - if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) { - return - } - - retryStr := "not retrying" - if retrying { - retryStr = "will retry" - } - - r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", - stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err)) -} - -// Build will build the request's object so it can be signed and sent -// to the service. Build will also validate all the request's parameters. -// Any additional build Handlers set on this request will be run -// in the order they were set. -// -// The request will only be built once. Multiple calls to build will have -// no effect. -// -// If any Validate or Build errors occur the build will stop and the error -// which occurred will be returned. -func (r *Request) Build() error { - if !r.built { - r.Handlers.Validate.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Request", false, r.Error) - return r.Error - } - r.Handlers.Build.Run(r) - if r.Error != nil { - debugLogReqError(r, "Build Request", false, r.Error) - return r.Error - } - r.built = true - } - - return r.Error -} - -// Sign will sign the request, returning error if errors are encountered. -// -// Sign will build the request prior to signing. All Sign Handlers will -// be executed in the order they were set. -func (r *Request) Sign() error { - r.Build() - if r.Error != nil { - debugLogReqError(r, "Build Request", false, r.Error) - return r.Error - } - - r.Handlers.Sign.Run(r) - return r.Error -} - -func (r *Request) getNextRequestBody() (io.ReadCloser, error) { - if r.safeBody != nil { - r.safeBody.Close() - } - - r.safeBody = newOffsetReader(r.Body, r.BodyStart) - - // Go 1.8 tightened and clarified the rules code needs to use when building - // requests with the http package. Go 1.8 removed the automatic detection - // of if the Request.Body was empty, or actually had bytes in it. The SDK - // always sets the Request.Body even if it is empty and should not actually - // be sent. This is incorrect. - // - // Go 1.8 did add a http.NoBody value that the SDK can use to tell the http - // client that the request really should be sent without a body. The - // Request.Body cannot be set to nil, which is preferable, because the - // field is exported and could introduce nil pointer dereferences for users - // of the SDK if they used that field. - // - // Related golang/go#18257 - l, err := aws.SeekerLen(r.Body) - if err != nil { - return nil, awserr.New(ErrCodeSerialization, "failed to compute request body size", err) - } - - var body io.ReadCloser - if l == 0 { - body = NoBody - } else if l > 0 { - body = r.safeBody - } else { - // Hack to prevent sending bodies for methods where the body - // should be ignored by the server. Sending bodies on these - // methods without an associated ContentLength will cause the - // request to socket timeout because the server does not handle - // Transfer-Encoding: chunked bodies for these methods. - // - // This would only happen if a aws.ReaderSeekerCloser was used with - // a io.Reader that was not also an io.Seeker, or did not implement - // Len() method. - switch r.Operation.HTTPMethod { - case "GET", "HEAD", "DELETE": - body = NoBody - default: - body = r.safeBody - } - } - - return body, nil -} - -// GetBody will return an io.ReadSeeker of the Request's underlying -// input body with a concurrency safe wrapper. -func (r *Request) GetBody() io.ReadSeeker { - return r.safeBody -} - -// Send will send the request, returning error if errors are encountered. -// -// Send will sign the request prior to sending. All Send Handlers will -// be executed in the order they were set. -// -// Canceling a request is non-deterministic. If a request has been canceled, -// then the transport will choose, randomly, one of the state channels during -// reads or getting the connection. -// -// readLoop() and getConn(req *Request, cm connectMethod) -// https://github.com/golang/go/blob/master/src/net/http/transport.go -// -// Send will not close the request.Request's body. -func (r *Request) Send() error { - defer func() { - // Regardless of success or failure of the request trigger the Complete - // request handlers. - r.Handlers.Complete.Run(r) - }() - - for { - r.AttemptTime = time.Now() - if aws.BoolValue(r.Retryable) { - if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { - r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", - r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount)) - } - - // The previous http.Request will have a reference to the r.Body - // and the HTTP Client's Transport may still be reading from - // the request's body even though the Client's Do returned. - r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) - r.ResetBody() - - // Closing response body to ensure that no response body is leaked - // between retry attempts. - if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { - r.HTTPResponse.Body.Close() - } - } - - r.Sign() - if r.Error != nil { - return r.Error - } - - r.Retryable = nil - - r.Handlers.Send.Run(r) - if r.Error != nil { - if !shouldRetryCancel(r) { - return r.Error - } - - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Send Request", false, err) - return r.Error - } - debugLogReqError(r, "Send Request", true, err) - continue - } - r.Handlers.UnmarshalMeta.Run(r) - r.Handlers.ValidateResponse.Run(r) - if r.Error != nil { - r.Handlers.UnmarshalError.Run(r) - err := r.Error - - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Response", false, err) - return r.Error - } - debugLogReqError(r, "Validate Response", true, err) - continue - } - - r.Handlers.Unmarshal.Run(r) - if r.Error != nil { - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Unmarshal Response", false, err) - return r.Error - } - debugLogReqError(r, "Unmarshal Response", true, err) - continue - } - - break - } - - return nil -} - -// copy will copy a request which will allow for local manipulation of the -// request. -func (r *Request) copy() *Request { - req := &Request{} - *req = *r - req.Handlers = r.Handlers.Copy() - op := *r.Operation - req.Operation = &op - return req -} - -// AddToUserAgent adds the string to the end of the request's current user agent. -func AddToUserAgent(r *Request, s string) { - curUA := r.HTTPRequest.Header.Get("User-Agent") - if len(curUA) > 0 { - s = curUA + " " + s - } - r.HTTPRequest.Header.Set("User-Agent", s) -} - -func shouldRetryCancel(r *Request) bool { - awsErr, ok := r.Error.(awserr.Error) - timeoutErr := false - errStr := r.Error.Error() - if ok { - if awsErr.Code() == CanceledErrorCode { - return false - } - err := awsErr.OrigErr() - netErr, netOK := err.(net.Error) - timeoutErr = netOK && netErr.Temporary() - if urlErr, ok := err.(*url.Error); !timeoutErr && ok { - errStr = urlErr.Err.Error() - } - } - - // There can be two types of canceled errors here. - // The first being a net.Error and the other being an error. - // If the request was timed out, we want to continue the retry - // process. Otherwise, return the canceled error. - return timeoutErr || - (errStr != "net/http: request canceled" && - errStr != "net/http: request canceled while waiting for connection") - -} - -// SanitizeHostForHeader removes default port from host and updates request.Host -func SanitizeHostForHeader(r *http.Request) { - host := getHost(r) - port := portOnly(host) - if port != "" && isDefaultPort(r.URL.Scheme, port) { - r.Host = stripPort(host) - } -} - -// Returns host from request -func getHost(r *http.Request) string { - if r.Host != "" { - return r.Host - } - - return r.URL.Host -} - -// Hostname returns u.Host, without any port number. -// -// If Host is an IPv6 literal with a port number, Hostname returns the -// IPv6 literal without the square brackets. IPv6 literals may include -// a zone identifier. -// -// Copied from the Go 1.8 standard library (net/url) -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} - -// Port returns the port part of u.Host, without the leading colon. -// If u.Host doesn't contain a port, Port returns an empty string. -// -// Copied from the Go 1.8 standard library (net/url) -func portOnly(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return "" - } - if i := strings.Index(hostport, "]:"); i != -1 { - return hostport[i+len("]:"):] - } - if strings.Contains(hostport, "]") { - return "" - } - return hostport[colon+len(":"):] -} - -// Returns true if the specified URI is using the standard port -// (i.e. port 80 for HTTP URIs or 443 for HTTPS URIs) -func isDefaultPort(scheme, port string) bool { - if port == "" { - return true - } - - lowerCaseScheme := strings.ToLower(scheme) - if (lowerCaseScheme == "http" && port == "80") || (lowerCaseScheme == "https" && port == "443") { - return true - } - - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go deleted file mode 100644 index e36e468..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go +++ /dev/null @@ -1,39 +0,0 @@ -// +build !go1.8 - -package request - -import "io" - -// NoBody is an io.ReadCloser with no bytes. Read always returns EOF -// and Close always returns nil. It can be used in an outgoing client -// request to explicitly signal that a request has zero bytes. -// An alternative, however, is to simply set Request.Body to nil. -// -// Copy of Go 1.8 NoBody type from net/http/http.go -type noBody struct{} - -func (noBody) Read([]byte) (int, error) { return 0, io.EOF } -func (noBody) Close() error { return nil } -func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil } - -// NoBody is an empty reader that will trigger the Go HTTP client to not include -// and body in the HTTP request. -var NoBody = noBody{} - -// ResetBody rewinds the request body back to its starting position, and -// sets the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go deleted file mode 100644 index 7c6a800..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.8 - -package request - -import ( - "net/http" -) - -// NoBody is a http.NoBody reader instructing Go HTTP client to not include -// and body in the HTTP request. -var NoBody = http.NoBody - -// ResetBody rewinds the request body back to its starting position, and -// sets the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -// -// Will also set the Go 1.8's http.Request.GetBody member to allow retrying -// PUT/POST redirects. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body - r.HTTPRequest.GetBody = r.getNextRequestBody -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go deleted file mode 100644 index a7365cd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest = r.HTTPRequest.WithContext(ctx) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go deleted file mode 100644 index 307fa07..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest.Cancel = ctx.Done() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go deleted file mode 100644 index a633ed5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ /dev/null @@ -1,264 +0,0 @@ -package request - -import ( - "reflect" - "sync/atomic" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// A Pagination provides paginating of SDK API operations which are paginatable. -// Generally you should not use this type directly, but use the "Pages" API -// operations method to automatically perform pagination for you. Such as, -// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. -// -// Pagination differs from a Paginator type in that pagination is the type that -// does the pagination between API operations, and Paginator defines the -// configuration that will be used per page request. -// -// cont := true -// for p.Next() && cont { -// data := p.Page().(*s3.ListObjectsOutput) -// // process the page's data -// } -// return p.Err() -// -// See service client API operation Pages methods for examples how the SDK will -// use the Pagination type. -type Pagination struct { - // Function to return a Request value for each pagination request. - // Any configuration or handlers that need to be applied to the request - // prior to getting the next page should be done here before the request - // returned. - // - // NewRequest should always be built from the same API operations. It is - // undefined if different API operations are returned on subsequent calls. - NewRequest func() (*Request, error) - // EndPageOnSameToken, when enabled, will allow the paginator to stop on - // token that are the same as its previous tokens. - EndPageOnSameToken bool - - started bool - prevTokens []interface{} - nextTokens []interface{} - - err error - curPage interface{} -} - -// HasNextPage will return true if Pagination is able to determine that the API -// operation has additional pages. False will be returned if there are no more -// pages remaining. -// -// Will always return true if Next has not been called yet. -func (p *Pagination) HasNextPage() bool { - if !p.started { - return true - } - - hasNextPage := len(p.nextTokens) != 0 - if p.EndPageOnSameToken { - return hasNextPage && !awsutil.DeepEqual(p.nextTokens, p.prevTokens) - } - return hasNextPage -} - -// Err returns the error Pagination encountered when retrieving the next page. -func (p *Pagination) Err() error { - return p.err -} - -// Page returns the current page. Page should only be called after a successful -// call to Next. It is undefined what Page will return if Page is called after -// Next returns false. -func (p *Pagination) Page() interface{} { - return p.curPage -} - -// Next will attempt to retrieve the next page for the API operation. When a page -// is retrieved true will be returned. If the page cannot be retrieved, or there -// are no more pages false will be returned. -// -// Use the Page method to retrieve the current page data. The data will need -// to be cast to the API operation's output type. -// -// Use the Err method to determine if an error occurred if Page returns false. -func (p *Pagination) Next() bool { - if !p.HasNextPage() { - return false - } - - req, err := p.NewRequest() - if err != nil { - p.err = err - return false - } - - if p.started { - for i, intok := range req.Operation.InputTokens { - awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) - } - } - p.started = true - - err = req.Send() - if err != nil { - p.err = err - return false - } - - p.prevTokens = p.nextTokens - p.nextTokens = req.nextPageTokens() - p.curPage = req.Data - - return true -} - -// A Paginator is the configuration data that defines how an API operation -// should be paginated. This type is used by the API service models to define -// the generated pagination config for service APIs. -// -// The Pagination type is what provides iterating between pages of an API. It -// is only used to store the token metadata the SDK should use for performing -// pagination. -type Paginator struct { - InputTokens []string - OutputTokens []string - LimitToken string - TruncationToken string -} - -// nextPageTokens returns the tokens to use when asking for the next page of data. -func (r *Request) nextPageTokens() []interface{} { - if r.Operation.Paginator == nil { - return nil - } - if r.Operation.TruncationToken != "" { - tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) - if len(tr) == 0 { - return nil - } - - switch v := tr[0].(type) { - case *bool: - if !aws.BoolValue(v) { - return nil - } - case bool: - if v == false { - return nil - } - } - } - - tokens := []interface{}{} - tokenAdded := false - for _, outToken := range r.Operation.OutputTokens { - vs, _ := awsutil.ValuesAtPath(r.Data, outToken) - if len(vs) == 0 { - tokens = append(tokens, nil) - continue - } - v := vs[0] - - switch tv := v.(type) { - case *string: - if len(aws.StringValue(tv)) == 0 { - tokens = append(tokens, nil) - continue - } - case string: - if len(tv) == 0 { - tokens = append(tokens, nil) - continue - } - } - - tokenAdded = true - tokens = append(tokens, v) - } - if !tokenAdded { - return nil - } - - return tokens -} - -// Ensure a deprecated item is only logged once instead of each time its used. -func logDeprecatedf(logger aws.Logger, flag *int32, msg string) { - if logger == nil { - return - } - if atomic.CompareAndSwapInt32(flag, 0, 1) { - logger.Log(msg) - } -} - -var ( - logDeprecatedHasNextPage int32 - logDeprecatedNextPage int32 - logDeprecatedEachPage int32 -) - -// HasNextPage returns true if this request has more pages of data available. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) HasNextPage() bool { - logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage, - "Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations") - - return len(r.nextPageTokens()) > 0 -} - -// NextPage returns a new Request that can be executed to return the next -// page of result data. Call .Send() on this request to execute it. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) NextPage() *Request { - logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage, - "Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations") - - tokens := r.nextPageTokens() - if len(tokens) == 0 { - return nil - } - - data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface() - nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data) - for i, intok := range nr.Operation.InputTokens { - awsutil.SetValueAtPath(nr.Params, intok, tokens[i]) - } - return nr -} - -// EachPage iterates over each page of a paginated request object. The fn -// parameter should be a function with the following sample signature: -// -// func(page *T, lastPage bool) bool { -// return true // return false to stop iterating -// } -// -// Where "T" is the structure type matching the output structure of the given -// operation. For example, a request object generated by -// DynamoDB.ListTablesRequest() would expect to see dynamodb.ListTablesOutput -// as the structure "T". The lastPage value represents whether the page is -// the last page of data or not. The return value of this function should -// return true to keep iterating or false to stop. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error { - logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage, - "Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations") - - for page := r; page != nil; page = page.NextPage() { - if err := page.Send(); err != nil { - return err - } - if getNextPage := fn(page.Data, !page.HasNextPage()); !getNextPage { - return page.Error - } - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go deleted file mode 100644 index 7d52702..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ /dev/null @@ -1,161 +0,0 @@ -package request - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Retryer is an interface to control retry logic for a given service. -// The default implementation used by most services is the client.DefaultRetryer -// structure, which contains basic retry logic using exponential backoff. -type Retryer interface { - RetryRules(*Request) time.Duration - ShouldRetry(*Request) bool - MaxRetries() int -} - -// WithRetryer sets a config Retryer value to the given Config returning it -// for chaining. -func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config { - cfg.Retryer = retryer - return cfg -} - -// retryableCodes is a collection of service response codes which are retry-able -// without any further action. -var retryableCodes = map[string]struct{}{ - "RequestError": {}, - "RequestTimeout": {}, - ErrCodeResponseTimeout: {}, - "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout -} - -var throttleCodes = map[string]struct{}{ - "ProvisionedThroughputExceededException": {}, - "Throttling": {}, - "ThrottlingException": {}, - "RequestLimitExceeded": {}, - "RequestThrottled": {}, - "TooManyRequestsException": {}, // Lambda functions - "PriorRequestNotComplete": {}, // Route53 -} - -// credsExpiredCodes is a collection of error codes which signify the credentials -// need to be refreshed. Expired tokens require refreshing of credentials, and -// resigning before the request can be retried. -var credsExpiredCodes = map[string]struct{}{ - "ExpiredToken": {}, - "ExpiredTokenException": {}, - "RequestExpired": {}, // EC2 Only -} - -func isCodeThrottle(code string) bool { - _, ok := throttleCodes[code] - return ok -} - -func isCodeRetryable(code string) bool { - if _, ok := retryableCodes[code]; ok { - return true - } - - return isCodeExpiredCreds(code) -} - -func isCodeExpiredCreds(code string) bool { - _, ok := credsExpiredCodes[code] - return ok -} - -var validParentCodes = map[string]struct{}{ - ErrCodeSerialization: {}, - ErrCodeRead: {}, -} - -type temporaryError interface { - Temporary() bool -} - -func isNestedErrorRetryable(parentErr awserr.Error) bool { - if parentErr == nil { - return false - } - - if _, ok := validParentCodes[parentErr.Code()]; !ok { - return false - } - - err := parentErr.OrigErr() - if err == nil { - return false - } - - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) - } - - if t, ok := err.(temporaryError); ok { - return t.Temporary() || isErrConnectionReset(err) - } - - return isErrConnectionReset(err) -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if error is nil. -func IsErrorRetryable(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) || isNestedErrorRetryable(aerr) - } - } - return false -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if error is nil. -func IsErrorThrottle(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeThrottle(aerr.Code()) - } - } - return false -} - -// IsErrorExpiredCreds returns whether the error code is a credential expiry error. -// Returns false if error is nil. -func IsErrorExpiredCreds(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeExpiredCreds(aerr.Code()) - } - } - return false -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorRetryable -func (r *Request) IsErrorRetryable() bool { - return IsErrorRetryable(r.Error) -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if the request has no Error set -// -// Alias for the utility function IsErrorThrottle -func (r *Request) IsErrorThrottle() bool { - return IsErrorThrottle(r.Error) -} - -// IsErrorExpired returns whether the error code is a credential expiry error. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorExpiredCreds -func (r *Request) IsErrorExpired() bool { - return IsErrorExpiredCreds(r.Error) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go deleted file mode 100644 index 09a44eb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go +++ /dev/null @@ -1,94 +0,0 @@ -package request - -import ( - "io" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var timeoutErr = awserr.New( - ErrCodeResponseTimeout, - "read on body has reached the timeout limit", - nil, -) - -type readResult struct { - n int - err error -} - -// timeoutReadCloser will handle body reads that take too long. -// We will return a ErrReadTimeout error if a timeout occurs. -type timeoutReadCloser struct { - reader io.ReadCloser - duration time.Duration -} - -// Read will spin off a goroutine to call the reader's Read method. We will -// select on the timer's channel or the read's channel. Whoever completes first -// will be returned. -func (r *timeoutReadCloser) Read(b []byte) (int, error) { - timer := time.NewTimer(r.duration) - c := make(chan readResult, 1) - - go func() { - n, err := r.reader.Read(b) - timer.Stop() - c <- readResult{n: n, err: err} - }() - - select { - case data := <-c: - return data.n, data.err - case <-timer.C: - return 0, timeoutErr - } -} - -func (r *timeoutReadCloser) Close() error { - return r.reader.Close() -} - -const ( - // HandlerResponseTimeout is what we use to signify the name of the - // response timeout handler. - HandlerResponseTimeout = "ResponseTimeoutHandler" -) - -// adaptToResponseTimeoutError is a handler that will replace any top level error -// to a ErrCodeResponseTimeout, if its child is that. -func adaptToResponseTimeoutError(req *Request) { - if err, ok := req.Error.(awserr.Error); ok { - aerr, ok := err.OrigErr().(awserr.Error) - if ok && aerr.Code() == ErrCodeResponseTimeout { - req.Error = aerr - } - } -} - -// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. -// This will allow for per read timeouts. If a timeout occurred, we will return the -// ErrCodeResponseTimeout. -// -// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) -func WithResponseReadTimeout(duration time.Duration) Option { - return func(r *Request) { - - var timeoutHandler = NamedHandler{ - HandlerResponseTimeout, - func(req *Request) { - req.HTTPResponse.Body = &timeoutReadCloser{ - reader: req.HTTPResponse.Body, - duration: duration, - } - }} - - // remove the handler so we are not stomping over any new durations. - r.Handlers.Send.RemoveByName(HandlerResponseTimeout) - r.Handlers.Send.PushBackNamed(timeoutHandler) - - r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) - r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go deleted file mode 100644 index 4012462..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go +++ /dev/null @@ -1,234 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -const ( - // InvalidParameterErrCode is the error code for invalid parameters errors - InvalidParameterErrCode = "InvalidParameter" - // ParamRequiredErrCode is the error code for required parameter errors - ParamRequiredErrCode = "ParamRequiredError" - // ParamMinValueErrCode is the error code for fields with too low of a - // number value. - ParamMinValueErrCode = "ParamMinValueError" - // ParamMinLenErrCode is the error code for fields without enough elements. - ParamMinLenErrCode = "ParamMinLenError" -) - -// Validator provides a way for types to perform validation logic on their -// input values that external code can use to determine if a type's values -// are valid. -type Validator interface { - Validate() error -} - -// An ErrInvalidParams provides wrapping of invalid parameter errors found when -// validating API operation input parameters. -type ErrInvalidParams struct { - // Context is the base context of the invalid parameter group. - Context string - errs []ErrInvalidParam -} - -// Add adds a new invalid parameter error to the collection of invalid -// parameters. The context of the invalid parameter will be updated to reflect -// this collection. -func (e *ErrInvalidParams) Add(err ErrInvalidParam) { - err.SetContext(e.Context) - e.errs = append(e.errs, err) -} - -// AddNested adds the invalid parameter errors from another ErrInvalidParams -// value into this collection. The nested errors will have their nested context -// updated and base context to reflect the merging. -// -// Use for nested validations errors. -func (e *ErrInvalidParams) AddNested(nestedCtx string, nested ErrInvalidParams) { - for _, err := range nested.errs { - err.SetContext(e.Context) - err.AddNestedContext(nestedCtx) - e.errs = append(e.errs, err) - } -} - -// Len returns the number of invalid parameter errors -func (e ErrInvalidParams) Len() int { - return len(e.errs) -} - -// Code returns the code of the error -func (e ErrInvalidParams) Code() string { - return InvalidParameterErrCode -} - -// Message returns the message of the error -func (e ErrInvalidParams) Message() string { - return fmt.Sprintf("%d validation error(s) found.", len(e.errs)) -} - -// Error returns the string formatted form of the invalid parameters. -func (e ErrInvalidParams) Error() string { - w := &bytes.Buffer{} - fmt.Fprintf(w, "%s: %s\n", e.Code(), e.Message()) - - for _, err := range e.errs { - fmt.Fprintf(w, "- %s\n", err.Message()) - } - - return w.String() -} - -// OrigErr returns the invalid parameters as a awserr.BatchedErrors value -func (e ErrInvalidParams) OrigErr() error { - return awserr.NewBatchError( - InvalidParameterErrCode, e.Message(), e.OrigErrs()) -} - -// OrigErrs returns a slice of the invalid parameters -func (e ErrInvalidParams) OrigErrs() []error { - errs := make([]error, len(e.errs)) - for i := 0; i < len(errs); i++ { - errs[i] = e.errs[i] - } - - return errs -} - -// An ErrInvalidParam represents an invalid parameter error type. -type ErrInvalidParam interface { - awserr.Error - - // Field name the error occurred on. - Field() string - - // SetContext updates the context of the error. - SetContext(string) - - // AddNestedContext updates the error's context to include a nested level. - AddNestedContext(string) -} - -type errInvalidParam struct { - context string - nestedContext string - field string - code string - msg string -} - -// Code returns the error code for the type of invalid parameter. -func (e *errInvalidParam) Code() string { - return e.code -} - -// Message returns the reason the parameter was invalid, and its context. -func (e *errInvalidParam) Message() string { - return fmt.Sprintf("%s, %s.", e.msg, e.Field()) -} - -// Error returns the string version of the invalid parameter error. -func (e *errInvalidParam) Error() string { - return fmt.Sprintf("%s: %s", e.code, e.Message()) -} - -// OrigErr returns nil, Implemented for awserr.Error interface. -func (e *errInvalidParam) OrigErr() error { - return nil -} - -// Field Returns the field and context the error occurred. -func (e *errInvalidParam) Field() string { - field := e.context - if len(field) > 0 { - field += "." - } - if len(e.nestedContext) > 0 { - field += fmt.Sprintf("%s.", e.nestedContext) - } - field += e.field - - return field -} - -// SetContext updates the base context of the error. -func (e *errInvalidParam) SetContext(ctx string) { - e.context = ctx -} - -// AddNestedContext prepends a context to the field's path. -func (e *errInvalidParam) AddNestedContext(ctx string) { - if len(e.nestedContext) == 0 { - e.nestedContext = ctx - } else { - e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) - } - -} - -// An ErrParamRequired represents an required parameter error. -type ErrParamRequired struct { - errInvalidParam -} - -// NewErrParamRequired creates a new required parameter error. -func NewErrParamRequired(field string) *ErrParamRequired { - return &ErrParamRequired{ - errInvalidParam{ - code: ParamRequiredErrCode, - field: field, - msg: fmt.Sprintf("missing required field"), - }, - } -} - -// An ErrParamMinValue represents a minimum value parameter error. -type ErrParamMinValue struct { - errInvalidParam - min float64 -} - -// NewErrParamMinValue creates a new minimum value parameter error. -func NewErrParamMinValue(field string, min float64) *ErrParamMinValue { - return &ErrParamMinValue{ - errInvalidParam: errInvalidParam{ - code: ParamMinValueErrCode, - field: field, - msg: fmt.Sprintf("minimum field value of %v", min), - }, - min: min, - } -} - -// MinValue returns the field's require minimum value. -// -// float64 is returned for both int and float min values. -func (e *ErrParamMinValue) MinValue() float64 { - return e.min -} - -// An ErrParamMinLen represents a minimum length parameter error. -type ErrParamMinLen struct { - errInvalidParam - min int -} - -// NewErrParamMinLen creates a new minimum length parameter error. -func NewErrParamMinLen(field string, min int) *ErrParamMinLen { - return &ErrParamMinLen{ - errInvalidParam: errInvalidParam{ - code: ParamMinLenErrCode, - field: field, - msg: fmt.Sprintf("minimum field size of %v", min), - }, - min: min, - } -} - -// MinLen returns the field's required minimum length. -func (e *ErrParamMinLen) MinLen() int { - return e.min -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go deleted file mode 100644 index 4601f88..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go +++ /dev/null @@ -1,295 +0,0 @@ -package request - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when -// the waiter's max attempts have been exhausted. -const WaiterResourceNotReadyErrorCode = "ResourceNotReady" - -// A WaiterOption is a function that will update the Waiter value's fields to -// configure the waiter. -type WaiterOption func(*Waiter) - -// WithWaiterMaxAttempts returns the maximum number of times the waiter should -// attempt to check the resource for the target state. -func WithWaiterMaxAttempts(max int) WaiterOption { - return func(w *Waiter) { - w.MaxAttempts = max - } -} - -// WaiterDelay will return a delay the waiter should pause between attempts to -// check the resource state. The passed in attempt is the number of times the -// Waiter has checked the resource state. -// -// Attempt is the number of attempts the Waiter has made checking the resource -// state. -type WaiterDelay func(attempt int) time.Duration - -// ConstantWaiterDelay returns a WaiterDelay that will always return a constant -// delay the waiter should use between attempts. It ignores the number of -// attempts made. -func ConstantWaiterDelay(delay time.Duration) WaiterDelay { - return func(attempt int) time.Duration { - return delay - } -} - -// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. -func WithWaiterDelay(delayer WaiterDelay) WaiterOption { - return func(w *Waiter) { - w.Delay = delayer - } -} - -// WithWaiterLogger returns a waiter option to set the logger a waiter -// should use to log warnings and errors to. -func WithWaiterLogger(logger aws.Logger) WaiterOption { - return func(w *Waiter) { - w.Logger = logger - } -} - -// WithWaiterRequestOptions returns a waiter option setting the request -// options for each request the waiter makes. Appends to waiter's request -// options already set. -func WithWaiterRequestOptions(opts ...Option) WaiterOption { - return func(w *Waiter) { - w.RequestOptions = append(w.RequestOptions, opts...) - } -} - -// A Waiter provides the functionality to perform a blocking call which will -// wait for a resource state to be satisfied by a service. -// -// This type should not be used directly. The API operations provided in the -// service packages prefixed with "WaitUntil" should be used instead. -type Waiter struct { - Name string - Acceptors []WaiterAcceptor - Logger aws.Logger - - MaxAttempts int - Delay WaiterDelay - - RequestOptions []Option - NewRequest func([]Option) (*Request, error) - SleepWithContext func(aws.Context, time.Duration) error -} - -// ApplyOptions updates the waiter with the list of waiter options provided. -func (w *Waiter) ApplyOptions(opts ...WaiterOption) { - for _, fn := range opts { - fn(w) - } -} - -// WaiterState are states the waiter uses based on WaiterAcceptor definitions -// to identify if the resource state the waiter is waiting on has occurred. -type WaiterState int - -// String returns the string representation of the waiter state. -func (s WaiterState) String() string { - switch s { - case SuccessWaiterState: - return "success" - case FailureWaiterState: - return "failure" - case RetryWaiterState: - return "retry" - default: - return "unknown waiter state" - } -} - -// States the waiter acceptors will use to identify target resource states. -const ( - SuccessWaiterState WaiterState = iota // waiter successful - FailureWaiterState // waiter failed - RetryWaiterState // waiter needs to be retried -) - -// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor -// definition's Expected attribute. -type WaiterMatchMode int - -// Modes the waiter will use when inspecting API response to identify target -// resource states. -const ( - PathAllWaiterMatch WaiterMatchMode = iota // match on all paths - PathWaiterMatch // match on specific path - PathAnyWaiterMatch // match on any path - PathListWaiterMatch // match on list of paths - StatusWaiterMatch // match on status code - ErrorWaiterMatch // match on error -) - -// String returns the string representation of the waiter match mode. -func (m WaiterMatchMode) String() string { - switch m { - case PathAllWaiterMatch: - return "pathAll" - case PathWaiterMatch: - return "path" - case PathAnyWaiterMatch: - return "pathAny" - case PathListWaiterMatch: - return "pathList" - case StatusWaiterMatch: - return "status" - case ErrorWaiterMatch: - return "error" - default: - return "unknown waiter match mode" - } -} - -// WaitWithContext will make requests for the API operation using NewRequest to -// build API requests. The request's response will be compared against the -// Waiter's Acceptors to determine the successful state of the resource the -// waiter is inspecting. -// -// The passed in context must not be nil. If it is nil a panic will occur. The -// Context will be used to cancel the waiter's pending requests and retry delays. -// Use aws.BackgroundContext if no context is available. -// -// The waiter will continue until the target state defined by the Acceptors, -// or the max attempts expires. -// -// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's -// retryer ShouldRetry returns false. This normally will happen when the max -// wait attempts expires. -func (w Waiter) WaitWithContext(ctx aws.Context) error { - - for attempt := 1; ; attempt++ { - req, err := w.NewRequest(w.RequestOptions) - if err != nil { - waiterLogf(w.Logger, "unable to create request %v", err) - return err - } - req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) - err = req.Send() - - // See if any of the acceptors match the request's response, or error - for _, a := range w.Acceptors { - if matched, matchErr := a.match(w.Name, w.Logger, req, err); matched { - return matchErr - } - } - - // The Waiter should only check the resource state MaxAttempts times - // This is here instead of in the for loop above to prevent delaying - // unnecessary when the waiter will not retry. - if attempt == w.MaxAttempts { - break - } - - // Delay to wait before inspecting the resource again - delay := w.Delay(attempt) - if sleepFn := req.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(delay) - } else { - sleepCtxFn := w.SleepWithContext - if sleepCtxFn == nil { - sleepCtxFn = aws.SleepWithContext - } - - if err := sleepCtxFn(ctx, delay); err != nil { - return awserr.New(CanceledErrorCode, "waiter context canceled", err) - } - } - } - - return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) -} - -// A WaiterAcceptor provides the information needed to wait for an API operation -// to complete. -type WaiterAcceptor struct { - State WaiterState - Matcher WaiterMatchMode - Argument string - Expected interface{} -} - -// match returns if the acceptor found a match with the passed in request -// or error. True is returned if the acceptor made a match, error is returned -// if there was an error attempting to perform the match. -func (a *WaiterAcceptor) match(name string, l aws.Logger, req *Request, err error) (bool, error) { - result := false - var vals []interface{} - - switch a.Matcher { - case PathAllWaiterMatch, PathWaiterMatch: - // Require all matches to be equal for result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - if len(vals) == 0 { - break - } - result = true - for _, val := range vals { - if !awsutil.DeepEqual(val, a.Expected) { - result = false - break - } - } - case PathAnyWaiterMatch: - // Only a single match needs to equal for the result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - for _, val := range vals { - if awsutil.DeepEqual(val, a.Expected) { - result = true - break - } - } - case PathListWaiterMatch: - // ignored matcher - case StatusWaiterMatch: - s := a.Expected.(int) - result = s == req.HTTPResponse.StatusCode - case ErrorWaiterMatch: - if aerr, ok := err.(awserr.Error); ok { - result = aerr.Code() == a.Expected.(string) - } - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", - name, a.Matcher) - } - - if !result { - // If there was no matching result found there is nothing more to do - // for this response, retry the request. - return false, nil - } - - switch a.State { - case SuccessWaiterState: - // waiter completed - return true, nil - case FailureWaiterState: - // Waiter failure state triggered - return true, awserr.New(WaiterResourceNotReadyErrorCode, - "failed waiting for successful resource state", err) - case RetryWaiterState: - // clear the error and retry the operation - return false, nil - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", - name, a.State) - return false, nil - } -} - -func waiterLogf(logger aws.Logger, msg string, args ...interface{}) { - if logger != nil { - logger.Log(fmt.Sprintf(msg, args...)) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go deleted file mode 100644 index 98d420f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go +++ /dev/null @@ -1,273 +0,0 @@ -/* -Package session provides configuration for the SDK's service clients. - -Sessions can be shared across all service clients that share the same base -configuration. The Session is built from the SDK's default configuration and -request handlers. - -Sessions should be cached when possible, because creating a new Session will -load all configuration values from the environment, and config files each time -the Session is created. Sharing the Session value across all of your service -clients will ensure the configuration is loaded the fewest number of times possible. - -Concurrency - -Sessions are safe to use concurrently as long as the Session is not being -modified. The SDK will not modify the Session once the Session has been created. -Creating service clients concurrently from a shared Session is safe. - -Sessions from Shared Config - -Sessions can be created using the method above that will only load the -additional config if the AWS_SDK_LOAD_CONFIG environment variable is set. -Alternatively you can explicitly create a Session with shared config enabled. -To do this you can use NewSessionWithOptions to configure how the Session will -be created. Using the NewSessionWithOptions with SharedConfigState set to -SharedConfigEnable will create the session as if the AWS_SDK_LOAD_CONFIG -environment variable was set. - -Creating Sessions - -When creating Sessions optional aws.Config values can be passed in that will -override the default, or loaded config values the Session is being created -with. This allows you to provide additional, or case based, configuration -as needed. - -By default NewSession will only load credentials from the shared credentials -file (~/.aws/credentials). If the AWS_SDK_LOAD_CONFIG environment variable is -set to a truthy value the Session will be created from the configuration -values from the shared config (~/.aws/config) and shared credentials -(~/.aws/credentials) files. See the section Sessions from Shared Config for -more information. - -Create a Session with the default config and request handlers. With credentials -region, and profile loaded from the environment and shared config automatically. -Requires the AWS_PROFILE to be set, or "default" is used. - - // Create Session - sess := session.Must(session.NewSession()) - - // Create a Session with a custom region - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String("us-east-1"), - })) - - // Create a S3 client instance from a session - sess := session.Must(session.NewSession()) - - svc := s3.New(sess) - -Create Session With Option Overrides - -In addition to NewSession, Sessions can be created using NewSessionWithOptions. -This func allows you to control and override how the Session will be created -through code instead of being driven by environment variables only. - -Use NewSessionWithOptions when you want to provide the config profile, or -override the shared config state (AWS_SDK_LOAD_CONFIG). - - // Equivalent to session.NewSession() - sess := session.Must(session.NewSessionWithOptions(session.Options{ - // Options - })) - - // Specify profile to load for the session's config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - Profile: "profile_name", - })) - - // Specify profile for config and region for requests - sess := session.Must(session.NewSessionWithOptions(session.Options{ - Config: aws.Config{Region: aws.String("us-east-1")}, - Profile: "profile_name", - })) - - // Force enable Shared Config support - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - -Adding Handlers - -You can add handlers to a session for processing HTTP requests. All service -clients that use the session inherit the handlers. For example, the following -handler logs every request and its payload made by a service client: - - // Create a session, and add additional handlers for all service - // clients created with the Session to inherit. Adds logging handler. - sess := session.Must(session.NewSession()) - - sess.Handlers.Send.PushFront(func(r *request.Request) { - // Log every request made and its payload - logger.Println("Request: %s/%s, Payload: %s", - r.ClientInfo.ServiceName, r.Operation, r.Params) - }) - -Deprecated "New" function - -The New session function has been deprecated because it does not provide good -way to return errors that occur when loading the configuration files and values. -Because of this, NewSession was created so errors can be retrieved when -creating a session fails. - -Shared Config Fields - -By default the SDK will only load the shared credentials file's (~/.aws/credentials) -credentials values, and all other config is provided by the environment variables, -SDK defaults, and user provided aws.Config values. - -If the AWS_SDK_LOAD_CONFIG environment variable is set, or SharedConfigEnable -option is used to create the Session the full shared config values will be -loaded. This includes credentials, region, and support for assume role. In -addition the Session will load its configuration from both the shared config -file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both -files have the same format. - -If both config files are present the configuration from both files will be -read. The Session will be created from configuration values from the shared -credentials file (~/.aws/credentials) over those in the shared config file (~/.aws/config). - -Credentials are the values the SDK should use for authenticating requests with -AWS Services. They are from a configuration file will need to include both -aws_access_key_id and aws_secret_access_key must be provided together in the -same file to be considered valid. The values will be ignored if not a complete -group. aws_session_token is an optional field that can be provided if both of -the other two fields are also provided. - - aws_access_key_id = AKID - aws_secret_access_key = SECRET - aws_session_token = TOKEN - -Assume Role values allow you to configure the SDK to assume an IAM role using -a set of credentials provided in a config file via the source_profile field. -Both "role_arn" and "source_profile" are required. The SDK supports assuming -a role with MFA token if the session option AssumeRoleTokenProvider -is set. - - role_arn = arn:aws:iam:::role/ - source_profile = profile_with_creds - external_id = 1234 - mfa_serial = - role_session_name = session_name - -Region is the region the SDK should use for looking up AWS service endpoints -and signing requests. - - region = us-east-1 - -Assume Role with MFA token - -To create a session with support for assuming an IAM role with MFA set the -session option AssumeRoleTokenProvider to a function that will prompt for the -MFA token code when the SDK assumes the role and refreshes the role's credentials. -This allows you to configure the SDK via the shared config to assumea role -with MFA tokens. - -In order for the SDK to assume a role with MFA the SharedConfigState -session option must be set to SharedConfigEnable, or AWS_SDK_LOAD_CONFIG -environment variable set. - -The shared configuration instructs the SDK to assume an IAM role with MFA -when the mfa_serial configuration field is set in the shared config -(~/.aws/config) or shared credentials (~/.aws/credentials) file. - -If mfa_serial is set in the configuration, the SDK will assume the role, and -the AssumeRoleTokenProvider session option is not set an an error will -be returned when creating the session. - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - AssumeRoleTokenProvider: stscreds.StdinTokenProvider, - })) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess) - -To setup assume role outside of a session see the stscrds.AssumeRoleProvider -documentation. - -Environment Variables - -When a Session is created several environment variables can be set to adjust -how the SDK functions, and what configuration data it loads when creating -Sessions. All environment values are optional, but some values like credentials -require multiple of the values to set or the partial values will be ignored. -All environment variable values are strings unless otherwise noted. - -Environment configuration values. If set both Access Key ID and Secret Access -Key must be provided. Session Token and optionally also be provided, but is -not required. - - # Access Key ID - AWS_ACCESS_KEY_ID=AKID - AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - - # Secret Access Key - AWS_SECRET_ACCESS_KEY=SECRET - AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - - # Session Token - AWS_SESSION_TOKEN=TOKEN - -Region value will instruct the SDK where to make service API requests to. If is -not provided in the environment the region must be provided before a service -client request is made. - - AWS_REGION=us-east-1 - - # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_REGION is not also set. - AWS_DEFAULT_REGION=us-east-1 - -Profile name the SDK should load use when loading shared config from the -configuration files. If not provided "default" will be used as the profile name. - - AWS_PROFILE=my_profile - - # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_PROFILE is not also set. - AWS_DEFAULT_PROFILE=my_profile - -SDK load config instructs the SDK to load the shared config in addition to -shared credentials. This also expands the configuration loaded so the shared -credentials will have parity with the shared config file. This also enables -Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE -env values as well. - - AWS_SDK_LOAD_CONFIG=1 - -Shared credentials file path can be set to instruct the SDK to use an alternative -file for the shared credentials. If not set the file will be loaded from -$HOME/.aws/credentials on Linux/Unix based systems, and -%USERPROFILE%\.aws\credentials on Windows. - - AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - -Shared config file path can be set to instruct the SDK to use an alternative -file for the shared config. If not set the file will be loaded from -$HOME/.aws/config on Linux/Unix based systems, and -%USERPROFILE%\.aws\config on Windows. - - AWS_CONFIG_FILE=$HOME/my_shared_config - -Path to a custom Credentials Authority (CA) bundle PEM file that the SDK -will use instead of the default system's root CA bundle. Use this only -if you want to replace the CA bundle the SDK uses for TLS requests. - - AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - -Enabling this option will attempt to merge the Transport into the SDK's HTTP -client. If the client's Transport is not a http.Transport an error will be -returned. If the Transport's TLS config is set this option will cause the SDK -to overwrite the Transport's TLS config's RootCAs value. If the CA bundle file -contains multiple certificates all of them will be loaded. - -The Session option CustomCABundle is also available when creating sessions -to also enable this feature. CustomCABundle session option field has priority -over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - -Setting a custom HTTPClient in the aws.Config options will override this setting. -To use this option and custom HTTP client, the HTTP client needs to be provided -when creating the session. Not the service client. -*/ -package session diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go deleted file mode 100644 index 82e04d7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ /dev/null @@ -1,219 +0,0 @@ -package session - -import ( - "os" - "strconv" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/defaults" -) - -// EnvProviderName provides a name of the provider when config is loaded from environment. -const EnvProviderName = "EnvConfigCredentials" - -// envConfig is a collection of environment values the SDK will read -// setup config from. All environment values are optional. But some values -// such as credentials require multiple values to be complete or the values -// will be ignored. -type envConfig struct { - // Environment configuration values. If set both Access Key ID and Secret Access - // Key must be provided. Session Token and optionally also be provided, but is - // not required. - // - // # Access Key ID - // AWS_ACCESS_KEY_ID=AKID - // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - // - // # Secret Access Key - // AWS_SECRET_ACCESS_KEY=SECRET - // AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - // - // # Session Token - // AWS_SESSION_TOKEN=TOKEN - Creds credentials.Value - - // Region value will instruct the SDK where to make service API requests to. If is - // not provided in the environment the region must be provided before a service - // client request is made. - // - // AWS_REGION=us-east-1 - // - // # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_REGION is not also set. - // AWS_DEFAULT_REGION=us-east-1 - Region string - - // Profile name the SDK should load use when loading shared configuration from the - // shared configuration files. If not provided "default" will be used as the - // profile name. - // - // AWS_PROFILE=my_profile - // - // # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_PROFILE is not also set. - // AWS_DEFAULT_PROFILE=my_profile - Profile string - - // SDK load config instructs the SDK to load the shared config in addition to - // shared credentials. This also expands the configuration loaded from the shared - // credentials to have parity with the shared config file. This also enables - // Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE - // env values as well. - // - // AWS_SDK_LOAD_CONFIG=1 - EnableSharedConfig bool - - // Shared credentials file path can be set to instruct the SDK to use an alternate - // file for the shared credentials. If not set the file will be loaded from - // $HOME/.aws/credentials on Linux/Unix based systems, and - // %USERPROFILE%\.aws\credentials on Windows. - // - // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - SharedCredentialsFile string - - // Shared config file path can be set to instruct the SDK to use an alternate - // file for the shared config. If not set the file will be loaded from - // $HOME/.aws/config on Linux/Unix based systems, and - // %USERPROFILE%\.aws\config on Windows. - // - // AWS_CONFIG_FILE=$HOME/my_shared_config - SharedConfigFile string - - // Sets the path to a custom Credentials Authroity (CA) Bundle PEM file - // that the SDK will use instead of the system's root CA bundle. - // Only use this if you want to configure the SDK to use a custom set - // of CAs. - // - // Enabling this option will attempt to merge the Transport - // into the SDK's HTTP client. If the client's Transport is - // not a http.Transport an error will be returned. If the - // Transport's TLS config is set this option will cause the - // SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this setting. - // To use this option and custom HTTP client, the HTTP client needs to be provided - // when creating the session. Not the service client. - // - // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - CustomCABundle string - - csmEnabled string - CSMEnabled bool - CSMPort string - CSMClientID string -} - -var ( - csmEnabledEnvKey = []string{ - "AWS_CSM_ENABLED", - } - csmPortEnvKey = []string{ - "AWS_CSM_PORT", - } - csmClientIDEnvKey = []string{ - "AWS_CSM_CLIENT_ID", - } - credAccessEnvKey = []string{ - "AWS_ACCESS_KEY_ID", - "AWS_ACCESS_KEY", - } - credSecretEnvKey = []string{ - "AWS_SECRET_ACCESS_KEY", - "AWS_SECRET_KEY", - } - credSessionEnvKey = []string{ - "AWS_SESSION_TOKEN", - } - - regionEnvKeys = []string{ - "AWS_REGION", - "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - profileEnvKeys = []string{ - "AWS_PROFILE", - "AWS_DEFAULT_PROFILE", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - sharedCredsFileEnvKey = []string{ - "AWS_SHARED_CREDENTIALS_FILE", - } - sharedConfigFileEnvKey = []string{ - "AWS_CONFIG_FILE", - } -) - -// loadEnvConfig retrieves the SDK's environment configuration. -// See `envConfig` for the values that will be retrieved. -// -// If the environment variable `AWS_SDK_LOAD_CONFIG` is set to a truthy value -// the shared SDK config will be loaded in addition to the SDK's specific -// configuration values. -func loadEnvConfig() envConfig { - enableSharedConfig, _ := strconv.ParseBool(os.Getenv("AWS_SDK_LOAD_CONFIG")) - return envConfigLoad(enableSharedConfig) -} - -// loadEnvSharedConfig retrieves the SDK's environment configuration, and the -// SDK shared config. See `envConfig` for the values that will be retrieved. -// -// Loads the shared configuration in addition to the SDK's specific configuration. -// This will load the same values as `loadEnvConfig` if the `AWS_SDK_LOAD_CONFIG` -// environment variable is set. -func loadSharedEnvConfig() envConfig { - return envConfigLoad(true) -} - -func envConfigLoad(enableSharedConfig bool) envConfig { - cfg := envConfig{} - - cfg.EnableSharedConfig = enableSharedConfig - - setFromEnvVal(&cfg.Creds.AccessKeyID, credAccessEnvKey) - setFromEnvVal(&cfg.Creds.SecretAccessKey, credSecretEnvKey) - setFromEnvVal(&cfg.Creds.SessionToken, credSessionEnvKey) - - // CSM environment variables - setFromEnvVal(&cfg.csmEnabled, csmEnabledEnvKey) - setFromEnvVal(&cfg.CSMPort, csmPortEnvKey) - setFromEnvVal(&cfg.CSMClientID, csmClientIDEnvKey) - cfg.CSMEnabled = len(cfg.csmEnabled) > 0 - - // Require logical grouping of credentials - if len(cfg.Creds.AccessKeyID) == 0 || len(cfg.Creds.SecretAccessKey) == 0 { - cfg.Creds = credentials.Value{} - } else { - cfg.Creds.ProviderName = EnvProviderName - } - - regionKeys := regionEnvKeys - profileKeys := profileEnvKeys - if !cfg.EnableSharedConfig { - regionKeys = regionKeys[:1] - profileKeys = profileKeys[:1] - } - - setFromEnvVal(&cfg.Region, regionKeys) - setFromEnvVal(&cfg.Profile, profileKeys) - - setFromEnvVal(&cfg.SharedCredentialsFile, sharedCredsFileEnvKey) - setFromEnvVal(&cfg.SharedConfigFile, sharedConfigFileEnvKey) - - if len(cfg.SharedCredentialsFile) == 0 { - cfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() - } - if len(cfg.SharedConfigFile) == 0 { - cfg.SharedConfigFile = defaults.SharedConfigFilename() - } - - cfg.CustomCABundle = os.Getenv("AWS_CA_BUNDLE") - - return cfg -} - -func setFromEnvVal(dst *string, keys []string) { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - *dst = v - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/session.go deleted file mode 100644 index 51f3055..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ /dev/null @@ -1,628 +0,0 @@ -package session - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/stscreds" - "github.com/aws/aws-sdk-go/aws/csm" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Session provides a central location to create service clients from and -// store configurations and request handlers for those services. -// -// Sessions are safe to create service clients concurrently, but it is not safe -// to mutate the Session concurrently. -// -// The Session satisfies the service client's client.ConfigProvider. -type Session struct { - Config *aws.Config - Handlers request.Handlers -} - -// New creates a new instance of the handlers merging in the provided configs -// on top of the SDK's default configurations. Once the Session is created it -// can be mutated to modify the Config or Handlers. The Session is safe to be -// read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New -// method could now encounter an error when loading the configuration. When -// The environment variable is set, and an error occurs, New will return a -// session that will fail all requests reporting the error that occurred while -// loading the session. Use NewSession to get the error when creating the -// session. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded, in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. -// -// Deprecated: Use NewSession functions to create sessions instead. NewSession -// has the same functionality as New except an error can be returned when the -// func is called instead of waiting to receive an error until a request is made. -func New(cfgs ...*aws.Config) *Session { - // load initial config from environment - envCfg := loadEnvConfig() - - if envCfg.EnableSharedConfig { - var cfg aws.Config - cfg.MergeIn(cfgs...) - s, err := NewSessionWithOptions(Options{ - Config: cfg, - SharedConfigState: SharedConfigEnable, - }) - if err != nil { - // Old session.New expected all errors to be discovered when - // a request is made, and would report the errors then. This - // needs to be replicated if an error occurs while creating - // the session. - msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " + - "Use session.NewSession to handle errors occurring during session creation." - - // Session creation failed, need to report the error and prevent - // any requests from succeeding. - s = &Session{Config: defaults.Config()} - s.Config.MergeIn(cfgs...) - s.Config.Logger.Log("ERROR:", msg, "Error:", err) - s.Handlers.Validate.PushBack(func(r *request.Request) { - r.Error = err - }) - } - - return s - } - - s := deprecatedNewSession(cfgs...) - if envCfg.CSMEnabled { - enableCSM(&s.Handlers, envCfg.CSMClientID, envCfg.CSMPort, s.Config.Logger) - } - - return s -} - -// NewSession returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. Once the Session is created -// it can be mutated to modify the Config or Handlers. The Session is safe to -// be read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// See the NewSessionWithOptions func for information on how to override or -// control through code how the Session will be created. Such as specifying the -// config profile, and controlling if shared config is enabled or not. -func NewSession(cfgs ...*aws.Config) (*Session, error) { - opts := Options{} - opts.Config.MergeIn(cfgs...) - - return NewSessionWithOptions(opts) -} - -// SharedConfigState provides the ability to optionally override the state -// of the session's creation based on the shared config being enabled or -// disabled. -type SharedConfigState int - -const ( - // SharedConfigStateFromEnv does not override any state of the - // AWS_SDK_LOAD_CONFIG env var. It is the default value of the - // SharedConfigState type. - SharedConfigStateFromEnv SharedConfigState = iota - - // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value - // and disables the shared config functionality. - SharedConfigDisable - - // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value - // and enables the shared config functionality. - SharedConfigEnable -) - -// Options provides the means to control how a Session is created and what -// configuration values will be loaded. -// -type Options struct { - // Provides config values for the SDK to use when creating service clients - // and making API requests to services. Any value set in with this field - // will override the associated value provided by the SDK defaults, - // environment or config files where relevant. - // - // If not set, configuration values from from SDK defaults, environment, - // config will be used. - Config aws.Config - - // Overrides the config profile the Session should be created from. If not - // set the value of the environment variable will be loaded (AWS_PROFILE, - // or AWS_DEFAULT_PROFILE if the Shared Config is enabled). - // - // If not set and environment variables are not set the "default" - // (DefaultSharedConfigProfile) will be used as the profile to load the - // session config from. - Profile string - - // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG - // environment variable. By default a Session will be created using the - // value provided by the AWS_SDK_LOAD_CONFIG environment variable. - // - // Setting this value to SharedConfigEnable or SharedConfigDisable - // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable - // and enable or disable the shared config functionality. - SharedConfigState SharedConfigState - - // Ordered list of files the session will load configuration from. - // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE. - SharedConfigFiles []string - - // When the SDK's shared config is configured to assume a role with MFA - // this option is required in order to provide the mechanism that will - // retrieve the MFA token. There is no default value for this field. If - // it is not set an error will be returned when creating the session. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed. Within the context of service clients - // all sharing the same session the SDK will ensure calls to the token - // provider are atomic. When sharing a token provider across multiple - // sessions additional synchronization logic is needed to ensure the - // token providers do not introduce race conditions. It is recommend to - // share the session where possible. - // - // stscreds.StdinTokenProvider is a basic implementation that will prompt - // from stdin for the MFA token code. - // - // This field is only used if the shared configuration is enabled, and - // the config enables assume role wit MFA via the mfa_serial field. - AssumeRoleTokenProvider func() (string, error) - - // Reader for a custom Credentials Authority (CA) bundle in PEM format that - // the SDK will use instead of the default system's root CA bundle. Use this - // only if you want to replace the CA bundle the SDK uses for TLS requests. - // - // Enabling this option will attempt to merge the Transport into the SDK's HTTP - // client. If the client's Transport is not a http.Transport an error will be - // returned. If the Transport's TLS config is set this option will cause the SDK - // to overwrite the Transport's TLS config's RootCAs value. If the CA - // bundle reader contains multiple certificates all of them will be loaded. - // - // The Session option CustomCABundle is also available when creating sessions - // to also enable this feature. CustomCABundle session option field has priority - // over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - CustomCABundle io.Reader -} - -// NewSessionWithOptions returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. This func uses the Options -// values to configure how the Session is created. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// // Equivalent to session.New -// sess := session.Must(session.NewSessionWithOptions(session.Options{})) -// -// // Specify profile to load for the session's config -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Profile: "profile_name", -// })) -// -// // Specify profile for config and region for requests -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Config: aws.Config{Region: aws.String("us-east-1")}, -// Profile: "profile_name", -// })) -// -// // Force enable Shared Config support -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -func NewSessionWithOptions(opts Options) (*Session, error) { - var envCfg envConfig - if opts.SharedConfigState == SharedConfigEnable { - envCfg = loadSharedEnvConfig() - } else { - envCfg = loadEnvConfig() - } - - if len(opts.Profile) > 0 { - envCfg.Profile = opts.Profile - } - - switch opts.SharedConfigState { - case SharedConfigDisable: - envCfg.EnableSharedConfig = false - case SharedConfigEnable: - envCfg.EnableSharedConfig = true - } - - // Only use AWS_CA_BUNDLE if session option is not provided. - if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil { - f, err := os.Open(envCfg.CustomCABundle) - if err != nil { - return nil, awserr.New("LoadCustomCABundleError", - "failed to open custom CA bundle PEM file", err) - } - defer f.Close() - opts.CustomCABundle = f - } - - return newSession(opts, envCfg, &opts.Config) -} - -// Must is a helper function to ensure the Session is valid and there was no -// error when calling a NewSession function. -// -// This helper is intended to be used in variable initialization to load the -// Session and configuration at startup. Such as: -// -// var sess = session.Must(session.NewSession()) -func Must(sess *Session, err error) *Session { - if err != nil { - panic(err) - } - - return sess -} - -func deprecatedNewSession(cfgs ...*aws.Config) *Session { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Apply the passed in configs so the configuration can be applied to the - // default credential chain - cfg.MergeIn(cfgs...) - if cfg.EndpointResolver == nil { - // An endpoint resolver is required for a session to be able to provide - // endpoints for service client configurations. - cfg.EndpointResolver = endpoints.DefaultResolver() - } - cfg.Credentials = defaults.CredChain(cfg, handlers) - - // Reapply any passed in configs to override credentials if set - cfg.MergeIn(cfgs...) - - s := &Session{ - Config: cfg, - Handlers: handlers, - } - - initHandlers(s) - return s -} - -func enableCSM(handlers *request.Handlers, clientID string, port string, logger aws.Logger) { - logger.Log("Enabling CSM") - if len(port) == 0 { - port = csm.DefaultPort - } - - r, err := csm.Start(clientID, "127.0.0.1:"+port) - if err != nil { - return - } - r.InjectHandlers(handlers) -} - -func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Get a merged version of the user provided config to determine if - // credentials were. - userCfg := &aws.Config{} - userCfg.MergeIn(cfgs...) - - // Ordered config files will be loaded in with later files overwriting - // previous config file values. - var cfgFiles []string - if opts.SharedConfigFiles != nil { - cfgFiles = opts.SharedConfigFiles - } else { - cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile} - if !envCfg.EnableSharedConfig { - // The shared config file (~/.aws/config) is only loaded if instructed - // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG). - cfgFiles = cfgFiles[1:] - } - } - - // Load additional config from file(s) - sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles) - if err != nil { - return nil, err - } - - if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { - return nil, err - } - - s := &Session{ - Config: cfg, - Handlers: handlers, - } - - initHandlers(s) - if envCfg.CSMEnabled { - enableCSM(&s.Handlers, envCfg.CSMClientID, envCfg.CSMPort, s.Config.Logger) - } - - // Setup HTTP client with custom cert bundle if enabled - if opts.CustomCABundle != nil { - if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil { - return nil, err - } - } - - return s, nil -} - -func loadCustomCABundle(s *Session, bundle io.Reader) error { - var t *http.Transport - switch v := s.Config.HTTPClient.Transport.(type) { - case *http.Transport: - t = v - default: - if s.Config.HTTPClient.Transport != nil { - return awserr.New("LoadCustomCABundleError", - "unable to load custom CA bundle, HTTPClient's transport unsupported type", nil) - } - } - if t == nil { - t = &http.Transport{} - } - - p, err := loadCertPool(bundle) - if err != nil { - return err - } - if t.TLSClientConfig == nil { - t.TLSClientConfig = &tls.Config{} - } - t.TLSClientConfig.RootCAs = p - - s.Config.HTTPClient.Transport = t - - return nil -} - -func loadCertPool(r io.Reader) (*x509.CertPool, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, awserr.New("LoadCustomCABundleError", - "failed to read custom CA bundle PEM file", err) - } - - p := x509.NewCertPool() - if !p.AppendCertsFromPEM(b) { - return nil, awserr.New("LoadCustomCABundleError", - "failed to load custom CA bundle PEM file", err) - } - - return p, nil -} - -func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options) error { - // Merge in user provided configuration - cfg.MergeIn(userCfg) - - // Region if not already set by user - if len(aws.StringValue(cfg.Region)) == 0 { - if len(envCfg.Region) > 0 { - cfg.WithRegion(envCfg.Region) - } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 { - cfg.WithRegion(sharedCfg.Region) - } - } - - // Configure credentials if not already set - if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { - if len(envCfg.Creds.AccessKeyID) > 0 { - cfg.Credentials = credentials.NewStaticCredentialsFromCreds( - envCfg.Creds, - ) - } else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil { - cfgCp := *cfg - cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds( - sharedCfg.AssumeRoleSource.Creds, - ) - if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil { - // AssumeRole Token provider is required if doing Assume Role - // with MFA. - return AssumeRoleTokenProviderNotSetError{} - } - cfg.Credentials = stscreds.NewCredentials( - &Session{ - Config: &cfgCp, - Handlers: handlers.Copy(), - }, - sharedCfg.AssumeRole.RoleARN, - func(opt *stscreds.AssumeRoleProvider) { - opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName - - // Assume role with external ID - if len(sharedCfg.AssumeRole.ExternalID) > 0 { - opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.AssumeRole.MFASerial) > 0 { - opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial) - opt.TokenProvider = sessOpts.AssumeRoleTokenProvider - } - }, - ) - } else if len(sharedCfg.Creds.AccessKeyID) > 0 { - cfg.Credentials = credentials.NewStaticCredentialsFromCreds( - sharedCfg.Creds, - ) - } else { - // Fallback to default credentials provider, include mock errors - // for the credential chain so user can identify why credentials - // failed to be retrieved. - cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)}, - &credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)}, - defaults.RemoteCredProvider(*cfg, handlers), - }, - }) - } - } - - return nil -} - -// AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the -// MFAToken option is not set when shared config is configured load assume a -// role with an MFA token. -type AssumeRoleTokenProviderNotSetError struct{} - -// Code is the short id of the error. -func (e AssumeRoleTokenProviderNotSetError) Code() string { - return "AssumeRoleTokenProviderNotSetError" -} - -// Message is the description of the error -func (e AssumeRoleTokenProviderNotSetError) Message() string { - return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") -} - -// OrigErr is the underlying error that caused the failure. -func (e AssumeRoleTokenProviderNotSetError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e AssumeRoleTokenProviderNotSetError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} - -type credProviderError struct { - Err error -} - -var emptyCreds = credentials.Value{} - -func (c credProviderError) Retrieve() (credentials.Value, error) { - return credentials.Value{}, c.Err -} -func (c credProviderError) IsExpired() bool { - return true -} - -func initHandlers(s *Session) { - // Add the Validate parameter handler if it is not disabled. - s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) - if !aws.BoolValue(s.Config.DisableParamValidation) { - s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) - } -} - -// Copy creates and returns a copy of the current Session, coping the config -// and handlers. If any additional configs are provided they will be merged -// on top of the Session's copied config. -// -// // Create a copy of the current Session, configured for the us-west-2 region. -// sess.Copy(&aws.Config{Region: aws.String("us-west-2")}) -func (s *Session) Copy(cfgs ...*aws.Config) *Session { - newSession := &Session{ - Config: s.Config.Copy(cfgs...), - Handlers: s.Handlers.Copy(), - } - - initHandlers(newSession) - - return newSession -} - -// ClientConfig satisfies the client.ConfigProvider interface and is used to -// configure the service client instances. Passing the Session to the service -// client's constructor (New) will use this method to configure the client. -func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config { - // Backwards compatibility, the error will be eaten if user calls ClientConfig - // directly. All SDK services will use ClientconfigWithError. - cfg, _ := s.clientConfigWithErr(serviceName, cfgs...) - - return cfg -} - -func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) (client.Config, error) { - s = s.Copy(cfgs...) - - var resolved endpoints.ResolvedEndpoint - var err error - - region := aws.StringValue(s.Config.Region) - - if endpoint := aws.StringValue(s.Config.Endpoint); len(endpoint) != 0 { - resolved.URL = endpoints.AddScheme(endpoint, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = region - } else { - resolved, err = s.Config.EndpointResolver.EndpointFor( - serviceName, region, - func(opt *endpoints.Options) { - opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL) - opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack) - - // Support the condition where the service is modeled but its - // endpoint metadata is not available. - opt.ResolveUnknownService = true - }, - ) - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningNameDerived: resolved.SigningNameDerived, - SigningName: resolved.SigningName, - }, err -} - -// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception -// that the EndpointResolver will not be used to resolve the endpoint. The only -// endpoint set must come from the aws.Config.Endpoint field. -func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { - s = s.Copy(cfgs...) - - var resolved endpoints.ResolvedEndpoint - - region := aws.StringValue(s.Config.Region) - - if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { - resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = region - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningNameDerived: resolved.SigningNameDerived, - SigningName: resolved.SigningName, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go deleted file mode 100644 index 09c8e5b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go +++ /dev/null @@ -1,295 +0,0 @@ -package session - -import ( - "fmt" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/go-ini/ini" -) - -const ( - // Static Credentials group - accessKeyIDKey = `aws_access_key_id` // group required - secretAccessKey = `aws_secret_access_key` // group required - sessionTokenKey = `aws_session_token` // optional - - // Assume Role Credentials group - roleArnKey = `role_arn` // group required - sourceProfileKey = `source_profile` // group required - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional - - // Additional Config fields - regionKey = `region` - - // DefaultSharedConfigProfile is the default profile to be used when - // loading configuration from the config files if another profile name - // is not provided. - DefaultSharedConfigProfile = `default` -) - -type assumeRoleConfig struct { - RoleARN string - SourceProfile string - ExternalID string - MFASerial string - RoleSessionName string -} - -// sharedConfig represents the configuration fields of the SDK config files. -type sharedConfig struct { - // Credentials values from the config file. Both aws_access_key_id - // and aws_secret_access_key must be provided together in the same file - // to be considered valid. The values will be ignored if not a complete group. - // aws_session_token is an optional field that can be provided if both of the - // other two fields are also provided. - // - // aws_access_key_id - // aws_secret_access_key - // aws_session_token - Creds credentials.Value - - AssumeRole assumeRoleConfig - AssumeRoleSource *sharedConfig - - // Region is the region the SDK should use for looking up AWS service endpoints - // and signing requests. - // - // region - Region string -} - -type sharedConfigFile struct { - Filename string - IniData *ini.File -} - -// loadSharedConfig retrieves the configuration from the list of files -// using the profile provided. The order the files are listed will determine -// precedence. Values in subsequent files will overwrite values defined in -// earlier files. -// -// For example, given two files A and B. Both define credentials. If the order -// of the files are A then B, B's credential values will be used instead of A's. -// -// See sharedConfig.setFromFile for information how the config files -// will be loaded. -func loadSharedConfig(profile string, filenames []string) (sharedConfig, error) { - if len(profile) == 0 { - profile = DefaultSharedConfigProfile - } - - files, err := loadSharedConfigIniFiles(filenames) - if err != nil { - return sharedConfig{}, err - } - - cfg := sharedConfig{} - if err = cfg.setFromIniFiles(profile, files); err != nil { - return sharedConfig{}, err - } - - if len(cfg.AssumeRole.SourceProfile) > 0 { - if err := cfg.setAssumeRoleSource(profile, files); err != nil { - return sharedConfig{}, err - } - } - - return cfg, nil -} - -func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { - files := make([]sharedConfigFile, 0, len(filenames)) - - for _, filename := range filenames { - b, err := ioutil.ReadFile(filename) - if err != nil { - // Skip files which can't be opened and read for whatever reason - continue - } - - f, err := ini.Load(b) - if err != nil { - return nil, SharedConfigLoadError{Filename: filename, Err: err} - } - - files = append(files, sharedConfigFile{ - Filename: filename, IniData: f, - }) - } - - return files, nil -} - -func (cfg *sharedConfig) setAssumeRoleSource(origProfile string, files []sharedConfigFile) error { - var assumeRoleSrc sharedConfig - - // Multiple level assume role chains are not support - if cfg.AssumeRole.SourceProfile == origProfile { - assumeRoleSrc = *cfg - assumeRoleSrc.AssumeRole = assumeRoleConfig{} - } else { - err := assumeRoleSrc.setFromIniFiles(cfg.AssumeRole.SourceProfile, files) - if err != nil { - return err - } - } - - if len(assumeRoleSrc.Creds.AccessKeyID) == 0 { - return SharedConfigAssumeRoleError{RoleARN: cfg.AssumeRole.RoleARN} - } - - cfg.AssumeRoleSource = &assumeRoleSrc - - return nil -} - -func (cfg *sharedConfig) setFromIniFiles(profile string, files []sharedConfigFile) error { - // Trim files from the list that don't exist. - for _, f := range files { - if err := cfg.setFromIniFile(profile, f); err != nil { - if _, ok := err.(SharedConfigProfileNotExistsError); ok { - // Ignore proviles missings - continue - } - return err - } - } - - return nil -} - -// setFromFile loads the configuration from the file using -// the profile provided. A sharedConfig pointer type value is used so that -// multiple config file loadings can be chained. -// -// Only loads complete logically grouped values, and will not set fields in cfg -// for incomplete grouped values in the config. Such as credentials. For example -// if a config file only includes aws_access_key_id but no aws_secret_access_key -// the aws_access_key_id will be ignored. -func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile) error { - section, err := file.IniData.GetSection(profile) - if err != nil { - // Fallback to to alternate profile name: profile - section, err = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) - if err != nil { - return SharedConfigProfileNotExistsError{Profile: profile, Err: err} - } - } - - // Shared Credentials - akid := section.Key(accessKeyIDKey).String() - secret := section.Key(secretAccessKey).String() - if len(akid) > 0 && len(secret) > 0 { - cfg.Creds = credentials.Value{ - AccessKeyID: akid, - SecretAccessKey: secret, - SessionToken: section.Key(sessionTokenKey).String(), - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename), - } - } - - // Assume Role - roleArn := section.Key(roleArnKey).String() - srcProfile := section.Key(sourceProfileKey).String() - if len(roleArn) > 0 && len(srcProfile) > 0 { - cfg.AssumeRole = assumeRoleConfig{ - RoleARN: roleArn, - SourceProfile: srcProfile, - ExternalID: section.Key(externalIDKey).String(), - MFASerial: section.Key(mfaSerialKey).String(), - RoleSessionName: section.Key(roleSessionNameKey).String(), - } - } - - // Region - if v := section.Key(regionKey).String(); len(v) > 0 { - cfg.Region = v - } - - return nil -} - -// SharedConfigLoadError is an error for the shared config file failed to load. -type SharedConfigLoadError struct { - Filename string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigLoadError) Code() string { - return "SharedConfigLoadError" -} - -// Message is the description of the error -func (e SharedConfigLoadError) Message() string { - return fmt.Sprintf("failed to load config file, %s", e.Filename) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigLoadError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigLoadError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigProfileNotExistsError is an error for the shared config when -// the profile was not find in the config file. -type SharedConfigProfileNotExistsError struct { - Profile string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigProfileNotExistsError) Code() string { - return "SharedConfigProfileNotExistsError" -} - -// Message is the description of the error -func (e SharedConfigProfileNotExistsError) Message() string { - return fmt.Sprintf("failed to get profile, %s", e.Profile) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigProfileNotExistsError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigProfileNotExistsError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigAssumeRoleError is an error for the shared config when the -// profile contains assume role information, but that information is invalid -// or not complete. -type SharedConfigAssumeRoleError struct { - RoleARN string -} - -// Code is the short id of the error. -func (e SharedConfigAssumeRoleError) Code() string { - return "SharedConfigAssumeRoleError" -} - -// Message is the description of the error -func (e SharedConfigAssumeRoleError) Message() string { - return fmt.Sprintf("failed to load assume role for %s, source profile has no shared credentials", - e.RoleARN) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigAssumeRoleError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e SharedConfigAssumeRoleError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go deleted file mode 100644 index 244c86d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go +++ /dev/null @@ -1,82 +0,0 @@ -package v4 - -import ( - "net/http" - "strings" -) - -// validator houses a set of rule needed for validation of a -// string value -type rules []rule - -// rule interface allows for more flexible rules and just simply -// checks whether or not a value adheres to that rule -type rule interface { - IsValid(value string) bool -} - -// IsValid will iterate through all rules and see if any rules -// apply to the value and supports nested rules -func (r rules) IsValid(value string) bool { - for _, rule := range r { - if rule.IsValid(value) { - return true - } - } - return false -} - -// mapRule generic rule for maps -type mapRule map[string]struct{} - -// IsValid for the map rule satisfies whether it exists in the map -func (m mapRule) IsValid(value string) bool { - _, ok := m[value] - return ok -} - -// whitelist is a generic rule for whitelisting -type whitelist struct { - rule -} - -// IsValid for whitelist checks if the value is within the whitelist -func (w whitelist) IsValid(value string) bool { - return w.rule.IsValid(value) -} - -// blacklist is a generic rule for blacklisting -type blacklist struct { - rule -} - -// IsValid for whitelist checks if the value is within the whitelist -func (b blacklist) IsValid(value string) bool { - return !b.rule.IsValid(value) -} - -type patterns []string - -// IsValid for patterns checks each pattern and returns if a match has -// been found -func (p patterns) IsValid(value string) bool { - for _, pattern := range p { - if strings.HasPrefix(http.CanonicalHeaderKey(value), pattern) { - return true - } - } - return false -} - -// inclusiveRules rules allow for rules to depend on one another -type inclusiveRules []rule - -// IsValid will return true if all rules are true -func (r inclusiveRules) IsValid(value string) bool { - for _, rule := range r { - if !rule.IsValid(value) { - return false - } - } - return true -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go deleted file mode 100644 index 6aa2ed2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go +++ /dev/null @@ -1,7 +0,0 @@ -package v4 - -// WithUnsignedPayload will enable and set the UnsignedPayload field to -// true of the signer. -func WithUnsignedPayload(v4 *Signer) { - v4.UnsignedPayload = true -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go deleted file mode 100644 index bd082e9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build go1.5 - -package v4 - -import ( - "net/url" - "strings" -) - -func getURIPath(u *url.URL) string { - var uri string - - if len(u.Opaque) > 0 { - uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") - } else { - uri = u.EscapedPath() - } - - if len(uri) == 0 { - uri = "/" - } - - return uri -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go deleted file mode 100644 index 8aa0681..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ /dev/null @@ -1,788 +0,0 @@ -// Package v4 implements signing for AWS V4 signer -// -// Provides request signing for request that need to be signed with -// AWS V4 Signatures. -// -// Standalone Signer -// -// Generally using the signer outside of the SDK should not require any additional -// logic when using Go v1.5 or higher. The signer does this by taking advantage -// of the URL.EscapedPath method. If your request URI requires additional escaping -// you many need to use the URL.Opaque to define what the raw URI should be sent -// to the service as. -// -// The signer will first check the URL.Opaque field, and use its value if set. -// The signer does require the URL.Opaque field to be set in the form of: -// -// "///" -// -// // e.g. -// "//example.com/some/path" -// -// The leading "//" and hostname are required or the URL.Opaque escaping will -// not work correctly. -// -// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() -// method and using the returned value. If you're using Go v1.4 you must set -// URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with -// Go v1.5 the signer will fallback to URL.Path. -// -// AWS v4 signature validation requires that the canonical string's URI path -// element must be the URI escaped form of the HTTP request's path. -// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html -// -// The Go HTTP client will perform escaping automatically on the request. Some -// of these escaping may cause signature validation errors because the HTTP -// request differs from the URI path or query that the signature was generated. -// https://golang.org/pkg/net/url/#URL.EscapedPath -// -// Because of this, it is recommended that when using the signer outside of the -// SDK that explicitly escaping the request prior to being signed is preferable, -// and will help prevent signature validation errors. This can be done by setting -// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then -// call URL.EscapedPath() if Opaque is not set. -// -// If signing a request intended for HTTP2 server, and you're using Go 1.6.2 -// through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the -// request URL. https://github.com/golang/go/issues/16847 points to a bug in -// Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP -// message. URL.Opaque generally will force Go to make requests with absolute URL. -// URL.RawPath does not do this, but RawPath must be a valid escaping of Path -// or url.EscapedPath will ignore the RawPath escaping. -// -// Test `TestStandaloneSign` provides a complete example of using the signer -// outside of the SDK and pre-escaping the URI path. -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkio" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -const ( - authHeaderPrefix = "AWS4-HMAC-SHA256" - timeFormat = "20060102T150405Z" - shortTimeFormat = "20060102" - - // emptyStringSHA256 is a SHA256 of an empty string - emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` -) - -var ignoredHeaders = rules{ - blacklist{ - mapRule{ - "Authorization": struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - }, - }, -} - -// requiredSignedHeaders is a whitelist for build canonical headers. -var requiredSignedHeaders = rules{ - whitelist{ - mapRule{ - "Cache-Control": struct{}{}, - "Content-Disposition": struct{}{}, - "Content-Encoding": struct{}{}, - "Content-Language": struct{}{}, - "Content-Md5": struct{}{}, - "Content-Type": struct{}{}, - "Expires": struct{}{}, - "If-Match": struct{}{}, - "If-Modified-Since": struct{}{}, - "If-None-Match": struct{}{}, - "If-Unmodified-Since": struct{}{}, - "Range": struct{}{}, - "X-Amz-Acl": struct{}{}, - "X-Amz-Copy-Source": struct{}{}, - "X-Amz-Copy-Source-If-Match": struct{}{}, - "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, - "X-Amz-Copy-Source-If-None-Match": struct{}{}, - "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, - "X-Amz-Copy-Source-Range": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Grant-Full-control": struct{}{}, - "X-Amz-Grant-Read": struct{}{}, - "X-Amz-Grant-Read-Acp": struct{}{}, - "X-Amz-Grant-Write": struct{}{}, - "X-Amz-Grant-Write-Acp": struct{}{}, - "X-Amz-Metadata-Directive": struct{}{}, - "X-Amz-Mfa": struct{}{}, - "X-Amz-Request-Payer": struct{}{}, - "X-Amz-Server-Side-Encryption": struct{}{}, - "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Storage-Class": struct{}{}, - "X-Amz-Website-Redirect-Location": struct{}{}, - "X-Amz-Content-Sha256": struct{}{}, - }, - }, - patterns{"X-Amz-Meta-"}, -} - -// allowedHoisting is a whitelist for build query headers. The boolean value -// represents whether or not it is a pattern. -var allowedQueryHoisting = inclusiveRules{ - blacklist{requiredSignedHeaders}, - patterns{"X-Amz-"}, -} - -// Signer applies AWS v4 signing to given request. Use this to sign requests -// that need to be signed with AWS V4 Signatures. -type Signer struct { - // The authentication credentials the request will be signed against. - // This value must be set to sign requests. - Credentials *credentials.Credentials - - // Sets the log level the signer should use when reporting information to - // the logger. If the logger is nil nothing will be logged. See - // aws.LogLevelType for more information on available logging levels - // - // By default nothing will be logged. - Debug aws.LogLevelType - - // The logger loging information will be written to. If there the logger - // is nil, nothing will be logged. - Logger aws.Logger - - // Disables the Signer's moving HTTP header key/value pairs from the HTTP - // request header to the request's query string. This is most commonly used - // with pre-signed requests preventing headers from being added to the - // request's query string. - DisableHeaderHoisting bool - - // Disables the automatic escaping of the URI path of the request for the - // siganture's canonical string's path. For services that do not need additional - // escaping then use this to disable the signer escaping the path. - // - // S3 is an example of a service that does not need additional escaping. - // - // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - DisableURIPathEscaping bool - - // Disales the automatical setting of the HTTP request's Body field with the - // io.ReadSeeker passed in to the signer. This is useful if you're using a - // custom wrapper around the body for the io.ReadSeeker and want to preserve - // the Body value on the Request.Body. - // - // This does run the risk of signing a request with a body that will not be - // sent in the request. Need to ensure that the underlying data of the Body - // values are the same. - DisableRequestBodyOverwrite bool - - // currentTimeFn returns the time value which represents the current time. - // This value should only be used for testing. If it is nil the default - // time.Now will be used. - currentTimeFn func() time.Time - - // UnsignedPayload will prevent signing of the payload. This will only - // work for services that have support for this. - UnsignedPayload bool -} - -// NewSigner returns a Signer pointer configured with the credentials and optional -// option values provided. If not options are provided the Signer will use its -// default configuration. -func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { - v4 := &Signer{ - Credentials: credentials, - } - - for _, option := range options { - option(v4) - } - - return v4 -} - -type signingCtx struct { - ServiceName string - Region string - Request *http.Request - Body io.ReadSeeker - Query url.Values - Time time.Time - ExpireTime time.Duration - SignedHeaderVals http.Header - - DisableURIPathEscaping bool - - credValues credentials.Value - isPresign bool - formattedTime string - formattedShortTime string - unsignedPayload bool - - bodyDigest string - signedHeaders string - canonicalHeaders string - canonicalString string - credentialString string - stringToSign string - signature string - authorization string -} - -// Sign signs AWS v4 requests with the provided body, service name, region the -// request is made to, and time the request is signed at. The signTime allows -// you to specify that a request is signed for the future, and cannot be -// used until then. -// -// Returns a list of HTTP headers that were included in the signature or an -// error if signing the request failed. Generally for signed requests this value -// is not needed as the full request context will be captured by the http.Request -// value. It is included for reference though. -// -// Sign will set the request's Body to be the `body` parameter passed in. If -// the body is not already an io.ReadCloser, it will be wrapped within one. If -// a `nil` body parameter passed to Sign, the request's Body field will be -// also set to nil. Its important to note that this functionality will not -// change the request's ContentLength of the request. -// -// Sign differs from Presign in that it will sign the request using HTTP -// header values. This type of signing is intended for http.Request values that -// will not be shared, or are shared in a way the header values on the request -// will not be lost. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, 0, false, signTime) -} - -// Presign signs AWS v4 requests with the provided body, service name, region -// the request is made to, and time the request is signed at. The signTime -// allows you to specify that a request is signed for the future, and cannot -// be used until then. -// -// Returns a list of HTTP headers that were included in the signature or an -// error if signing the request failed. For presigned requests these headers -// and their values must be included on the HTTP request when it is made. This -// is helpful to know what header values need to be shared with the party the -// presigned request will be distributed to. -// -// Presign differs from Sign in that it will sign the request using query string -// instead of header values. This allows you to share the Presigned Request's -// URL with third parties, or distribute it throughout your system with minimal -// dependencies. -// -// Presign also takes an exp value which is the duration the -// signed request will be valid after the signing time. This is allows you to -// set when the request will expire. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -// -// Presigning a S3 request will not compute the body's SHA256 hash by default. -// This is done due to the general use case for S3 presigned URLs is to share -// PUT/GET capabilities. If you would like to include the body's SHA256 in the -// presigned request's signature you can set the "X-Amz-Content-Sha256" -// HTTP header and that will be included in the request's signature. -func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, exp, true, signTime) -} - -func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { - currentTimeFn := v4.currentTimeFn - if currentTimeFn == nil { - currentTimeFn = time.Now - } - - ctx := &signingCtx{ - Request: r, - Body: body, - Query: r.URL.Query(), - Time: signTime, - ExpireTime: exp, - isPresign: isPresign, - ServiceName: service, - Region: region, - DisableURIPathEscaping: v4.DisableURIPathEscaping, - unsignedPayload: v4.UnsignedPayload, - } - - for key := range ctx.Query { - sort.Strings(ctx.Query[key]) - } - - if ctx.isRequestSigned() { - ctx.Time = currentTimeFn() - ctx.handlePresignRemoval() - } - - var err error - ctx.credValues, err = v4.Credentials.Get() - if err != nil { - return http.Header{}, err - } - - ctx.sanitizeHostForHeader() - ctx.assignAmzQueryValues() - if err := ctx.build(v4.DisableHeaderHoisting); err != nil { - return nil, err - } - - // If the request is not presigned the body should be attached to it. This - // prevents the confusion of wanting to send a signed request without - // the body the request was signed for attached. - if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { - var reader io.ReadCloser - if body != nil { - var ok bool - if reader, ok = body.(io.ReadCloser); !ok { - reader = ioutil.NopCloser(body) - } - } - r.Body = reader - } - - if v4.Debug.Matches(aws.LogDebugWithSigning) { - v4.logSigningInfo(ctx) - } - - return ctx.SignedHeaderVals, nil -} - -func (ctx *signingCtx) sanitizeHostForHeader() { - request.SanitizeHostForHeader(ctx.Request) -} - -func (ctx *signingCtx) handlePresignRemoval() { - if !ctx.isPresign { - return - } - - // The credentials have expired for this request. The current signing - // is invalid, and needs to be request because the request will fail. - ctx.removePresign() - - // Update the request's query string to ensure the values stays in - // sync in the case retrieving the new credentials fails. - ctx.Request.URL.RawQuery = ctx.Query.Encode() -} - -func (ctx *signingCtx) assignAmzQueryValues() { - if ctx.isPresign { - ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) - if ctx.credValues.SessionToken != "" { - ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } else { - ctx.Query.Del("X-Amz-Security-Token") - } - - return - } - - if ctx.credValues.SessionToken != "" { - ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } -} - -// SignRequestHandler is a named request handler the SDK will use to sign -// service client request with using the V4 signature. -var SignRequestHandler = request.NamedHandler{ - Name: "v4.SignRequestHandler", Fn: SignSDKRequest, -} - -// SignSDKRequest signs an AWS request with the V4 signature. This -// request handler should only be used with the SDK's built in service client's -// API operation requests. -// -// This function should not be used on its on its own, but in conjunction with -// an AWS service client's API operation call. To sign a standalone request -// not created by a service client's API operation method use the "Sign" or -// "Presign" functions of the "Signer" type. -// -// If the credentials of the request's config are set to -// credentials.AnonymousCredentials the request will not be signed. -func SignSDKRequest(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now) -} - -// BuildNamedHandler will build a generic handler for signing. -func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { - return request.NamedHandler{ - Name: name, - Fn: func(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now, opts...) - }, - } -} - -func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { - // If the request does not need to be signed ignore the signing of the - // request if the AnonymousCredentials object is used. - if req.Config.Credentials == credentials.AnonymousCredentials { - return - } - - region := req.ClientInfo.SigningRegion - if region == "" { - region = aws.StringValue(req.Config.Region) - } - - name := req.ClientInfo.SigningName - if name == "" { - name = req.ClientInfo.ServiceName - } - - v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { - v4.Debug = req.Config.LogLevel.Value() - v4.Logger = req.Config.Logger - v4.DisableHeaderHoisting = req.NotHoist - v4.currentTimeFn = curTimeFn - if name == "s3" { - // S3 service should not have any escaping applied - v4.DisableURIPathEscaping = true - } - // Prevents setting the HTTPRequest's Body. Since the Body could be - // wrapped in a custom io.Closer that we do not want to be stompped - // on top of by the signer. - v4.DisableRequestBodyOverwrite = true - }) - - for _, opt := range opts { - opt(v4) - } - - signingTime := req.Time - if !req.LastSignedAt.IsZero() { - signingTime = req.LastSignedAt - } - - signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), - name, region, req.ExpireTime, req.ExpireTime > 0, signingTime, - ) - if err != nil { - req.Error = err - req.SignedHeaderVals = nil - return - } - - req.SignedHeaderVals = signedHeaders - req.LastSignedAt = curTimeFn() -} - -const logSignInfoMsg = `DEBUG: Request Signature: ----[ CANONICAL STRING ]----------------------------- -%s ----[ STRING TO SIGN ]-------------------------------- -%s%s ------------------------------------------------------` -const logSignedURLMsg = ` ----[ SIGNED URL ]------------------------------------ -%s` - -func (v4 *Signer) logSigningInfo(ctx *signingCtx) { - signedURLMsg := "" - if ctx.isPresign { - signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) - } - msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) - v4.Logger.Log(msg) -} - -func (ctx *signingCtx) build(disableHeaderHoisting bool) error { - ctx.buildTime() // no depends - ctx.buildCredentialString() // no depends - - if err := ctx.buildBodyDigest(); err != nil { - return err - } - - unsignedHeaders := ctx.Request.Header - if ctx.isPresign { - if !disableHeaderHoisting { - urlValues := url.Values{} - urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends - for k := range urlValues { - ctx.Query[k] = urlValues[k] - } - } - } - - ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) - ctx.buildCanonicalString() // depends on canon headers / signed headers - ctx.buildStringToSign() // depends on canon string - ctx.buildSignature() // depends on string to sign - - if ctx.isPresign { - ctx.Request.URL.RawQuery += "&X-Amz-Signature=" + ctx.signature - } else { - parts := []string{ - authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, - "SignedHeaders=" + ctx.signedHeaders, - "Signature=" + ctx.signature, - } - ctx.Request.Header.Set("Authorization", strings.Join(parts, ", ")) - } - - return nil -} - -func (ctx *signingCtx) buildTime() { - ctx.formattedTime = ctx.Time.UTC().Format(timeFormat) - ctx.formattedShortTime = ctx.Time.UTC().Format(shortTimeFormat) - - if ctx.isPresign { - duration := int64(ctx.ExpireTime / time.Second) - ctx.Query.Set("X-Amz-Date", ctx.formattedTime) - ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) - } else { - ctx.Request.Header.Set("X-Amz-Date", ctx.formattedTime) - } -} - -func (ctx *signingCtx) buildCredentialString() { - ctx.credentialString = strings.Join([]string{ - ctx.formattedShortTime, - ctx.Region, - ctx.ServiceName, - "aws4_request", - }, "/") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) - } -} - -func buildQuery(r rule, header http.Header) (url.Values, http.Header) { - query := url.Values{} - unsignedHeaders := http.Header{} - for k, h := range header { - if r.IsValid(k) { - query[k] = h - } else { - unsignedHeaders[k] = h - } - } - - return query, unsignedHeaders -} -func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { - var headers []string - headers = append(headers, "host") - for k, v := range header { - canonicalKey := http.CanonicalHeaderKey(k) - if !r.IsValid(canonicalKey) { - continue // ignored header - } - if ctx.SignedHeaderVals == nil { - ctx.SignedHeaderVals = make(http.Header) - } - - lowerCaseKey := strings.ToLower(k) - if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { - // include additional values - ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) - continue - } - - headers = append(headers, lowerCaseKey) - ctx.SignedHeaderVals[lowerCaseKey] = v - } - sort.Strings(headers) - - ctx.signedHeaders = strings.Join(headers, ";") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) - } - - headerValues := make([]string, len(headers)) - for i, k := range headers { - if k == "host" { - if ctx.Request.Host != "" { - headerValues[i] = "host:" + ctx.Request.Host - } else { - headerValues[i] = "host:" + ctx.Request.URL.Host - } - } else { - headerValues[i] = k + ":" + - strings.Join(ctx.SignedHeaderVals[k], ",") - } - } - stripExcessSpaces(headerValues) - ctx.canonicalHeaders = strings.Join(headerValues, "\n") -} - -func (ctx *signingCtx) buildCanonicalString() { - ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) - - uri := getURIPath(ctx.Request.URL) - - if !ctx.DisableURIPathEscaping { - uri = rest.EscapePath(uri, false) - } - - ctx.canonicalString = strings.Join([]string{ - ctx.Request.Method, - uri, - ctx.Request.URL.RawQuery, - ctx.canonicalHeaders + "\n", - ctx.signedHeaders, - ctx.bodyDigest, - }, "\n") -} - -func (ctx *signingCtx) buildStringToSign() { - ctx.stringToSign = strings.Join([]string{ - authHeaderPrefix, - ctx.formattedTime, - ctx.credentialString, - hex.EncodeToString(makeSha256([]byte(ctx.canonicalString))), - }, "\n") -} - -func (ctx *signingCtx) buildSignature() { - secret := ctx.credValues.SecretAccessKey - date := makeHmac([]byte("AWS4"+secret), []byte(ctx.formattedShortTime)) - region := makeHmac(date, []byte(ctx.Region)) - service := makeHmac(region, []byte(ctx.ServiceName)) - credentials := makeHmac(service, []byte("aws4_request")) - signature := makeHmac(credentials, []byte(ctx.stringToSign)) - ctx.signature = hex.EncodeToString(signature) -} - -func (ctx *signingCtx) buildBodyDigest() error { - hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") - if hash == "" { - includeSHA256Header := ctx.unsignedPayload || - ctx.ServiceName == "s3" || - ctx.ServiceName == "glacier" - - s3Presign := ctx.isPresign && ctx.ServiceName == "s3" - - if ctx.unsignedPayload || s3Presign { - hash = "UNSIGNED-PAYLOAD" - includeSHA256Header = !s3Presign - } else if ctx.Body == nil { - hash = emptyStringSHA256 - } else { - if !aws.IsReaderSeekable(ctx.Body) { - return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) - } - hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) - } - - if includeSHA256Header { - ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) - } - } - ctx.bodyDigest = hash - - return nil -} - -// isRequestSigned returns if the request is currently signed or presigned -func (ctx *signingCtx) isRequestSigned() bool { - if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { - return true - } - if ctx.Request.Header.Get("Authorization") != "" { - return true - } - - return false -} - -// unsign removes signing flags for both signed and presigned requests. -func (ctx *signingCtx) removePresign() { - ctx.Query.Del("X-Amz-Algorithm") - ctx.Query.Del("X-Amz-Signature") - ctx.Query.Del("X-Amz-Security-Token") - ctx.Query.Del("X-Amz-Date") - ctx.Query.Del("X-Amz-Expires") - ctx.Query.Del("X-Amz-Credential") - ctx.Query.Del("X-Amz-SignedHeaders") -} - -func makeHmac(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256(data []byte) []byte { - hash := sha256.New() - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256Reader(reader io.ReadSeeker) []byte { - hash := sha256.New() - start, _ := reader.Seek(0, sdkio.SeekCurrent) - defer reader.Seek(start, sdkio.SeekStart) - - io.Copy(hash, reader) - return hash.Sum(nil) -} - -const doubleSpace = " " - -// stripExcessSpaces will rewrite the passed in slice's string values to not -// contain muliple side-by-side spaces. -func stripExcessSpaces(vals []string) { - var j, k, l, m, spaces int - for i, str := range vals { - // Trim trailing spaces - for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { - } - - // Trim leading spaces - for k = 0; k < j && str[k] == ' '; k++ { - } - str = str[k : j+1] - - // Strip multiple spaces. - j = strings.Index(str, doubleSpace) - if j < 0 { - vals[i] = str - continue - } - - buf := []byte(str) - for k, m, l = j, j, len(buf); k < l; k++ { - if buf[k] == ' ' { - if spaces == 0 { - // First space. - buf[m] = buf[k] - m++ - } - spaces++ - } else { - // End of multiple spaces. - spaces = 0 - buf[m] = buf[k] - m++ - } - } - - vals[i] = string(buf[:m]) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/types.go deleted file mode 100644 index 8b6f234..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ /dev/null @@ -1,201 +0,0 @@ -package aws - -import ( - "io" - "sync" - - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -// ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Should -// only be used with an io.Reader that is also an io.Seeker. Doing so may -// cause request signature errors, or request body's not sent for GET, HEAD -// and DELETE HTTP methods. -// -// Deprecated: Should only be used with io.ReadSeeker. If using for -// S3 PutObject to stream content use s3manager.Uploader instead. -func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { - return ReaderSeekerCloser{r} -} - -// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and -// io.Closer interfaces to the underlying object if they are available. -type ReaderSeekerCloser struct { - r io.Reader -} - -// IsReaderSeekable returns if the underlying reader type can be seeked. A -// io.Reader might not actually be seekable if it is the ReaderSeekerCloser -// type. -func IsReaderSeekable(r io.Reader) bool { - switch v := r.(type) { - case ReaderSeekerCloser: - return v.IsSeeker() - case *ReaderSeekerCloser: - return v.IsSeeker() - case io.ReadSeeker: - return true - default: - return false - } -} - -// Read reads from the reader up to size of p. The number of bytes read, and -// error if it occurred will be returned. -// -// If the reader is not an io.Reader zero bytes read, and nil error will be returned. -// -// Performs the same functionality as io.Reader Read -func (r ReaderSeekerCloser) Read(p []byte) (int, error) { - switch t := r.r.(type) { - case io.Reader: - return t.Read(p) - } - return 0, nil -} - -// Seek sets the offset for the next Read to offset, interpreted according to -// whence: 0 means relative to the origin of the file, 1 means relative to the -// current offset, and 2 means relative to the end. Seek returns the new offset -// and an error, if any. -// -// If the ReaderSeekerCloser is not an io.Seeker nothing will be done. -func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { - switch t := r.r.(type) { - case io.Seeker: - return t.Seek(offset, whence) - } - return int64(0), nil -} - -// IsSeeker returns if the underlying reader is also a seeker. -func (r ReaderSeekerCloser) IsSeeker() bool { - _, ok := r.r.(io.Seeker) - return ok -} - -// HasLen returns the length of the underlying reader if the value implements -// the Len() int method. -func (r ReaderSeekerCloser) HasLen() (int, bool) { - type lenner interface { - Len() int - } - - if lr, ok := r.r.(lenner); ok { - return lr.Len(), true - } - - return 0, false -} - -// GetLen returns the length of the bytes remaining in the underlying reader. -// Checks first for Len(), then io.Seeker to determine the size of the -// underlying reader. -// -// Will return -1 if the length cannot be determined. -func (r ReaderSeekerCloser) GetLen() (int64, error) { - if l, ok := r.HasLen(); ok { - return int64(l), nil - } - - if s, ok := r.r.(io.Seeker); ok { - return seekerLen(s) - } - - return -1, nil -} - -// SeekerLen attempts to get the number of bytes remaining at the seeker's -// current position. Returns the number of bytes remaining or error. -func SeekerLen(s io.Seeker) (int64, error) { - // Determine if the seeker is actually seekable. ReaderSeekerCloser - // hides the fact that a io.Readers might not actually be seekable. - switch v := s.(type) { - case ReaderSeekerCloser: - return v.GetLen() - case *ReaderSeekerCloser: - return v.GetLen() - } - - return seekerLen(s) -} - -func seekerLen(s io.Seeker) (int64, error) { - curOffset, err := s.Seek(0, sdkio.SeekCurrent) - if err != nil { - return 0, err - } - - endOffset, err := s.Seek(0, sdkio.SeekEnd) - if err != nil { - return 0, err - } - - _, err = s.Seek(curOffset, sdkio.SeekStart) - if err != nil { - return 0, err - } - - return endOffset - curOffset, nil -} - -// Close closes the ReaderSeekerCloser. -// -// If the ReaderSeekerCloser is not an io.Closer nothing will be done. -func (r ReaderSeekerCloser) Close() error { - switch t := r.r.(type) { - case io.Closer: - return t.Close() - } - return nil -} - -// A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface -// Can be used with the s3manager.Downloader to download content to a buffer -// in memory. Safe to use concurrently. -type WriteAtBuffer struct { - buf []byte - m sync.Mutex - - // GrowthCoeff defines the growth rate of the internal buffer. By - // default, the growth rate is 1, where expanding the internal - // buffer will allocate only enough capacity to fit the new expected - // length. - GrowthCoeff float64 -} - -// NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer -// provided by buf. -func NewWriteAtBuffer(buf []byte) *WriteAtBuffer { - return &WriteAtBuffer{buf: buf} -} - -// WriteAt writes a slice of bytes to a buffer starting at the position provided -// The number of bytes written will be returned, or error. Can overwrite previous -// written slices if the write ats overlap. -func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { - pLen := len(p) - expLen := pos + int64(pLen) - b.m.Lock() - defer b.m.Unlock() - if int64(len(b.buf)) < expLen { - if int64(cap(b.buf)) < expLen { - if b.GrowthCoeff < 1 { - b.GrowthCoeff = 1 - } - newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen))) - copy(newBuf, b.buf) - b.buf = newBuf - } - b.buf = b.buf[:expLen] - } - copy(b.buf[pos:], p) - return pLen, nil -} - -// Bytes returns a slice of bytes written to the buffer. -func (b *WriteAtBuffer) Bytes() []byte { - b.m.Lock() - defer b.m.Unlock() - return b.buf -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/url.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/url.go deleted file mode 100644 index 6192b24..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/url.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build go1.8 - -package aws - -import "net/url" - -// URLHostname will extract the Hostname without port from the URL value. -// -// Wrapper of net/url#URL.Hostname for backwards Go version compatibility. -func URLHostname(url *url.URL) string { - return url.Hostname() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go deleted file mode 100644 index 0210d27..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build !go1.8 - -package aws - -import ( - "net/url" - "strings" -) - -// URLHostname will extract the Hostname without port from the URL value. -// -// Copy of Go 1.8's net/url#URL.Hostname functionality. -func URLHostname(url *url.URL) string { - return stripPort(url.Host) - -} - -// stripPort is copy of Go 1.8 url#URL.Hostname functionality. -// https://golang.org/src/net/url/url.go -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/version.go deleted file mode 100644 index dc9bcab..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package aws provides core functionality for making requests to AWS services. -package aws - -// SDKName is the name of this AWS SDK -const SDKName = "aws-sdk-go" - -// SDKVersion is the version of this SDK -const SDKVersion = "1.15.23" diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go deleted file mode 100644 index 5aa9137..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !go1.7 - -package sdkio - -// Copy of Go 1.7 io package's Seeker constants. -const ( - SeekStart = 0 // seek relative to the origin of the file - SeekCurrent = 1 // seek relative to the current offset - SeekEnd = 2 // seek relative to the end -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go deleted file mode 100644 index e5f0056..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build go1.7 - -package sdkio - -import "io" - -// Alias for Go 1.7 io package Seeker constants -const ( - SeekStart = io.SeekStart // seek relative to the origin of the file - SeekCurrent = io.SeekCurrent // seek relative to the current offset - SeekEnd = io.SeekEnd // seek relative to the end -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go deleted file mode 100644 index 0c9802d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go +++ /dev/null @@ -1,29 +0,0 @@ -package sdkrand - -import ( - "math/rand" - "sync" - "time" -) - -// lockedSource is a thread-safe implementation of rand.Source -type lockedSource struct { - lk sync.Mutex - src rand.Source -} - -func (r *lockedSource) Int63() (n int64) { - r.lk.Lock() - n = r.src.Int63() - r.lk.Unlock() - return -} - -func (r *lockedSource) Seed(seed int64) { - r.lk.Lock() - r.src.Seed(seed) - r.lk.Unlock() -} - -// SeededRand is a new RNG using a thread safe implementation of rand.Source -var SeededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go deleted file mode 100644 index 38ea61a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go +++ /dev/null @@ -1,23 +0,0 @@ -package sdkuri - -import ( - "path" - "strings" -) - -// PathJoin will join the elements of the path delimited by the "/" -// character. Similar to path.Join with the exception the trailing "/" -// character is preserved if present. -func PathJoin(elems ...string) string { - if len(elems) == 0 { - return "" - } - - hasTrailing := strings.HasSuffix(elems[len(elems)-1], "/") - str := path.Join(elems...) - if hasTrailing && str != "/" { - str += "/" - } - - return str -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go deleted file mode 100644 index ebcbc2b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults - -import ( - "os" - "path/filepath" - "runtime" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "credentials") -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "config") -} - -// UserHomeDir returns the home directory for the user the process is -// running under. -func UserHomeDir() string { - if runtime.GOOS == "windows" { // Windows - return os.Getenv("USERPROFILE") - } - - // *nix - return os.Getenv("HOME") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go deleted file mode 100644 index 53831df..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go +++ /dev/null @@ -1,75 +0,0 @@ -package protocol - -import ( - "crypto/rand" - "fmt" - "reflect" -) - -// RandReader is the random reader the protocol package will use to read -// random bytes from. This is exported for testing, and should not be used. -var RandReader = rand.Reader - -const idempotencyTokenFillTag = `idempotencyToken` - -// CanSetIdempotencyToken returns true if the struct field should be -// automatically populated with a Idempotency token. -// -// Only *string and string type fields that are tagged with idempotencyToken -// which are not already set can be auto filled. -func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool { - switch u := v.Interface().(type) { - // To auto fill an Idempotency token the field must be a string, - // tagged for auto fill, and have a zero value. - case *string: - return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - case string: - return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - } - - return false -} - -// GetIdempotencyToken returns a randomly generated idempotency token. -func GetIdempotencyToken() string { - b := make([]byte, 16) - RandReader.Read(b) - - return UUIDVersion4(b) -} - -// SetIdempotencyToken will set the value provided with a Idempotency Token. -// Given that the value can be set. Will panic if value is not setable. -func SetIdempotencyToken(v reflect.Value) { - if v.Kind() == reflect.Ptr { - if v.IsNil() && v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - v = reflect.Indirect(v) - - if !v.CanSet() { - panic(fmt.Sprintf("unable to set idempotnecy token %v", v)) - } - - b := make([]byte, 16) - _, err := rand.Read(b) - if err != nil { - // TODO handle error - return - } - - v.Set(reflect.ValueOf(UUIDVersion4(b))) -} - -// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided -func UUIDVersion4(u []byte) string { - // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 - // 13th character is "4" - u[6] = (u[6] | 0x40) & 0x4F - // 17th character is "8", "9", "a", or "b" - u[8] = (u[8] | 0x80) & 0xBF - - return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go deleted file mode 100644 index 864fb67..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go +++ /dev/null @@ -1,296 +0,0 @@ -// Package jsonutil provides JSON serialization of AWS requests and responses. -package jsonutil - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/private/protocol" -) - -var timeType = reflect.ValueOf(time.Time{}).Type() -var byteSliceType = reflect.ValueOf([]byte{}).Type() - -// BuildJSON builds a JSON string for a given object v. -func BuildJSON(v interface{}) ([]byte, error) { - var buf bytes.Buffer - - err := buildAny(reflect.ValueOf(v), &buf, "") - return buf.Bytes(), err -} - -func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - origVal := value - value = reflect.Indirect(value) - if !value.IsValid() { - return nil - } - - vtype := value.Type() - - t := tag.Get("type") - if t == "" { - switch vtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if value.Type() != timeType { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := value.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - // cannot be a JSONValue map - if _, ok := value.Interface().(aws.JSONValue); !ok { - t = "map" - } - } - } - - switch t { - case "structure": - if field, ok := vtype.FieldByName("_"); ok { - tag = field.Tag - } - return buildStruct(value, buf, tag) - case "list": - return buildList(value, buf, tag) - case "map": - return buildMap(value, buf, tag) - default: - return buildScalar(origVal, buf, tag) - } -} - -func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - buf.WriteByte('{') - - t := value.Type() - first := true - for i := 0; i < t.NumField(); i++ { - member := value.Field(i) - - // This allocates the most memory. - // Additionally, we cannot skip nil fields due to - // idempotency auto filling. - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("json") == "-" { - continue - } - if field.Tag.Get("location") != "" { - continue // ignore non-body elements - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(member, field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(&token) - } - - if (member.Kind() == reflect.Ptr || member.Kind() == reflect.Slice || member.Kind() == reflect.Map) && member.IsNil() { - continue // ignore unset fields - } - - if first { - first = false - } else { - buf.WriteByte(',') - } - - // figure out what this field is called - name := field.Name - if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - writeString(name, buf) - buf.WriteString(`:`) - - err := buildAny(member, buf, field.Tag) - if err != nil { - return err - } - - } - - buf.WriteString("}") - - return nil -} - -func buildList(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - buf.WriteString("[") - - for i := 0; i < value.Len(); i++ { - buildAny(value.Index(i), buf, "") - - if i < value.Len()-1 { - buf.WriteString(",") - } - } - - buf.WriteString("]") - - return nil -} - -type sortedValues []reflect.Value - -func (sv sortedValues) Len() int { return len(sv) } -func (sv sortedValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv sortedValues) Less(i, j int) bool { return sv[i].String() < sv[j].String() } - -func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - buf.WriteString("{") - - sv := sortedValues(value.MapKeys()) - sort.Sort(sv) - - for i, k := range sv { - if i > 0 { - buf.WriteByte(',') - } - - writeString(k.String(), buf) - buf.WriteString(`:`) - - buildAny(value.MapIndex(k), buf, "") - } - - buf.WriteString("}") - - return nil -} - -func buildScalar(v reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - // prevents allocation on the heap. - scratch := [64]byte{} - switch value := reflect.Indirect(v); value.Kind() { - case reflect.String: - writeString(value.String(), buf) - case reflect.Bool: - if value.Bool() { - buf.WriteString("true") - } else { - buf.WriteString("false") - } - case reflect.Int64: - buf.Write(strconv.AppendInt(scratch[:0], value.Int(), 10)) - case reflect.Float64: - f := value.Float() - if math.IsInf(f, 0) || math.IsNaN(f) { - return &json.UnsupportedValueError{Value: v, Str: strconv.FormatFloat(f, 'f', -1, 64)} - } - buf.Write(strconv.AppendFloat(scratch[:0], f, 'f', -1, 64)) - default: - switch converted := value.Interface().(type) { - case time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.UnixTimeFormatName - } - - ts := protocol.FormatTime(format, converted) - if format != protocol.UnixTimeFormatName { - ts = `"` + ts + `"` - } - - buf.WriteString(ts) - case []byte: - if !value.IsNil() { - buf.WriteByte('"') - if len(converted) < 1024 { - // for small buffers, using Encode directly is much faster. - dst := make([]byte, base64.StdEncoding.EncodedLen(len(converted))) - base64.StdEncoding.Encode(dst, converted) - buf.Write(dst) - } else { - // for large buffers, avoid unnecessary extra temporary - // buffer space. - enc := base64.NewEncoder(base64.StdEncoding, buf) - enc.Write(converted) - enc.Close() - } - buf.WriteByte('"') - } - case aws.JSONValue: - str, err := protocol.EncodeJSONValue(converted, protocol.QuotedEscape) - if err != nil { - return fmt.Errorf("unable to encode JSONValue, %v", err) - } - buf.WriteString(str) - default: - return fmt.Errorf("unsupported JSON value %v (%s)", value.Interface(), value.Type()) - } - } - return nil -} - -var hex = "0123456789abcdef" - -func writeString(s string, buf *bytes.Buffer) { - buf.WriteByte('"') - for i := 0; i < len(s); i++ { - if s[i] == '"' { - buf.WriteString(`\"`) - } else if s[i] == '\\' { - buf.WriteString(`\\`) - } else if s[i] == '\b' { - buf.WriteString(`\b`) - } else if s[i] == '\f' { - buf.WriteString(`\f`) - } else if s[i] == '\r' { - buf.WriteString(`\r`) - } else if s[i] == '\t' { - buf.WriteString(`\t`) - } else if s[i] == '\n' { - buf.WriteString(`\n`) - } else if s[i] < 32 { - buf.WriteString("\\u00") - buf.WriteByte(hex[s[i]>>4]) - buf.WriteByte(hex[s[i]&0xF]) - } else { - buf.WriteByte(s[i]) - } - } - buf.WriteByte('"') -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go deleted file mode 100644 index 2f6628d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go +++ /dev/null @@ -1,235 +0,0 @@ -package jsonutil - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "reflect" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalJSON reads a stream and unmarshals the results in object v. -func UnmarshalJSON(v interface{}, stream io.Reader) error { - var out interface{} - - b, err := ioutil.ReadAll(stream) - if err != nil { - return err - } - - if len(b) == 0 { - return nil - } - - if err := json.Unmarshal(b, &out); err != nil { - return err - } - - return unmarshalAny(reflect.ValueOf(v), out, "") -} - -func unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error { - vtype := value.Type() - if vtype.Kind() == reflect.Ptr { - vtype = vtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch vtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if _, ok := value.Interface().(*time.Time); !ok { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := value.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - // cannot be a JSONValue map - if _, ok := value.Interface().(aws.JSONValue); !ok { - t = "map" - } - } - } - - switch t { - case "structure": - if field, ok := vtype.FieldByName("_"); ok { - tag = field.Tag - } - return unmarshalStruct(value, data, tag) - case "list": - return unmarshalList(value, data, tag) - case "map": - return unmarshalMap(value, data, tag) - default: - return unmarshalScalar(value, data, tag) - } -} - -func unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - mapData, ok := data.(map[string]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a structure (%#v)", data) - } - - t := value.Type() - if value.Kind() == reflect.Ptr { - if value.IsNil() { // create the structure if it's nil - s := reflect.New(value.Type().Elem()) - value.Set(s) - value = s - } - - value = value.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return unmarshalAny(value.FieldByName(payload), data, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.PkgPath != "" { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - member := value.FieldByIndex(field.Index) - err := unmarshalAny(member, mapData[name], field.Tag) - if err != nil { - return err - } - } - return nil -} - -func unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - listData, ok := data.([]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a list (%#v)", data) - } - - if value.IsNil() { - l := len(listData) - value.Set(reflect.MakeSlice(value.Type(), l, l)) - } - - for i, c := range listData { - err := unmarshalAny(value.Index(i), c, "") - if err != nil { - return err - } - } - - return nil -} - -func unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - mapData, ok := data.(map[string]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a map (%#v)", data) - } - - if value.IsNil() { - value.Set(reflect.MakeMap(value.Type())) - } - - for k, v := range mapData { - kvalue := reflect.ValueOf(k) - vvalue := reflect.New(value.Type().Elem()).Elem() - - unmarshalAny(vvalue, v, "") - value.SetMapIndex(kvalue, vvalue) - } - - return nil -} - -func unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error { - - switch d := data.(type) { - case nil: - return nil // nothing to do here - case string: - switch value.Interface().(type) { - case *string: - value.Set(reflect.ValueOf(&d)) - case []byte: - b, err := base64.StdEncoding.DecodeString(d) - if err != nil { - return err - } - value.Set(reflect.ValueOf(b)) - case *time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - t, err := protocol.ParseTime(format, d) - if err != nil { - return err - } - value.Set(reflect.ValueOf(&t)) - case aws.JSONValue: - // No need to use escaping as the value is a non-quoted string. - v, err := protocol.DecodeJSONValue(d, protocol.NoEscape) - if err != nil { - return err - } - value.Set(reflect.ValueOf(v)) - default: - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - case float64: - switch value.Interface().(type) { - case *int64: - di := int64(d) - value.Set(reflect.ValueOf(&di)) - case *float64: - value.Set(reflect.ValueOf(&d)) - case *time.Time: - // Time unmarshaled from a float64 can only be epoch seconds - t := time.Unix(int64(d), 0).UTC() - value.Set(reflect.ValueOf(&t)) - default: - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - case bool: - switch value.Interface().(type) { - case *bool: - value.Set(reflect.ValueOf(&d)) - default: - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - default: - return fmt.Errorf("unsupported JSON value (%v)", data) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go deleted file mode 100644 index 56af4dc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package jsonrpc provides JSON RPC utilities for serialization of AWS -// requests and responses. -package jsonrpc - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/json.json build_test.go -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/json.json unmarshal_test.go - -import ( - "encoding/json" - "io/ioutil" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -var emptyJSON = []byte("{}") - -// BuildHandler is a named request handler for building jsonrpc protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Build", Fn: Build} - -// UnmarshalHandler is a named request handler for unmarshaling jsonrpc protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalMeta", Fn: UnmarshalMeta} - -// UnmarshalErrorHandler is a named request handler for unmarshaling jsonrpc protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalError", Fn: UnmarshalError} - -// Build builds a JSON payload for a JSON RPC request. -func Build(req *request.Request) { - var buf []byte - var err error - if req.ParamsFilled() { - buf, err = jsonutil.BuildJSON(req.Params) - if err != nil { - req.Error = awserr.New("SerializationError", "failed encoding JSON RPC request", err) - return - } - } else { - buf = emptyJSON - } - - if req.ClientInfo.TargetPrefix != "" || string(buf) != "{}" { - req.SetBufferBody(buf) - } - - if req.ClientInfo.TargetPrefix != "" { - target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name - req.HTTPRequest.Header.Add("X-Amz-Target", target) - } - if req.ClientInfo.JSONVersion != "" { - jsonVersion := req.ClientInfo.JSONVersion - req.HTTPRequest.Header.Add("Content-Type", "application/x-amz-json-"+jsonVersion) - } -} - -// Unmarshal unmarshals a response for a JSON RPC service. -func Unmarshal(req *request.Request) { - defer req.HTTPResponse.Body.Close() - if req.DataFilled() { - err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("SerializationError", "failed decoding JSON RPC response", err) - } - } - return -} - -// UnmarshalMeta unmarshals headers from a response for a JSON RPC service. -func UnmarshalMeta(req *request.Request) { - rest.UnmarshalMeta(req) -} - -// UnmarshalError unmarshals an error response for a JSON RPC service. -func UnmarshalError(req *request.Request) { - defer req.HTTPResponse.Body.Close() - bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("SerializationError", "failed reading JSON RPC error response", err) - return - } - if len(bodyBytes) == 0 { - req.Error = awserr.NewRequestFailure( - awserr.New("SerializationError", req.HTTPResponse.Status, nil), - req.HTTPResponse.StatusCode, - "", - ) - return - } - var jsonErr jsonErrorResponse - if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = awserr.New("SerializationError", "failed decoding JSON RPC error response", err) - return - } - - codes := strings.SplitN(jsonErr.Code, "#", 2) - req.Error = awserr.NewRequestFailure( - awserr.New(codes[len(codes)-1], jsonErr.Message, nil), - req.HTTPResponse.StatusCode, - req.RequestID, - ) -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go deleted file mode 100644 index 776d110..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go +++ /dev/null @@ -1,76 +0,0 @@ -package protocol - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "strconv" - - "github.com/aws/aws-sdk-go/aws" -) - -// EscapeMode is the mode that should be use for escaping a value -type EscapeMode uint - -// The modes for escaping a value before it is marshaled, and unmarshaled. -const ( - NoEscape EscapeMode = iota - Base64Escape - QuotedEscape -) - -// EncodeJSONValue marshals the value into a JSON string, and optionally base64 -// encodes the string before returning it. -// -// Will panic if the escape mode is unknown. -func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) { - b, err := json.Marshal(v) - if err != nil { - return "", err - } - - switch escape { - case NoEscape: - return string(b), nil - case Base64Escape: - return base64.StdEncoding.EncodeToString(b), nil - case QuotedEscape: - return strconv.Quote(string(b)), nil - } - - panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape)) -} - -// DecodeJSONValue will attempt to decode the string input as a JSONValue. -// Optionally decoding base64 the value first before JSON unmarshaling. -// -// Will panic if the escape mode is unknown. -func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) { - var b []byte - var err error - - switch escape { - case NoEscape: - b = []byte(v) - case Base64Escape: - b, err = base64.StdEncoding.DecodeString(v) - case QuotedEscape: - var u string - u, err = strconv.Unquote(v) - b = []byte(u) - default: - panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape)) - } - - if err != nil { - return nil, err - } - - m := aws.JSONValue{} - err = json.Unmarshal(b, &m) - if err != nil { - return nil, err - } - - return m, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go deleted file mode 100644 index e21614a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go +++ /dev/null @@ -1,81 +0,0 @@ -package protocol - -import ( - "io" - "io/ioutil" - "net/http" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// PayloadUnmarshaler provides the interface for unmarshaling a payload's -// reader into a SDK shape. -type PayloadUnmarshaler interface { - UnmarshalPayload(io.Reader, interface{}) error -} - -// HandlerPayloadUnmarshal implements the PayloadUnmarshaler from a -// HandlerList. This provides the support for unmarshaling a payload reader to -// a shape without needing a SDK request first. -type HandlerPayloadUnmarshal struct { - Unmarshalers request.HandlerList -} - -// UnmarshalPayload unmarshals the io.Reader payload into the SDK shape using -// the Unmarshalers HandlerList provided. Returns an error if unable -// unmarshaling fails. -func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error { - req := &request.Request{ - HTTPRequest: &http.Request{}, - HTTPResponse: &http.Response{ - StatusCode: 200, - Header: http.Header{}, - Body: ioutil.NopCloser(r), - }, - Data: v, - } - - h.Unmarshalers.Run(req) - - return req.Error -} - -// PayloadMarshaler provides the interface for marshaling a SDK shape into and -// io.Writer. -type PayloadMarshaler interface { - MarshalPayload(io.Writer, interface{}) error -} - -// HandlerPayloadMarshal implements the PayloadMarshaler from a HandlerList. -// This provides support for marshaling a SDK shape into an io.Writer without -// needing a SDK request first. -type HandlerPayloadMarshal struct { - Marshalers request.HandlerList -} - -// MarshalPayload marshals the SDK shape into the io.Writer using the -// Marshalers HandlerList provided. Returns an error if unable if marshal -// fails. -func (h HandlerPayloadMarshal) MarshalPayload(w io.Writer, v interface{}) error { - req := request.New( - aws.Config{}, - metadata.ClientInfo{}, - request.Handlers{}, - nil, - &request.Operation{HTTPMethod: "GET"}, - v, - nil, - ) - - h.Marshalers.Run(req) - - if req.Error != nil { - return req.Error - } - - io.Copy(w, req.GetBody()) - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go deleted file mode 100644 index 60e5b09..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go +++ /dev/null @@ -1,36 +0,0 @@ -// Package query provides serialization of AWS query requests, and responses. -package query - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/query.json build_test.go - -import ( - "net/url" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query/queryutil" -) - -// BuildHandler is a named request handler for building query protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.query.Build", Fn: Build} - -// Build builds a request for an AWS Query service. -func Build(r *request.Request) { - body := url.Values{ - "Action": {r.Operation.Name}, - "Version": {r.ClientInfo.APIVersion}, - } - if err := queryutil.Parse(body, r.Params, false); err != nil { - r.Error = awserr.New("SerializationError", "failed encoding Query request", err) - return - } - - if !r.IsPresigned() { - r.HTTPRequest.Method = "POST" - r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") - r.SetBufferBody([]byte(body.Encode())) - } else { // This is a pre-signed request - r.HTTPRequest.Method = "GET" - r.HTTPRequest.URL.RawQuery = body.Encode() - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go deleted file mode 100644 index 75866d0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go +++ /dev/null @@ -1,246 +0,0 @@ -package queryutil - -import ( - "encoding/base64" - "fmt" - "net/url" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// Parse parses an object i and fills a url.Values object. The isEC2 flag -// indicates if this is the EC2 Query sub-protocol. -func Parse(body url.Values, i interface{}, isEC2 bool) error { - q := queryParser{isEC2: isEC2} - return q.parseValue(body, reflect.ValueOf(i), "", "") -} - -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -type queryParser struct { - isEC2 bool -} - -func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - value = elemOf(value) - - // no need to handle zero values - if !value.IsValid() { - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - return q.parseStruct(v, value, prefix) - case "list": - return q.parseList(v, value, prefix, tag) - case "map": - return q.parseMap(v, value, prefix, tag) - default: - return q.parseScalar(v, value, prefix, tag) - } -} - -func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error { - if !value.IsValid() { - return nil - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - elemValue := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - elemValue = reflect.ValueOf(token) - } - - var name string - if q.isEC2 { - name = field.Tag.Get("queryName") - } - if name == "" { - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - if name != "" && q.isEC2 { - name = strings.ToUpper(name[0:1]) + name[1:] - } - } - if name == "" { - name = field.Name - } - - if prefix != "" { - name = prefix + "." + name - } - - if err := q.parseValue(v, elemValue, name, field.Tag); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - if _, ok := value.Interface().([]byte); ok { - return q.parseScalar(v, value, prefix, tag) - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - if listName := tag.Get("locationNameList"); listName == "" { - prefix += ".member" - } else { - prefix += "." + listName - } - } - - for i := 0; i < value.Len(); i++ { - slicePrefix := prefix - if slicePrefix == "" { - slicePrefix = strconv.Itoa(i + 1) - } else { - slicePrefix = slicePrefix + "." + strconv.Itoa(i+1) - } - if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".entry" - } - - // sort keys for improved serialization consistency. - // this is not strictly necessary for protocol support. - mapKeyValues := value.MapKeys() - mapKeys := map[string]reflect.Value{} - mapKeyNames := make([]string, len(mapKeyValues)) - for i, mapKey := range mapKeyValues { - name := mapKey.String() - mapKeys[name] = mapKey - mapKeyNames[i] = name - } - sort.Strings(mapKeyNames) - - for i, mapKeyName := range mapKeyNames { - mapKey := mapKeys[mapKeyName] - mapValue := value.MapIndex(mapKey) - - kname := tag.Get("locationNameKey") - if kname == "" { - kname = "key" - } - vname := tag.Get("locationNameValue") - if vname == "" { - vname = "value" - } - - // serialize key - var keyName string - if prefix == "" { - keyName = strconv.Itoa(i+1) + "." + kname - } else { - keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname - } - - if err := q.parseValue(v, mapKey, keyName, ""); err != nil { - return err - } - - // serialize value - var valueName string - if prefix == "" { - valueName = strconv.Itoa(i+1) + "." + vname - } else { - valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname - } - - if err := q.parseValue(v, mapValue, valueName, ""); err != nil { - return err - } - } - - return nil -} - -func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error { - switch value := r.Interface().(type) { - case string: - v.Set(name, value) - case []byte: - if !r.IsNil() { - v.Set(name, base64.StdEncoding.EncodeToString(value)) - } - case bool: - v.Set(name, strconv.FormatBool(value)) - case int64: - v.Set(name, strconv.FormatInt(value, 10)) - case int: - v.Set(name, strconv.Itoa(value)) - case float64: - v.Set(name, strconv.FormatFloat(value, 'f', -1, 64)) - case float32: - v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32)) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - v.Set(name, protocol.FormatTime(format, value)) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go deleted file mode 100644 index e0f4d5a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go +++ /dev/null @@ -1,35 +0,0 @@ -package query - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/query.json unmarshal_test.go - -import ( - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// UnmarshalHandler is a named request handler for unmarshaling query protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.query.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling query protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals a response for an AWS Query service. -func Unmarshal(r *request.Request) { - defer r.HTTPResponse.Body.Close() - if r.DataFilled() { - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") - if err != nil { - r.Error = awserr.New("SerializationError", "failed decoding Query response", err) - return - } - } -} - -// UnmarshalMeta unmarshals header response values for an AWS Query service. -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go deleted file mode 100644 index f214296..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go +++ /dev/null @@ -1,66 +0,0 @@ -package query - -import ( - "encoding/xml" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -type xmlErrorResponse struct { - XMLName xml.Name `xml:"ErrorResponse"` - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -type xmlServiceUnavailableResponse struct { - XMLName xml.Name `xml:"ServiceUnavailableException"` -} - -// UnmarshalErrorHandler is a name request handler to unmarshal request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalError", Fn: UnmarshalError} - -// UnmarshalError unmarshals an error response for an AWS Query service. -func UnmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to read from query HTTP response body", err) - return - } - - // First check for specific error - resp := xmlErrorResponse{} - decodeErr := xml.Unmarshal(bodyBytes, &resp) - if decodeErr == nil { - reqID := resp.RequestID - if reqID == "" { - reqID = r.RequestID - } - r.Error = awserr.NewRequestFailure( - awserr.New(resp.Code, resp.Message, nil), - r.HTTPResponse.StatusCode, - reqID, - ) - return - } - - // Check for unhandled error - servUnavailResp := xmlServiceUnavailableResponse{} - unavailErr := xml.Unmarshal(bodyBytes, &servUnavailResp) - if unavailErr == nil { - r.Error = awserr.NewRequestFailure( - awserr.New("ServiceUnavailableException", "service is unavailable", nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - - // Failed to retrieve any error message from the response body - r.Error = awserr.New("SerializationError", - "failed to decode query XML error response", decodeErr) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go deleted file mode 100644 index b34f525..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ /dev/null @@ -1,295 +0,0 @@ -// Package rest provides RESTful serialization of AWS requests and responses. -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "net/http" - "net/url" - "path" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// Whether the byte value can be sent without escaping in AWS URLs -var noEscape [256]bool - -var errValueNotSet = fmt.Errorf("value not set") - -func init() { - for i := 0; i < len(noEscape); i++ { - // AWS expects every character except these to be escaped - noEscape[i] = (i >= 'A' && i <= 'Z') || - (i >= 'a' && i <= 'z') || - (i >= '0' && i <= '9') || - i == '-' || - i == '.' || - i == '_' || - i == '~' - } -} - -// BuildHandler is a named request handler for building rest protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build} - -// Build builds the REST component of a service request. -func Build(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, false) - buildBody(r, v) - } -} - -// BuildAsGET builds the REST component of a service request with the ability to hoist -// data from the body. -func BuildAsGET(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, true) - buildBody(r, v) - } -} - -func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { - query := r.HTTPRequest.URL.Query() - - // Setup the raw path to match the base path pattern. This is needed - // so that when the path is mutated a custom escaped version can be - // stored in RawPath that will be used by the Go client. - r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path - - for i := 0; i < v.NumField(); i++ { - m := v.Field(i) - if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - field := v.Type().Field(i) - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - if kind := m.Kind(); kind == reflect.Ptr { - m = m.Elem() - } else if kind == reflect.Interface { - if !m.Elem().IsValid() { - continue - } - } - if !m.IsValid() { - continue - } - if field.Tag.Get("ignore") != "" { - continue - } - - var err error - switch field.Tag.Get("location") { - case "headers": // header maps - err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) - case "header": - err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) - case "uri": - err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) - case "querystring": - err = buildQueryString(query, m, name, field.Tag) - default: - if buildGETQuery { - err = buildQueryString(query, m, name, field.Tag) - } - } - r.Error = err - } - if r.Error != nil { - return - } - } - - r.HTTPRequest.URL.RawQuery = query.Encode() - if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) { - cleanPath(r.HTTPRequest.URL) - } -} - -func buildBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := reflect.Indirect(v.FieldByName(payloadName)) - if payload.IsValid() && payload.Interface() != nil { - switch reader := payload.Interface().(type) { - case io.ReadSeeker: - r.SetReaderBody(reader) - case []byte: - r.SetBufferBody(reader) - case string: - r.SetStringBody(reader) - default: - r.Error = awserr.New("SerializationError", - "failed to encode REST request", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } -} - -func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - - header.Add(name, str) - - return nil -} - -func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { - prefix := tag.Get("locationName") - for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key), tag) - if err == errValueNotSet { - continue - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - - } - - header.Add(prefix+key.String(), str) - } - return nil -} - -func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { - value, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - - u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1) - u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1) - - u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1) - u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1) - - return nil -} - -func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { - switch value := v.Interface().(type) { - case []*string: - for _, item := range value { - query.Add(name, *item) - } - case map[string]*string: - for key, item := range value { - query.Add(key, *item) - } - case map[string][]*string: - for key, items := range value { - for _, item := range items { - query.Add(key, *item) - } - } - default: - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - query.Set(name, str) - } - - return nil -} - -func cleanPath(u *url.URL) { - hasSlash := strings.HasSuffix(u.Path, "/") - - // clean up path, removing duplicate `/` - u.Path = path.Clean(u.Path) - u.RawPath = path.Clean(u.RawPath) - - if hasSlash && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - u.RawPath += "/" - } -} - -// EscapePath escapes part of a URL path in Amazon style -func EscapePath(path string, encodeSep bool) string { - var buf bytes.Buffer - for i := 0; i < len(path); i++ { - c := path[i] - if noEscape[c] || (c == '/' && !encodeSep) { - buf.WriteByte(c) - } else { - fmt.Fprintf(&buf, "%%%02X", c) - } - } - return buf.String() -} - -func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) { - v = reflect.Indirect(v) - if !v.IsValid() { - return "", errValueNotSet - } - - switch value := v.Interface().(type) { - case string: - str = value - case []byte: - str = base64.StdEncoding.EncodeToString(value) - case bool: - str = strconv.FormatBool(value) - case int64: - str = strconv.FormatInt(value, 10) - case float64: - str = strconv.FormatFloat(value, 'f', -1, 64) - case time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.RFC822TimeFormatName - if tag.Get("location") == "querystring" { - format = protocol.ISO8601TimeFormatName - } - } - str = protocol.FormatTime(format, value) - case aws.JSONValue: - if len(value) == 0 { - return "", errValueNotSet - } - escaping := protocol.NoEscape - if tag.Get("location") == "header" { - escaping = protocol.Base64Escape - } - str, err = protocol.EncodeJSONValue(value, escaping) - if err != nil { - return "", fmt.Errorf("unable to encode JSONValue, %v", err) - } - default: - err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type()) - return "", err - } - return str, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go deleted file mode 100644 index 4366de2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go +++ /dev/null @@ -1,45 +0,0 @@ -package rest - -import "reflect" - -// PayloadMember returns the payload field member of i if there is one, or nil. -func PayloadMember(i interface{}) interface{} { - if i == nil { - return nil - } - - v := reflect.ValueOf(i).Elem() - if !v.IsValid() { - return nil - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - field, _ := v.Type().FieldByName(payloadName) - if field.Tag.Get("type") != "structure" { - return nil - } - - payload := v.FieldByName(payloadName) - if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) { - return payload.Interface() - } - } - } - return nil -} - -// PayloadType returns the type of a payload field member of i if there is one, or "". -func PayloadType(i interface{}) string { - v := reflect.Indirect(reflect.ValueOf(i)) - if !v.IsValid() { - return "" - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - if member, ok := v.Type().FieldByName(payloadName); ok { - return member.Tag.Get("type") - } - } - } - return "" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go deleted file mode 100644 index 33fd53b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ /dev/null @@ -1,225 +0,0 @@ -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalHandler is a named request handler for unmarshaling rest protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.rest.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling rest protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.rest.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals the REST component of a response in a REST service. -func Unmarshal(r *request.Request) { - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalBody(r, v) - } -} - -// UnmarshalMeta unmarshals the REST metadata of a response in a REST service -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") - if r.RequestID == "" { - // Alternative version of request id in the header - r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id") - } - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalLocationElements(r, v) - } -} - -func unmarshalBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := v.FieldByName(payloadName) - if payload.IsValid() { - switch payload.Interface().(type) { - case []byte: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - } else { - payload.Set(reflect.ValueOf(b)) - } - case *string: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - } else { - str := string(b) - payload.Set(reflect.ValueOf(&str)) - } - default: - switch payload.Type().String() { - case "io.ReadCloser": - payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) - case "io.ReadSeeker": - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", - "failed to read response body", err) - return - } - payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b)))) - default: - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - defer r.HTTPResponse.Body.Close() - r.Error = awserr.New("SerializationError", - "failed to decode REST response", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } - } -} - -func unmarshalLocationElements(r *request.Request, v reflect.Value) { - for i := 0; i < v.NumField(); i++ { - m, field := v.Field(i), v.Type().Field(i) - if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - - switch field.Tag.Get("location") { - case "statusCode": - unmarshalStatusCode(m, r.HTTPResponse.StatusCode) - case "header": - err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name), field.Tag) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - break - } - case "headers": - prefix := field.Tag.Get("locationName") - err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - break - } - } - } - if r.Error != nil { - return - } - } -} - -func unmarshalStatusCode(v reflect.Value, statusCode int) { - if !v.IsValid() { - return - } - - switch v.Interface().(type) { - case *int64: - s := int64(statusCode) - v.Set(reflect.ValueOf(&s)) - } -} - -func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error { - switch r.Interface().(type) { - case map[string]*string: // we only support string map value types - out := map[string]*string{} - for k, v := range headers { - k = http.CanonicalHeaderKey(k) - if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) { - out[k[len(prefix):]] = &v[0] - } - } - r.Set(reflect.ValueOf(out)) - } - return nil -} - -func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { - isJSONValue := tag.Get("type") == "jsonvalue" - if isJSONValue { - if len(header) == 0 { - return nil - } - } else if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { - return nil - } - - switch v.Interface().(type) { - case *string: - v.Set(reflect.ValueOf(&header)) - case []byte: - b, err := base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *bool: - b, err := strconv.ParseBool(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *int64: - i, err := strconv.ParseInt(header, 10, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&i)) - case *float64: - f, err := strconv.ParseFloat(header, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&f)) - case *time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.RFC822TimeFormatName - } - t, err := protocol.ParseTime(format, header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&t)) - case aws.JSONValue: - escaping := protocol.NoEscape - if tag.Get("location") == "header" { - escaping = protocol.Base64Escape - } - m, err := protocol.DecodeJSONValue(header, escaping) - if err != nil { - return err - } - v.Set(reflect.ValueOf(m)) - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return err - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go deleted file mode 100644 index 7bdf4c8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package restxml provides RESTful XML serialization of AWS -// requests and responses. -package restxml - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/rest-xml.json build_test.go -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/rest-xml.json unmarshal_test.go - -import ( - "bytes" - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/rest" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// BuildHandler is a named request handler for building restxml protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.restxml.Build", Fn: Build} - -// UnmarshalHandler is a named request handler for unmarshaling restxml protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.restxml.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling restxml protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.restxml.UnmarshalMeta", Fn: UnmarshalMeta} - -// UnmarshalErrorHandler is a named request handler for unmarshaling restxml protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.restxml.UnmarshalError", Fn: UnmarshalError} - -// Build builds a request payload for the REST XML protocol. -func Build(r *request.Request) { - rest.Build(r) - - if t := rest.PayloadType(r.Params); t == "structure" || t == "" { - var buf bytes.Buffer - err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to encode rest XML request", err) - return - } - r.SetBufferBody(buf.Bytes()) - } -} - -// Unmarshal unmarshals a payload response for the REST XML protocol. -func Unmarshal(r *request.Request) { - if t := rest.PayloadType(r.Data); t == "structure" || t == "" { - defer r.HTTPResponse.Body.Close() - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, "") - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST XML response", err) - return - } - } else { - rest.Unmarshal(r) - } -} - -// UnmarshalMeta unmarshals response headers for the REST XML protocol. -func UnmarshalMeta(r *request.Request) { - rest.UnmarshalMeta(r) -} - -// UnmarshalError unmarshals a response error for the REST XML protocol. -func UnmarshalError(r *request.Request) { - query.UnmarshalError(r) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go deleted file mode 100644 index b7ed6c6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go +++ /dev/null @@ -1,72 +0,0 @@ -package protocol - -import ( - "strconv" - "time" -) - -// Names of time formats supported by the SDK -const ( - RFC822TimeFormatName = "rfc822" - ISO8601TimeFormatName = "iso8601" - UnixTimeFormatName = "unixTimestamp" -) - -// Time formats supported by the SDK -const ( - // RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT - RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT" - - // RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z - ISO8601TimeFormat = "2006-01-02T15:04:05Z" -) - -// IsKnownTimestampFormat returns if the timestamp format name -// is know to the SDK's protocols. -func IsKnownTimestampFormat(name string) bool { - switch name { - case RFC822TimeFormatName: - fallthrough - case ISO8601TimeFormatName: - fallthrough - case UnixTimeFormatName: - return true - default: - return false - } -} - -// FormatTime returns a string value of the time. -func FormatTime(name string, t time.Time) string { - t = t.UTC() - - switch name { - case RFC822TimeFormatName: - return t.Format(RFC822TimeFormat) - case ISO8601TimeFormatName: - return t.Format(ISO8601TimeFormat) - case UnixTimeFormatName: - return strconv.FormatInt(t.Unix(), 10) - default: - panic("unknown timestamp format name, " + name) - } -} - -// ParseTime attempts to parse the time given the format. Returns -// the time if it was able to be parsed, and fails otherwise. -func ParseTime(formatName, value string) (time.Time, error) { - switch formatName { - case RFC822TimeFormatName: - return time.Parse(RFC822TimeFormat, value) - case ISO8601TimeFormatName: - return time.Parse(ISO8601TimeFormat, value) - case UnixTimeFormatName: - v, err := strconv.ParseFloat(value, 64) - if err != nil { - return time.Time{}, err - } - return time.Unix(int64(v), 0), nil - default: - panic("unknown timestamp format name, " + formatName) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go deleted file mode 100644 index da1a681..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go +++ /dev/null @@ -1,21 +0,0 @@ -package protocol - -import ( - "io" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/request" -) - -// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body -var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody} - -// UnmarshalDiscardBody is a request handler to empty a response's body and closing it. -func UnmarshalDiscardBody(r *request.Request) { - if r.HTTPResponse == nil || r.HTTPResponse.Body == nil { - return - } - - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - r.HTTPResponse.Body.Close() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go deleted file mode 100644 index 1bfe45f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go +++ /dev/null @@ -1,306 +0,0 @@ -// Package xmlutil provides XML serialization of AWS requests and responses. -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "reflect" - "sort" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// BuildXML will serialize params into an xml.Encoder. Error will be returned -// if the serialization of any of the params or nested values fails. -func BuildXML(params interface{}, e *xml.Encoder) error { - return buildXML(params, e, false) -} - -func buildXML(params interface{}, e *xml.Encoder, sorted bool) error { - b := xmlBuilder{encoder: e, namespaces: map[string]string{}} - root := NewXMLElement(xml.Name{}) - if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil { - return err - } - for _, c := range root.Children { - for _, v := range c { - return StructToXML(e, v, sorted) - } - } - return nil -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -// A xmlBuilder serializes values from Go code to XML -type xmlBuilder struct { - encoder *xml.Encoder - namespaces map[string]string -} - -// buildValue generic XMLNode builder for any type. Will build value for their specific type -// struct, list, map, scalar. -// -// Also takes a "type" tag value to set what type a value should be converted to XMLNode as. If -// type is not provided reflect will be used to determine the value's type. -func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - value = elemOf(value) - if !value.IsValid() { // no need to handle zero values - return nil - } else if tag.Get("location") != "" { // don't handle non-body location values - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := value.Type().FieldByName("_"); ok { - tag = tag + reflect.StructTag(" ") + field.Tag - } - return b.buildStruct(value, current, tag) - case "list": - return b.buildList(value, current, tag) - case "map": - return b.buildMap(value, current, tag) - default: - return b.buildScalar(value, current, tag) - } -} - -// buildStruct adds a struct and its fields to the current XMLNode. All fields any any nested -// types are converted to XMLNodes also. -func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - child := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - - // there is an xmlNamespace associated with this struct - if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" { - ns := xml.Attr{ - Name: xml.Name{Local: "xmlns"}, - Value: uri, - } - if prefix != "" { - b.namespaces[prefix] = uri // register the namespace - ns.Name.Local = "xmlns:" + prefix - } - - child.Attr = append(child.Attr, ns) - } - - var payloadFields, nonPayloadFields int - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - member := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - mTag := field.Tag - if mTag.Get("location") != "" { // skip non-body members - nonPayloadFields++ - continue - } - payloadFields++ - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(token) - } - - memberName := mTag.Get("locationName") - if memberName == "" { - memberName = field.Name - mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`) - } - if err := b.buildValue(member, child, mTag); err != nil { - return err - } - } - - // Only case where the child shape is not added is if the shape only contains - // non-payload fields, e.g headers/query. - if !(payloadFields == 0 && nonPayloadFields > 0) { - current.AddChild(child) - } - - return nil -} - -// buildList adds the value's list items to the current XMLNode as children nodes. All -// nested values in the list are converted to XMLNodes also. -func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted lists - return nil - } - - // check for unflattened list member - flattened := tag.Get("flattened") != "" - - xname := xml.Name{Local: tag.Get("locationName")} - if flattened { - for i := 0; i < value.Len(); i++ { - child := NewXMLElement(xname) - current.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } else { - list := NewXMLElement(xname) - current.AddChild(list) - - for i := 0; i < value.Len(); i++ { - iname := tag.Get("locationNameList") - if iname == "" { - iname = "member" - } - - child := NewXMLElement(xml.Name{Local: iname}) - list.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } - - return nil -} - -// buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All -// nested values in the map are converted to XMLNodes also. -// -// Error will be returned if it is unable to build the map's values into XMLNodes -func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted maps - return nil - } - - maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - current.AddChild(maproot) - current = maproot - - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - // sorting is not required for compliance, but it makes testing easier - keys := make([]string, value.Len()) - for i, k := range value.MapKeys() { - keys[i] = k.String() - } - sort.Strings(keys) - - for _, k := range keys { - v := value.MapIndex(reflect.ValueOf(k)) - - mapcur := current - if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps - child := NewXMLElement(xml.Name{Local: "entry"}) - mapcur.AddChild(child) - mapcur = child - } - - kchild := NewXMLElement(xml.Name{Local: kname}) - kchild.Text = k - vchild := NewXMLElement(xml.Name{Local: vname}) - mapcur.AddChild(kchild) - mapcur.AddChild(vchild) - - if err := b.buildValue(v, vchild, ""); err != nil { - return err - } - } - - return nil -} - -// buildScalar will convert the value into a string and append it as a attribute or child -// of the current XMLNode. -// -// The value will be added as an attribute if tag contains a "xmlAttribute" attribute value. -// -// Error will be returned if the value type is unsupported. -func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - var str string - switch converted := value.Interface().(type) { - case string: - str = converted - case []byte: - if !value.IsNil() { - str = base64.StdEncoding.EncodeToString(converted) - } - case bool: - str = strconv.FormatBool(converted) - case int64: - str = strconv.FormatInt(converted, 10) - case int: - str = strconv.Itoa(converted) - case float64: - str = strconv.FormatFloat(converted, 'f', -1, 64) - case float32: - str = strconv.FormatFloat(float64(converted), 'f', -1, 32) - case time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - str = protocol.FormatTime(format, converted) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", - tag.Get("locationName"), value.Interface(), value.Type().Name()) - } - - xname := xml.Name{Local: tag.Get("locationName")} - if tag.Get("xmlAttribute") != "" { // put into current node's attribute list - attr := xml.Attr{Name: xname, Value: str} - current.Attr = append(current.Attr, attr) - } else { // regular text node - current.AddChild(&XMLNode{Name: xname, Text: str}) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go deleted file mode 100644 index ff1ef68..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go +++ /dev/null @@ -1,272 +0,0 @@ -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "io" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalXML deserializes an xml.Decoder into the container v. V -// needs to match the shape of the XML expected to be decoded. -// If the shape doesn't match unmarshaling will fail. -func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { - n, err := XMLToStruct(d, nil) - if err != nil { - return err - } - if n.Children != nil { - for _, root := range n.Children { - for _, c := range root { - if wrappedChild, ok := c.Children[wrapper]; ok { - c = wrappedChild[0] // pull out wrapped element - } - - err = parse(reflect.ValueOf(v), c, "") - if err != nil { - if err == io.EOF { - return nil - } - return err - } - } - } - return nil - } - return nil -} - -// parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect -// will be used to determine the type from r. -func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - rtype := r.Type() - if rtype.Kind() == reflect.Ptr { - rtype = rtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch rtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if _, ok := r.Interface().(*time.Time); !ok { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := r.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := rtype.FieldByName("_"); ok { - tag = field.Tag - } - return parseStruct(r, node, tag) - case "list": - return parseList(r, node, tag) - case "map": - return parseMap(r, node, tag) - default: - return parseScalar(r, node, tag) - } -} - -// parseStruct deserializes a structure and its fields from an XMLNode. Any nested -// types in the structure will also be deserialized. -func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - if r.Kind() == reflect.Ptr { - if r.IsNil() { // create the structure if it's nil - s := reflect.New(r.Type().Elem()) - r.Set(s) - r = s - } - - r = r.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return parseStruct(r.FieldByName(payload), node, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if c := field.Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - // try to find the field by name in elements - elems := node.Children[name] - - if elems == nil { // try to find the field in attributes - if val, ok := node.findElem(name); ok { - elems = []*XMLNode{{Text: val}} - } - } - - member := r.FieldByName(field.Name) - for _, elem := range elems { - err := parse(member, elem, field.Tag) - if err != nil { - return err - } - } - } - return nil -} - -// parseList deserializes a list of values from an XML node. Each list entry -// will also be deserialized. -func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - - if tag.Get("flattened") == "" { // look at all item entries - mname := "member" - if name := tag.Get("locationNameList"); name != "" { - mname = name - } - - if Children, ok := node.Children[mname]; ok { - if r.IsNil() { - r.Set(reflect.MakeSlice(t, len(Children), len(Children))) - } - - for i, c := range Children { - err := parse(r.Index(i), c, "") - if err != nil { - return err - } - } - } - } else { // flattened list means this is a single element - if r.IsNil() { - r.Set(reflect.MakeSlice(t, 0, 0)) - } - - childR := reflect.Zero(t.Elem()) - r.Set(reflect.Append(r, childR)) - err := parse(r.Index(r.Len()-1), node, "") - if err != nil { - return err - } - } - - return nil -} - -// parseMap deserializes a map from an XMLNode. The direct children of the XMLNode -// will also be deserialized as map entries. -func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - if r.IsNil() { - r.Set(reflect.MakeMap(r.Type())) - } - - if tag.Get("flattened") == "" { // look at all child entries - for _, entry := range node.Children["entry"] { - parseMapEntry(r, entry, tag) - } - } else { // this element is itself an entry - parseMapEntry(r, node, tag) - } - - return nil -} - -// parseMapEntry deserializes a map entry from a XML node. -func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - keys, ok := node.Children[kname] - values := node.Children[vname] - if ok { - for i, key := range keys { - keyR := reflect.ValueOf(key.Text) - value := values[i] - valueR := reflect.New(r.Type().Elem()).Elem() - - parse(valueR, value, "") - r.SetMapIndex(keyR, valueR) - } - } - return nil -} - -// parseScaller deserializes an XMLNode value into a concrete type based on the -// interface type of r. -// -// Error is returned if the deserialization fails due to invalid type conversion, -// or unsupported interface type. -func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - switch r.Interface().(type) { - case *string: - r.Set(reflect.ValueOf(&node.Text)) - return nil - case []byte: - b, err := base64.StdEncoding.DecodeString(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(b)) - case *bool: - v, err := strconv.ParseBool(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *int64: - v, err := strconv.ParseInt(node.Text, 10, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *float64: - v, err := strconv.ParseFloat(node.Text, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - t, err := protocol.ParseTime(format, node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&t)) - default: - return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type()) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go deleted file mode 100644 index 515ce15..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go +++ /dev/null @@ -1,148 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "fmt" - "io" - "sort" -) - -// A XMLNode contains the values to be encoded or decoded. -type XMLNode struct { - Name xml.Name `json:",omitempty"` - Children map[string][]*XMLNode `json:",omitempty"` - Text string `json:",omitempty"` - Attr []xml.Attr `json:",omitempty"` - - namespaces map[string]string - parent *XMLNode -} - -// NewXMLElement returns a pointer to a new XMLNode initialized to default values. -func NewXMLElement(name xml.Name) *XMLNode { - return &XMLNode{ - Name: name, - Children: map[string][]*XMLNode{}, - Attr: []xml.Attr{}, - } -} - -// AddChild adds child to the XMLNode. -func (n *XMLNode) AddChild(child *XMLNode) { - child.parent = n - if _, ok := n.Children[child.Name.Local]; !ok { - n.Children[child.Name.Local] = []*XMLNode{} - } - n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child) -} - -// XMLToStruct converts a xml.Decoder stream to XMLNode with nested values. -func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) { - out := &XMLNode{} - for { - tok, err := d.Token() - if err != nil { - if err == io.EOF { - break - } else { - return out, err - } - } - - if tok == nil { - break - } - - switch typed := tok.(type) { - case xml.CharData: - out.Text = string(typed.Copy()) - case xml.StartElement: - el := typed.Copy() - out.Attr = el.Attr - if out.Children == nil { - out.Children = map[string][]*XMLNode{} - } - - name := typed.Name.Local - slice := out.Children[name] - if slice == nil { - slice = []*XMLNode{} - } - node, e := XMLToStruct(d, &el) - out.findNamespaces() - if e != nil { - return out, e - } - node.Name = typed.Name - node.findNamespaces() - tempOut := *out - // Save into a temp variable, simply because out gets squashed during - // loop iterations - node.parent = &tempOut - slice = append(slice, node) - out.Children[name] = slice - case xml.EndElement: - if s != nil && s.Name.Local == typed.Name.Local { // matching end token - return out, nil - } - out = &XMLNode{} - } - } - return out, nil -} - -func (n *XMLNode) findNamespaces() { - ns := map[string]string{} - for _, a := range n.Attr { - if a.Name.Space == "xmlns" { - ns[a.Value] = a.Name.Local - } - } - - n.namespaces = ns -} - -func (n *XMLNode) findElem(name string) (string, bool) { - for node := n; node != nil; node = node.parent { - for _, a := range node.Attr { - namespace := a.Name.Space - if v, ok := node.namespaces[namespace]; ok { - namespace = v - } - if name == fmt.Sprintf("%s:%s", namespace, a.Name.Local) { - return a.Value, true - } - } - } - return "", false -} - -// StructToXML writes an XMLNode to a xml.Encoder as tokens. -func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error { - e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr}) - - if node.Text != "" { - e.EncodeToken(xml.CharData([]byte(node.Text))) - } else if sorted { - sortedNames := []string{} - for k := range node.Children { - sortedNames = append(sortedNames, k) - } - sort.Strings(sortedNames) - - for _, k := range sortedNames { - for _, v := range node.Children[k] { - StructToXML(e, v, sorted) - } - } - } else { - for _, c := range node.Children { - for _, v := range c { - StructToXML(e, v, sorted) - } - } - } - - e.EncodeToken(xml.EndElement{Name: node.Name}) - return e.Flush() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go deleted file mode 100644 index 8178113..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go +++ /dev/null @@ -1,16202 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package lightsail - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAllocateStaticIp = "AllocateStaticIp" - -// AllocateStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the AllocateStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AllocateStaticIp for more information on using the AllocateStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AllocateStaticIpRequest method. -// req, resp := client.AllocateStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AllocateStaticIp -func (c *Lightsail) AllocateStaticIpRequest(input *AllocateStaticIpInput) (req *request.Request, output *AllocateStaticIpOutput) { - op := &request.Operation{ - Name: opAllocateStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AllocateStaticIpInput{} - } - - output = &AllocateStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// AllocateStaticIp API operation for Amazon Lightsail. -// -// Allocates a static IP address. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AllocateStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AllocateStaticIp -func (c *Lightsail) AllocateStaticIp(input *AllocateStaticIpInput) (*AllocateStaticIpOutput, error) { - req, out := c.AllocateStaticIpRequest(input) - return out, req.Send() -} - -// AllocateStaticIpWithContext is the same as AllocateStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See AllocateStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AllocateStaticIpWithContext(ctx aws.Context, input *AllocateStaticIpInput, opts ...request.Option) (*AllocateStaticIpOutput, error) { - req, out := c.AllocateStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachDisk = "AttachDisk" - -// AttachDiskRequest generates a "aws/request.Request" representing the -// client's request for the AttachDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachDisk for more information on using the AttachDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachDiskRequest method. -// req, resp := client.AttachDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachDisk -func (c *Lightsail) AttachDiskRequest(input *AttachDiskInput) (req *request.Request, output *AttachDiskOutput) { - op := &request.Operation{ - Name: opAttachDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachDiskInput{} - } - - output = &AttachDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachDisk API operation for Amazon Lightsail. -// -// Attaches a block storage disk to a running or stopped Lightsail instance -// and exposes it to the instance with the specified disk name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachDisk -func (c *Lightsail) AttachDisk(input *AttachDiskInput) (*AttachDiskOutput, error) { - req, out := c.AttachDiskRequest(input) - return out, req.Send() -} - -// AttachDiskWithContext is the same as AttachDisk with the addition of -// the ability to pass a context and additional request options. -// -// See AttachDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachDiskWithContext(ctx aws.Context, input *AttachDiskInput, opts ...request.Option) (*AttachDiskOutput, error) { - req, out := c.AttachDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachInstancesToLoadBalancer = "AttachInstancesToLoadBalancer" - -// AttachInstancesToLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the AttachInstancesToLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachInstancesToLoadBalancer for more information on using the AttachInstancesToLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachInstancesToLoadBalancerRequest method. -// req, resp := client.AttachInstancesToLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachInstancesToLoadBalancer -func (c *Lightsail) AttachInstancesToLoadBalancerRequest(input *AttachInstancesToLoadBalancerInput) (req *request.Request, output *AttachInstancesToLoadBalancerOutput) { - op := &request.Operation{ - Name: opAttachInstancesToLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachInstancesToLoadBalancerInput{} - } - - output = &AttachInstancesToLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachInstancesToLoadBalancer API operation for Amazon Lightsail. -// -// Attaches one or more Lightsail instances to a load balancer. -// -// After some time, the instances are attached to the load balancer and the -// health check status is available. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachInstancesToLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachInstancesToLoadBalancer -func (c *Lightsail) AttachInstancesToLoadBalancer(input *AttachInstancesToLoadBalancerInput) (*AttachInstancesToLoadBalancerOutput, error) { - req, out := c.AttachInstancesToLoadBalancerRequest(input) - return out, req.Send() -} - -// AttachInstancesToLoadBalancerWithContext is the same as AttachInstancesToLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See AttachInstancesToLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachInstancesToLoadBalancerWithContext(ctx aws.Context, input *AttachInstancesToLoadBalancerInput, opts ...request.Option) (*AttachInstancesToLoadBalancerOutput, error) { - req, out := c.AttachInstancesToLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachLoadBalancerTlsCertificate = "AttachLoadBalancerTlsCertificate" - -// AttachLoadBalancerTlsCertificateRequest generates a "aws/request.Request" representing the -// client's request for the AttachLoadBalancerTlsCertificate operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachLoadBalancerTlsCertificate for more information on using the AttachLoadBalancerTlsCertificate -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachLoadBalancerTlsCertificateRequest method. -// req, resp := client.AttachLoadBalancerTlsCertificateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachLoadBalancerTlsCertificate -func (c *Lightsail) AttachLoadBalancerTlsCertificateRequest(input *AttachLoadBalancerTlsCertificateInput) (req *request.Request, output *AttachLoadBalancerTlsCertificateOutput) { - op := &request.Operation{ - Name: opAttachLoadBalancerTlsCertificate, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachLoadBalancerTlsCertificateInput{} - } - - output = &AttachLoadBalancerTlsCertificateOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachLoadBalancerTlsCertificate API operation for Amazon Lightsail. -// -// Attaches a Transport Layer Security (TLS) certificate to your load balancer. -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -// -// Once you create and validate your certificate, you can attach it to your -// load balancer. You can also use this API to rotate the certificates on your -// account. Use the AttachLoadBalancerTlsCertificate operation with the non-attached -// certificate, and it will replace the existing one and become the attached -// certificate. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachLoadBalancerTlsCertificate for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachLoadBalancerTlsCertificate -func (c *Lightsail) AttachLoadBalancerTlsCertificate(input *AttachLoadBalancerTlsCertificateInput) (*AttachLoadBalancerTlsCertificateOutput, error) { - req, out := c.AttachLoadBalancerTlsCertificateRequest(input) - return out, req.Send() -} - -// AttachLoadBalancerTlsCertificateWithContext is the same as AttachLoadBalancerTlsCertificate with the addition of -// the ability to pass a context and additional request options. -// -// See AttachLoadBalancerTlsCertificate for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachLoadBalancerTlsCertificateWithContext(ctx aws.Context, input *AttachLoadBalancerTlsCertificateInput, opts ...request.Option) (*AttachLoadBalancerTlsCertificateOutput, error) { - req, out := c.AttachLoadBalancerTlsCertificateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachStaticIp = "AttachStaticIp" - -// AttachStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the AttachStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachStaticIp for more information on using the AttachStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachStaticIpRequest method. -// req, resp := client.AttachStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachStaticIp -func (c *Lightsail) AttachStaticIpRequest(input *AttachStaticIpInput) (req *request.Request, output *AttachStaticIpOutput) { - op := &request.Operation{ - Name: opAttachStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachStaticIpInput{} - } - - output = &AttachStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachStaticIp API operation for Amazon Lightsail. -// -// Attaches a static IP address to a specific Amazon Lightsail instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachStaticIp -func (c *Lightsail) AttachStaticIp(input *AttachStaticIpInput) (*AttachStaticIpOutput, error) { - req, out := c.AttachStaticIpRequest(input) - return out, req.Send() -} - -// AttachStaticIpWithContext is the same as AttachStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See AttachStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachStaticIpWithContext(ctx aws.Context, input *AttachStaticIpInput, opts ...request.Option) (*AttachStaticIpOutput, error) { - req, out := c.AttachStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCloseInstancePublicPorts = "CloseInstancePublicPorts" - -// CloseInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the CloseInstancePublicPorts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CloseInstancePublicPorts for more information on using the CloseInstancePublicPorts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CloseInstancePublicPortsRequest method. -// req, resp := client.CloseInstancePublicPortsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloseInstancePublicPorts -func (c *Lightsail) CloseInstancePublicPortsRequest(input *CloseInstancePublicPortsInput) (req *request.Request, output *CloseInstancePublicPortsOutput) { - op := &request.Operation{ - Name: opCloseInstancePublicPorts, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CloseInstancePublicPortsInput{} - } - - output = &CloseInstancePublicPortsOutput{} - req = c.newRequest(op, input, output) - return -} - -// CloseInstancePublicPorts API operation for Amazon Lightsail. -// -// Closes the public ports on a specific Amazon Lightsail instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CloseInstancePublicPorts for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloseInstancePublicPorts -func (c *Lightsail) CloseInstancePublicPorts(input *CloseInstancePublicPortsInput) (*CloseInstancePublicPortsOutput, error) { - req, out := c.CloseInstancePublicPortsRequest(input) - return out, req.Send() -} - -// CloseInstancePublicPortsWithContext is the same as CloseInstancePublicPorts with the addition of -// the ability to pass a context and additional request options. -// -// See CloseInstancePublicPorts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CloseInstancePublicPortsWithContext(ctx aws.Context, input *CloseInstancePublicPortsInput, opts ...request.Option) (*CloseInstancePublicPortsOutput, error) { - req, out := c.CloseInstancePublicPortsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDisk = "CreateDisk" - -// CreateDiskRequest generates a "aws/request.Request" representing the -// client's request for the CreateDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDisk for more information on using the CreateDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDiskRequest method. -// req, resp := client.CreateDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDisk -func (c *Lightsail) CreateDiskRequest(input *CreateDiskInput) (req *request.Request, output *CreateDiskOutput) { - op := &request.Operation{ - Name: opCreateDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDiskInput{} - } - - output = &CreateDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDisk API operation for Amazon Lightsail. -// -// Creates a block storage disk that can be attached to a Lightsail instance -// in the same Availability Zone (e.g., us-east-2a). The disk is created in -// the regional endpoint that you send the HTTP request to. For more information, -// see Regions and Availability Zones in Lightsail (https://lightsail.aws.amazon.com/ls/docs/overview/article/understanding-regions-and-availability-zones-in-amazon-lightsail). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDisk -func (c *Lightsail) CreateDisk(input *CreateDiskInput) (*CreateDiskOutput, error) { - req, out := c.CreateDiskRequest(input) - return out, req.Send() -} - -// CreateDiskWithContext is the same as CreateDisk with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDiskWithContext(ctx aws.Context, input *CreateDiskInput, opts ...request.Option) (*CreateDiskOutput, error) { - req, out := c.CreateDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDiskFromSnapshot = "CreateDiskFromSnapshot" - -// CreateDiskFromSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateDiskFromSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDiskFromSnapshot for more information on using the CreateDiskFromSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDiskFromSnapshotRequest method. -// req, resp := client.CreateDiskFromSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskFromSnapshot -func (c *Lightsail) CreateDiskFromSnapshotRequest(input *CreateDiskFromSnapshotInput) (req *request.Request, output *CreateDiskFromSnapshotOutput) { - op := &request.Operation{ - Name: opCreateDiskFromSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDiskFromSnapshotInput{} - } - - output = &CreateDiskFromSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDiskFromSnapshot API operation for Amazon Lightsail. -// -// Creates a block storage disk from a disk snapshot that can be attached to -// a Lightsail instance in the same Availability Zone (e.g., us-east-2a). The -// disk is created in the regional endpoint that you send the HTTP request to. -// For more information, see Regions and Availability Zones in Lightsail (https://lightsail.aws.amazon.com/ls/docs/overview/article/understanding-regions-and-availability-zones-in-amazon-lightsail). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDiskFromSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskFromSnapshot -func (c *Lightsail) CreateDiskFromSnapshot(input *CreateDiskFromSnapshotInput) (*CreateDiskFromSnapshotOutput, error) { - req, out := c.CreateDiskFromSnapshotRequest(input) - return out, req.Send() -} - -// CreateDiskFromSnapshotWithContext is the same as CreateDiskFromSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDiskFromSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDiskFromSnapshotWithContext(ctx aws.Context, input *CreateDiskFromSnapshotInput, opts ...request.Option) (*CreateDiskFromSnapshotOutput, error) { - req, out := c.CreateDiskFromSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDiskSnapshot = "CreateDiskSnapshot" - -// CreateDiskSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateDiskSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDiskSnapshot for more information on using the CreateDiskSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDiskSnapshotRequest method. -// req, resp := client.CreateDiskSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskSnapshot -func (c *Lightsail) CreateDiskSnapshotRequest(input *CreateDiskSnapshotInput) (req *request.Request, output *CreateDiskSnapshotOutput) { - op := &request.Operation{ - Name: opCreateDiskSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDiskSnapshotInput{} - } - - output = &CreateDiskSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDiskSnapshot API operation for Amazon Lightsail. -// -// Creates a snapshot of a block storage disk. You can use snapshots for backups, -// to make copies of disks, and to save data before shutting down a Lightsail -// instance. -// -// You can take a snapshot of an attached disk that is in use; however, snapshots -// only capture data that has been written to your disk at the time the snapshot -// command is issued. This may exclude any data that has been cached by any -// applications or the operating system. If you can pause any file systems on -// the disk long enough to take a snapshot, your snapshot should be complete. -// Nevertheless, if you cannot pause all file writes to the disk, you should -// unmount the disk from within the Lightsail instance, issue the create disk -// snapshot command, and then remount the disk to ensure a consistent and complete -// snapshot. You may remount and use your disk while the snapshot status is -// pending. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDiskSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskSnapshot -func (c *Lightsail) CreateDiskSnapshot(input *CreateDiskSnapshotInput) (*CreateDiskSnapshotOutput, error) { - req, out := c.CreateDiskSnapshotRequest(input) - return out, req.Send() -} - -// CreateDiskSnapshotWithContext is the same as CreateDiskSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDiskSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDiskSnapshotWithContext(ctx aws.Context, input *CreateDiskSnapshotInput, opts ...request.Option) (*CreateDiskSnapshotOutput, error) { - req, out := c.CreateDiskSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDomain = "CreateDomain" - -// CreateDomainRequest generates a "aws/request.Request" representing the -// client's request for the CreateDomain operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDomain for more information on using the CreateDomain -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDomainRequest method. -// req, resp := client.CreateDomainRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomain -func (c *Lightsail) CreateDomainRequest(input *CreateDomainInput) (req *request.Request, output *CreateDomainOutput) { - op := &request.Operation{ - Name: opCreateDomain, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDomainInput{} - } - - output = &CreateDomainOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDomain API operation for Amazon Lightsail. -// -// Creates a domain resource for the specified domain (e.g., example.com). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDomain for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomain -func (c *Lightsail) CreateDomain(input *CreateDomainInput) (*CreateDomainOutput, error) { - req, out := c.CreateDomainRequest(input) - return out, req.Send() -} - -// CreateDomainWithContext is the same as CreateDomain with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDomain for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDomainWithContext(ctx aws.Context, input *CreateDomainInput, opts ...request.Option) (*CreateDomainOutput, error) { - req, out := c.CreateDomainRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDomainEntry = "CreateDomainEntry" - -// CreateDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the CreateDomainEntry operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDomainEntry for more information on using the CreateDomainEntry -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDomainEntryRequest method. -// req, resp := client.CreateDomainEntryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomainEntry -func (c *Lightsail) CreateDomainEntryRequest(input *CreateDomainEntryInput) (req *request.Request, output *CreateDomainEntryOutput) { - op := &request.Operation{ - Name: opCreateDomainEntry, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDomainEntryInput{} - } - - output = &CreateDomainEntryOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDomainEntry API operation for Amazon Lightsail. -// -// Creates one of the following entry records associated with the domain: A -// record, CNAME record, TXT record, or MX record. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDomainEntry for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomainEntry -func (c *Lightsail) CreateDomainEntry(input *CreateDomainEntryInput) (*CreateDomainEntryOutput, error) { - req, out := c.CreateDomainEntryRequest(input) - return out, req.Send() -} - -// CreateDomainEntryWithContext is the same as CreateDomainEntry with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDomainEntry for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDomainEntryWithContext(ctx aws.Context, input *CreateDomainEntryInput, opts ...request.Option) (*CreateDomainEntryOutput, error) { - req, out := c.CreateDomainEntryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateInstanceSnapshot = "CreateInstanceSnapshot" - -// CreateInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateInstanceSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateInstanceSnapshot for more information on using the CreateInstanceSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateInstanceSnapshotRequest method. -// req, resp := client.CreateInstanceSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstanceSnapshot -func (c *Lightsail) CreateInstanceSnapshotRequest(input *CreateInstanceSnapshotInput) (req *request.Request, output *CreateInstanceSnapshotOutput) { - op := &request.Operation{ - Name: opCreateInstanceSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateInstanceSnapshotInput{} - } - - output = &CreateInstanceSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateInstanceSnapshot API operation for Amazon Lightsail. -// -// Creates a snapshot of a specific virtual private server, or instance. You -// can use a snapshot to create a new instance that is based on that snapshot. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateInstanceSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstanceSnapshot -func (c *Lightsail) CreateInstanceSnapshot(input *CreateInstanceSnapshotInput) (*CreateInstanceSnapshotOutput, error) { - req, out := c.CreateInstanceSnapshotRequest(input) - return out, req.Send() -} - -// CreateInstanceSnapshotWithContext is the same as CreateInstanceSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateInstanceSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateInstanceSnapshotWithContext(ctx aws.Context, input *CreateInstanceSnapshotInput, opts ...request.Option) (*CreateInstanceSnapshotOutput, error) { - req, out := c.CreateInstanceSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateInstances = "CreateInstances" - -// CreateInstancesRequest generates a "aws/request.Request" representing the -// client's request for the CreateInstances operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateInstances for more information on using the CreateInstances -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateInstancesRequest method. -// req, resp := client.CreateInstancesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstances -func (c *Lightsail) CreateInstancesRequest(input *CreateInstancesInput) (req *request.Request, output *CreateInstancesOutput) { - op := &request.Operation{ - Name: opCreateInstances, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateInstancesInput{} - } - - output = &CreateInstancesOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateInstances API operation for Amazon Lightsail. -// -// Creates one or more Amazon Lightsail virtual private servers, or instances. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateInstances for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstances -func (c *Lightsail) CreateInstances(input *CreateInstancesInput) (*CreateInstancesOutput, error) { - req, out := c.CreateInstancesRequest(input) - return out, req.Send() -} - -// CreateInstancesWithContext is the same as CreateInstances with the addition of -// the ability to pass a context and additional request options. -// -// See CreateInstances for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateInstancesWithContext(ctx aws.Context, input *CreateInstancesInput, opts ...request.Option) (*CreateInstancesOutput, error) { - req, out := c.CreateInstancesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateInstancesFromSnapshot = "CreateInstancesFromSnapshot" - -// CreateInstancesFromSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateInstancesFromSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateInstancesFromSnapshot for more information on using the CreateInstancesFromSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateInstancesFromSnapshotRequest method. -// req, resp := client.CreateInstancesFromSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstancesFromSnapshot -func (c *Lightsail) CreateInstancesFromSnapshotRequest(input *CreateInstancesFromSnapshotInput) (req *request.Request, output *CreateInstancesFromSnapshotOutput) { - op := &request.Operation{ - Name: opCreateInstancesFromSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateInstancesFromSnapshotInput{} - } - - output = &CreateInstancesFromSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateInstancesFromSnapshot API operation for Amazon Lightsail. -// -// Uses a specific snapshot as a blueprint for creating one or more new instances -// that are based on that identical configuration. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateInstancesFromSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstancesFromSnapshot -func (c *Lightsail) CreateInstancesFromSnapshot(input *CreateInstancesFromSnapshotInput) (*CreateInstancesFromSnapshotOutput, error) { - req, out := c.CreateInstancesFromSnapshotRequest(input) - return out, req.Send() -} - -// CreateInstancesFromSnapshotWithContext is the same as CreateInstancesFromSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateInstancesFromSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateInstancesFromSnapshotWithContext(ctx aws.Context, input *CreateInstancesFromSnapshotInput, opts ...request.Option) (*CreateInstancesFromSnapshotOutput, error) { - req, out := c.CreateInstancesFromSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateKeyPair = "CreateKeyPair" - -// CreateKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the CreateKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateKeyPair for more information on using the CreateKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateKeyPairRequest method. -// req, resp := client.CreateKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateKeyPair -func (c *Lightsail) CreateKeyPairRequest(input *CreateKeyPairInput) (req *request.Request, output *CreateKeyPairOutput) { - op := &request.Operation{ - Name: opCreateKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateKeyPairInput{} - } - - output = &CreateKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateKeyPair API operation for Amazon Lightsail. -// -// Creates sn SSH key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateKeyPair -func (c *Lightsail) CreateKeyPair(input *CreateKeyPairInput) (*CreateKeyPairOutput, error) { - req, out := c.CreateKeyPairRequest(input) - return out, req.Send() -} - -// CreateKeyPairWithContext is the same as CreateKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See CreateKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateKeyPairWithContext(ctx aws.Context, input *CreateKeyPairInput, opts ...request.Option) (*CreateKeyPairOutput, error) { - req, out := c.CreateKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLoadBalancer = "CreateLoadBalancer" - -// CreateLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the CreateLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLoadBalancer for more information on using the CreateLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateLoadBalancerRequest method. -// req, resp := client.CreateLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancer -func (c *Lightsail) CreateLoadBalancerRequest(input *CreateLoadBalancerInput) (req *request.Request, output *CreateLoadBalancerOutput) { - op := &request.Operation{ - Name: opCreateLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLoadBalancerInput{} - } - - output = &CreateLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateLoadBalancer API operation for Amazon Lightsail. -// -// Creates a Lightsail load balancer. To learn more about deciding whether to -// load balance your application, see Configure your Lightsail instances for -// load balancing (https://lightsail.aws.amazon.com/ls/docs/how-to/article/configure-lightsail-instances-for-load-balancing). -// You can create up to 5 load balancers per AWS Region in your account. -// -// When you create a load balancer, you can specify a unique name and port settings. -// To change additional load balancer settings, use the UpdateLoadBalancerAttribute -// operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancer -func (c *Lightsail) CreateLoadBalancer(input *CreateLoadBalancerInput) (*CreateLoadBalancerOutput, error) { - req, out := c.CreateLoadBalancerRequest(input) - return out, req.Send() -} - -// CreateLoadBalancerWithContext is the same as CreateLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateLoadBalancerWithContext(ctx aws.Context, input *CreateLoadBalancerInput, opts ...request.Option) (*CreateLoadBalancerOutput, error) { - req, out := c.CreateLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLoadBalancerTlsCertificate = "CreateLoadBalancerTlsCertificate" - -// CreateLoadBalancerTlsCertificateRequest generates a "aws/request.Request" representing the -// client's request for the CreateLoadBalancerTlsCertificate operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLoadBalancerTlsCertificate for more information on using the CreateLoadBalancerTlsCertificate -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateLoadBalancerTlsCertificateRequest method. -// req, resp := client.CreateLoadBalancerTlsCertificateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancerTlsCertificate -func (c *Lightsail) CreateLoadBalancerTlsCertificateRequest(input *CreateLoadBalancerTlsCertificateInput) (req *request.Request, output *CreateLoadBalancerTlsCertificateOutput) { - op := &request.Operation{ - Name: opCreateLoadBalancerTlsCertificate, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLoadBalancerTlsCertificateInput{} - } - - output = &CreateLoadBalancerTlsCertificateOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateLoadBalancerTlsCertificate API operation for Amazon Lightsail. -// -// Creates a Lightsail load balancer TLS certificate. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateLoadBalancerTlsCertificate for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancerTlsCertificate -func (c *Lightsail) CreateLoadBalancerTlsCertificate(input *CreateLoadBalancerTlsCertificateInput) (*CreateLoadBalancerTlsCertificateOutput, error) { - req, out := c.CreateLoadBalancerTlsCertificateRequest(input) - return out, req.Send() -} - -// CreateLoadBalancerTlsCertificateWithContext is the same as CreateLoadBalancerTlsCertificate with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLoadBalancerTlsCertificate for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateLoadBalancerTlsCertificateWithContext(ctx aws.Context, input *CreateLoadBalancerTlsCertificateInput, opts ...request.Option) (*CreateLoadBalancerTlsCertificateOutput, error) { - req, out := c.CreateLoadBalancerTlsCertificateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDisk = "DeleteDisk" - -// DeleteDiskRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDisk for more information on using the DeleteDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDiskRequest method. -// req, resp := client.DeleteDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDisk -func (c *Lightsail) DeleteDiskRequest(input *DeleteDiskInput) (req *request.Request, output *DeleteDiskOutput) { - op := &request.Operation{ - Name: opDeleteDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDiskInput{} - } - - output = &DeleteDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDisk API operation for Amazon Lightsail. -// -// Deletes the specified block storage disk. The disk must be in the available -// state (not attached to a Lightsail instance). -// -// The disk may remain in the deleting state for several minutes. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDisk -func (c *Lightsail) DeleteDisk(input *DeleteDiskInput) (*DeleteDiskOutput, error) { - req, out := c.DeleteDiskRequest(input) - return out, req.Send() -} - -// DeleteDiskWithContext is the same as DeleteDisk with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDiskWithContext(ctx aws.Context, input *DeleteDiskInput, opts ...request.Option) (*DeleteDiskOutput, error) { - req, out := c.DeleteDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDiskSnapshot = "DeleteDiskSnapshot" - -// DeleteDiskSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDiskSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDiskSnapshot for more information on using the DeleteDiskSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDiskSnapshotRequest method. -// req, resp := client.DeleteDiskSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDiskSnapshot -func (c *Lightsail) DeleteDiskSnapshotRequest(input *DeleteDiskSnapshotInput) (req *request.Request, output *DeleteDiskSnapshotOutput) { - op := &request.Operation{ - Name: opDeleteDiskSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDiskSnapshotInput{} - } - - output = &DeleteDiskSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDiskSnapshot API operation for Amazon Lightsail. -// -// Deletes the specified disk snapshot. -// -// When you make periodic snapshots of a disk, the snapshots are incremental, -// and only the blocks on the device that have changed since your last snapshot -// are saved in the new snapshot. When you delete a snapshot, only the data -// not needed for any other snapshot is removed. So regardless of which prior -// snapshots have been deleted, all active snapshots will have access to all -// the information needed to restore the disk. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDiskSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDiskSnapshot -func (c *Lightsail) DeleteDiskSnapshot(input *DeleteDiskSnapshotInput) (*DeleteDiskSnapshotOutput, error) { - req, out := c.DeleteDiskSnapshotRequest(input) - return out, req.Send() -} - -// DeleteDiskSnapshotWithContext is the same as DeleteDiskSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDiskSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDiskSnapshotWithContext(ctx aws.Context, input *DeleteDiskSnapshotInput, opts ...request.Option) (*DeleteDiskSnapshotOutput, error) { - req, out := c.DeleteDiskSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDomain = "DeleteDomain" - -// DeleteDomainRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDomain operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDomain for more information on using the DeleteDomain -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDomainRequest method. -// req, resp := client.DeleteDomainRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomain -func (c *Lightsail) DeleteDomainRequest(input *DeleteDomainInput) (req *request.Request, output *DeleteDomainOutput) { - op := &request.Operation{ - Name: opDeleteDomain, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDomainInput{} - } - - output = &DeleteDomainOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDomain API operation for Amazon Lightsail. -// -// Deletes the specified domain recordset and all of its domain records. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDomain for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomain -func (c *Lightsail) DeleteDomain(input *DeleteDomainInput) (*DeleteDomainOutput, error) { - req, out := c.DeleteDomainRequest(input) - return out, req.Send() -} - -// DeleteDomainWithContext is the same as DeleteDomain with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDomain for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDomainWithContext(ctx aws.Context, input *DeleteDomainInput, opts ...request.Option) (*DeleteDomainOutput, error) { - req, out := c.DeleteDomainRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDomainEntry = "DeleteDomainEntry" - -// DeleteDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDomainEntry operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDomainEntry for more information on using the DeleteDomainEntry -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDomainEntryRequest method. -// req, resp := client.DeleteDomainEntryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomainEntry -func (c *Lightsail) DeleteDomainEntryRequest(input *DeleteDomainEntryInput) (req *request.Request, output *DeleteDomainEntryOutput) { - op := &request.Operation{ - Name: opDeleteDomainEntry, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDomainEntryInput{} - } - - output = &DeleteDomainEntryOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDomainEntry API operation for Amazon Lightsail. -// -// Deletes a specific domain entry. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDomainEntry for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomainEntry -func (c *Lightsail) DeleteDomainEntry(input *DeleteDomainEntryInput) (*DeleteDomainEntryOutput, error) { - req, out := c.DeleteDomainEntryRequest(input) - return out, req.Send() -} - -// DeleteDomainEntryWithContext is the same as DeleteDomainEntry with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDomainEntry for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDomainEntryWithContext(ctx aws.Context, input *DeleteDomainEntryInput, opts ...request.Option) (*DeleteDomainEntryOutput, error) { - req, out := c.DeleteDomainEntryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteInstance = "DeleteInstance" - -// DeleteInstanceRequest generates a "aws/request.Request" representing the -// client's request for the DeleteInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteInstance for more information on using the DeleteInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteInstanceRequest method. -// req, resp := client.DeleteInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstance -func (c *Lightsail) DeleteInstanceRequest(input *DeleteInstanceInput) (req *request.Request, output *DeleteInstanceOutput) { - op := &request.Operation{ - Name: opDeleteInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteInstanceInput{} - } - - output = &DeleteInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteInstance API operation for Amazon Lightsail. -// -// Deletes a specific Amazon Lightsail virtual private server, or instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstance -func (c *Lightsail) DeleteInstance(input *DeleteInstanceInput) (*DeleteInstanceOutput, error) { - req, out := c.DeleteInstanceRequest(input) - return out, req.Send() -} - -// DeleteInstanceWithContext is the same as DeleteInstance with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteInstanceWithContext(ctx aws.Context, input *DeleteInstanceInput, opts ...request.Option) (*DeleteInstanceOutput, error) { - req, out := c.DeleteInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteInstanceSnapshot = "DeleteInstanceSnapshot" - -// DeleteInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the DeleteInstanceSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteInstanceSnapshot for more information on using the DeleteInstanceSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteInstanceSnapshotRequest method. -// req, resp := client.DeleteInstanceSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstanceSnapshot -func (c *Lightsail) DeleteInstanceSnapshotRequest(input *DeleteInstanceSnapshotInput) (req *request.Request, output *DeleteInstanceSnapshotOutput) { - op := &request.Operation{ - Name: opDeleteInstanceSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteInstanceSnapshotInput{} - } - - output = &DeleteInstanceSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteInstanceSnapshot API operation for Amazon Lightsail. -// -// Deletes a specific snapshot of a virtual private server (or instance). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteInstanceSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstanceSnapshot -func (c *Lightsail) DeleteInstanceSnapshot(input *DeleteInstanceSnapshotInput) (*DeleteInstanceSnapshotOutput, error) { - req, out := c.DeleteInstanceSnapshotRequest(input) - return out, req.Send() -} - -// DeleteInstanceSnapshotWithContext is the same as DeleteInstanceSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteInstanceSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteInstanceSnapshotWithContext(ctx aws.Context, input *DeleteInstanceSnapshotInput, opts ...request.Option) (*DeleteInstanceSnapshotOutput, error) { - req, out := c.DeleteInstanceSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteKeyPair = "DeleteKeyPair" - -// DeleteKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the DeleteKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteKeyPair for more information on using the DeleteKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteKeyPairRequest method. -// req, resp := client.DeleteKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteKeyPair -func (c *Lightsail) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *request.Request, output *DeleteKeyPairOutput) { - op := &request.Operation{ - Name: opDeleteKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteKeyPairInput{} - } - - output = &DeleteKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteKeyPair API operation for Amazon Lightsail. -// -// Deletes a specific SSH key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteKeyPair -func (c *Lightsail) DeleteKeyPair(input *DeleteKeyPairInput) (*DeleteKeyPairOutput, error) { - req, out := c.DeleteKeyPairRequest(input) - return out, req.Send() -} - -// DeleteKeyPairWithContext is the same as DeleteKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteKeyPairWithContext(ctx aws.Context, input *DeleteKeyPairInput, opts ...request.Option) (*DeleteKeyPairOutput, error) { - req, out := c.DeleteKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLoadBalancer = "DeleteLoadBalancer" - -// DeleteLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLoadBalancer for more information on using the DeleteLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteLoadBalancerRequest method. -// req, resp := client.DeleteLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancer -func (c *Lightsail) DeleteLoadBalancerRequest(input *DeleteLoadBalancerInput) (req *request.Request, output *DeleteLoadBalancerOutput) { - op := &request.Operation{ - Name: opDeleteLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLoadBalancerInput{} - } - - output = &DeleteLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteLoadBalancer API operation for Amazon Lightsail. -// -// Deletes a Lightsail load balancer and all its associated SSL/TLS certificates. -// Once the load balancer is deleted, you will need to create a new load balancer, -// create a new certificate, and verify domain ownership again. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancer -func (c *Lightsail) DeleteLoadBalancer(input *DeleteLoadBalancerInput) (*DeleteLoadBalancerOutput, error) { - req, out := c.DeleteLoadBalancerRequest(input) - return out, req.Send() -} - -// DeleteLoadBalancerWithContext is the same as DeleteLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteLoadBalancerWithContext(ctx aws.Context, input *DeleteLoadBalancerInput, opts ...request.Option) (*DeleteLoadBalancerOutput, error) { - req, out := c.DeleteLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLoadBalancerTlsCertificate = "DeleteLoadBalancerTlsCertificate" - -// DeleteLoadBalancerTlsCertificateRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLoadBalancerTlsCertificate operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLoadBalancerTlsCertificate for more information on using the DeleteLoadBalancerTlsCertificate -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteLoadBalancerTlsCertificateRequest method. -// req, resp := client.DeleteLoadBalancerTlsCertificateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancerTlsCertificate -func (c *Lightsail) DeleteLoadBalancerTlsCertificateRequest(input *DeleteLoadBalancerTlsCertificateInput) (req *request.Request, output *DeleteLoadBalancerTlsCertificateOutput) { - op := &request.Operation{ - Name: opDeleteLoadBalancerTlsCertificate, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLoadBalancerTlsCertificateInput{} - } - - output = &DeleteLoadBalancerTlsCertificateOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteLoadBalancerTlsCertificate API operation for Amazon Lightsail. -// -// Deletes an SSL/TLS certificate associated with a Lightsail load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteLoadBalancerTlsCertificate for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancerTlsCertificate -func (c *Lightsail) DeleteLoadBalancerTlsCertificate(input *DeleteLoadBalancerTlsCertificateInput) (*DeleteLoadBalancerTlsCertificateOutput, error) { - req, out := c.DeleteLoadBalancerTlsCertificateRequest(input) - return out, req.Send() -} - -// DeleteLoadBalancerTlsCertificateWithContext is the same as DeleteLoadBalancerTlsCertificate with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLoadBalancerTlsCertificate for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteLoadBalancerTlsCertificateWithContext(ctx aws.Context, input *DeleteLoadBalancerTlsCertificateInput, opts ...request.Option) (*DeleteLoadBalancerTlsCertificateOutput, error) { - req, out := c.DeleteLoadBalancerTlsCertificateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDetachDisk = "DetachDisk" - -// DetachDiskRequest generates a "aws/request.Request" representing the -// client's request for the DetachDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DetachDisk for more information on using the DetachDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DetachDiskRequest method. -// req, resp := client.DetachDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachDisk -func (c *Lightsail) DetachDiskRequest(input *DetachDiskInput) (req *request.Request, output *DetachDiskOutput) { - op := &request.Operation{ - Name: opDetachDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DetachDiskInput{} - } - - output = &DetachDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// DetachDisk API operation for Amazon Lightsail. -// -// Detaches a stopped block storage disk from a Lightsail instance. Make sure -// to unmount any file systems on the device within your operating system before -// stopping the instance and detaching the disk. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DetachDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachDisk -func (c *Lightsail) DetachDisk(input *DetachDiskInput) (*DetachDiskOutput, error) { - req, out := c.DetachDiskRequest(input) - return out, req.Send() -} - -// DetachDiskWithContext is the same as DetachDisk with the addition of -// the ability to pass a context and additional request options. -// -// See DetachDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DetachDiskWithContext(ctx aws.Context, input *DetachDiskInput, opts ...request.Option) (*DetachDiskOutput, error) { - req, out := c.DetachDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDetachInstancesFromLoadBalancer = "DetachInstancesFromLoadBalancer" - -// DetachInstancesFromLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the DetachInstancesFromLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DetachInstancesFromLoadBalancer for more information on using the DetachInstancesFromLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DetachInstancesFromLoadBalancerRequest method. -// req, resp := client.DetachInstancesFromLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachInstancesFromLoadBalancer -func (c *Lightsail) DetachInstancesFromLoadBalancerRequest(input *DetachInstancesFromLoadBalancerInput) (req *request.Request, output *DetachInstancesFromLoadBalancerOutput) { - op := &request.Operation{ - Name: opDetachInstancesFromLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DetachInstancesFromLoadBalancerInput{} - } - - output = &DetachInstancesFromLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// DetachInstancesFromLoadBalancer API operation for Amazon Lightsail. -// -// Detaches the specified instances from a Lightsail load balancer. -// -// This operation waits until the instances are no longer needed before they -// are detached from the load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DetachInstancesFromLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachInstancesFromLoadBalancer -func (c *Lightsail) DetachInstancesFromLoadBalancer(input *DetachInstancesFromLoadBalancerInput) (*DetachInstancesFromLoadBalancerOutput, error) { - req, out := c.DetachInstancesFromLoadBalancerRequest(input) - return out, req.Send() -} - -// DetachInstancesFromLoadBalancerWithContext is the same as DetachInstancesFromLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See DetachInstancesFromLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DetachInstancesFromLoadBalancerWithContext(ctx aws.Context, input *DetachInstancesFromLoadBalancerInput, opts ...request.Option) (*DetachInstancesFromLoadBalancerOutput, error) { - req, out := c.DetachInstancesFromLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDetachStaticIp = "DetachStaticIp" - -// DetachStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the DetachStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DetachStaticIp for more information on using the DetachStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DetachStaticIpRequest method. -// req, resp := client.DetachStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachStaticIp -func (c *Lightsail) DetachStaticIpRequest(input *DetachStaticIpInput) (req *request.Request, output *DetachStaticIpOutput) { - op := &request.Operation{ - Name: opDetachStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DetachStaticIpInput{} - } - - output = &DetachStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// DetachStaticIp API operation for Amazon Lightsail. -// -// Detaches a static IP from the Amazon Lightsail instance to which it is attached. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DetachStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachStaticIp -func (c *Lightsail) DetachStaticIp(input *DetachStaticIpInput) (*DetachStaticIpOutput, error) { - req, out := c.DetachStaticIpRequest(input) - return out, req.Send() -} - -// DetachStaticIpWithContext is the same as DetachStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See DetachStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DetachStaticIpWithContext(ctx aws.Context, input *DetachStaticIpInput, opts ...request.Option) (*DetachStaticIpOutput, error) { - req, out := c.DetachStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDownloadDefaultKeyPair = "DownloadDefaultKeyPair" - -// DownloadDefaultKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the DownloadDefaultKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DownloadDefaultKeyPair for more information on using the DownloadDefaultKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DownloadDefaultKeyPairRequest method. -// req, resp := client.DownloadDefaultKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DownloadDefaultKeyPair -func (c *Lightsail) DownloadDefaultKeyPairRequest(input *DownloadDefaultKeyPairInput) (req *request.Request, output *DownloadDefaultKeyPairOutput) { - op := &request.Operation{ - Name: opDownloadDefaultKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DownloadDefaultKeyPairInput{} - } - - output = &DownloadDefaultKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// DownloadDefaultKeyPair API operation for Amazon Lightsail. -// -// Downloads the default SSH key pair from the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DownloadDefaultKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DownloadDefaultKeyPair -func (c *Lightsail) DownloadDefaultKeyPair(input *DownloadDefaultKeyPairInput) (*DownloadDefaultKeyPairOutput, error) { - req, out := c.DownloadDefaultKeyPairRequest(input) - return out, req.Send() -} - -// DownloadDefaultKeyPairWithContext is the same as DownloadDefaultKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See DownloadDefaultKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DownloadDefaultKeyPairWithContext(ctx aws.Context, input *DownloadDefaultKeyPairInput, opts ...request.Option) (*DownloadDefaultKeyPairOutput, error) { - req, out := c.DownloadDefaultKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetActiveNames = "GetActiveNames" - -// GetActiveNamesRequest generates a "aws/request.Request" representing the -// client's request for the GetActiveNames operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetActiveNames for more information on using the GetActiveNames -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetActiveNamesRequest method. -// req, resp := client.GetActiveNamesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetActiveNames -func (c *Lightsail) GetActiveNamesRequest(input *GetActiveNamesInput) (req *request.Request, output *GetActiveNamesOutput) { - op := &request.Operation{ - Name: opGetActiveNames, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetActiveNamesInput{} - } - - output = &GetActiveNamesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetActiveNames API operation for Amazon Lightsail. -// -// Returns the names of all active (not deleted) resources. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetActiveNames for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetActiveNames -func (c *Lightsail) GetActiveNames(input *GetActiveNamesInput) (*GetActiveNamesOutput, error) { - req, out := c.GetActiveNamesRequest(input) - return out, req.Send() -} - -// GetActiveNamesWithContext is the same as GetActiveNames with the addition of -// the ability to pass a context and additional request options. -// -// See GetActiveNames for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetActiveNamesWithContext(ctx aws.Context, input *GetActiveNamesInput, opts ...request.Option) (*GetActiveNamesOutput, error) { - req, out := c.GetActiveNamesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBlueprints = "GetBlueprints" - -// GetBlueprintsRequest generates a "aws/request.Request" representing the -// client's request for the GetBlueprints operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBlueprints for more information on using the GetBlueprints -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBlueprintsRequest method. -// req, resp := client.GetBlueprintsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBlueprints -func (c *Lightsail) GetBlueprintsRequest(input *GetBlueprintsInput) (req *request.Request, output *GetBlueprintsOutput) { - op := &request.Operation{ - Name: opGetBlueprints, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetBlueprintsInput{} - } - - output = &GetBlueprintsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBlueprints API operation for Amazon Lightsail. -// -// Returns the list of available instance images, or blueprints. You can use -// a blueprint to create a new virtual private server already running a specific -// operating system, as well as a preinstalled app or development stack. The -// software each instance is running depends on the blueprint image you choose. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetBlueprints for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBlueprints -func (c *Lightsail) GetBlueprints(input *GetBlueprintsInput) (*GetBlueprintsOutput, error) { - req, out := c.GetBlueprintsRequest(input) - return out, req.Send() -} - -// GetBlueprintsWithContext is the same as GetBlueprints with the addition of -// the ability to pass a context and additional request options. -// -// See GetBlueprints for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetBlueprintsWithContext(ctx aws.Context, input *GetBlueprintsInput, opts ...request.Option) (*GetBlueprintsOutput, error) { - req, out := c.GetBlueprintsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBundles = "GetBundles" - -// GetBundlesRequest generates a "aws/request.Request" representing the -// client's request for the GetBundles operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBundles for more information on using the GetBundles -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBundlesRequest method. -// req, resp := client.GetBundlesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBundles -func (c *Lightsail) GetBundlesRequest(input *GetBundlesInput) (req *request.Request, output *GetBundlesOutput) { - op := &request.Operation{ - Name: opGetBundles, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetBundlesInput{} - } - - output = &GetBundlesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBundles API operation for Amazon Lightsail. -// -// Returns the list of bundles that are available for purchase. A bundle describes -// the specs for your virtual private server (or instance). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetBundles for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBundles -func (c *Lightsail) GetBundles(input *GetBundlesInput) (*GetBundlesOutput, error) { - req, out := c.GetBundlesRequest(input) - return out, req.Send() -} - -// GetBundlesWithContext is the same as GetBundles with the addition of -// the ability to pass a context and additional request options. -// -// See GetBundles for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetBundlesWithContext(ctx aws.Context, input *GetBundlesInput, opts ...request.Option) (*GetBundlesOutput, error) { - req, out := c.GetBundlesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDisk = "GetDisk" - -// GetDiskRequest generates a "aws/request.Request" representing the -// client's request for the GetDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDisk for more information on using the GetDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDiskRequest method. -// req, resp := client.GetDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisk -func (c *Lightsail) GetDiskRequest(input *GetDiskInput) (req *request.Request, output *GetDiskOutput) { - op := &request.Operation{ - Name: opGetDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDiskInput{} - } - - output = &GetDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDisk API operation for Amazon Lightsail. -// -// Returns information about a specific block storage disk. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisk -func (c *Lightsail) GetDisk(input *GetDiskInput) (*GetDiskOutput, error) { - req, out := c.GetDiskRequest(input) - return out, req.Send() -} - -// GetDiskWithContext is the same as GetDisk with the addition of -// the ability to pass a context and additional request options. -// -// See GetDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDiskWithContext(ctx aws.Context, input *GetDiskInput, opts ...request.Option) (*GetDiskOutput, error) { - req, out := c.GetDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDiskSnapshot = "GetDiskSnapshot" - -// GetDiskSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the GetDiskSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDiskSnapshot for more information on using the GetDiskSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDiskSnapshotRequest method. -// req, resp := client.GetDiskSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshot -func (c *Lightsail) GetDiskSnapshotRequest(input *GetDiskSnapshotInput) (req *request.Request, output *GetDiskSnapshotOutput) { - op := &request.Operation{ - Name: opGetDiskSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDiskSnapshotInput{} - } - - output = &GetDiskSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDiskSnapshot API operation for Amazon Lightsail. -// -// Returns information about a specific block storage disk snapshot. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDiskSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshot -func (c *Lightsail) GetDiskSnapshot(input *GetDiskSnapshotInput) (*GetDiskSnapshotOutput, error) { - req, out := c.GetDiskSnapshotRequest(input) - return out, req.Send() -} - -// GetDiskSnapshotWithContext is the same as GetDiskSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See GetDiskSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDiskSnapshotWithContext(ctx aws.Context, input *GetDiskSnapshotInput, opts ...request.Option) (*GetDiskSnapshotOutput, error) { - req, out := c.GetDiskSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDiskSnapshots = "GetDiskSnapshots" - -// GetDiskSnapshotsRequest generates a "aws/request.Request" representing the -// client's request for the GetDiskSnapshots operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDiskSnapshots for more information on using the GetDiskSnapshots -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDiskSnapshotsRequest method. -// req, resp := client.GetDiskSnapshotsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshots -func (c *Lightsail) GetDiskSnapshotsRequest(input *GetDiskSnapshotsInput) (req *request.Request, output *GetDiskSnapshotsOutput) { - op := &request.Operation{ - Name: opGetDiskSnapshots, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDiskSnapshotsInput{} - } - - output = &GetDiskSnapshotsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDiskSnapshots API operation for Amazon Lightsail. -// -// Returns information about all block storage disk snapshots in your AWS account -// and region. -// -// If you are describing a long list of disk snapshots, you can paginate the -// output to make the list more manageable. You can use the pageToken and nextPageToken -// values to retrieve the next items in the list. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDiskSnapshots for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshots -func (c *Lightsail) GetDiskSnapshots(input *GetDiskSnapshotsInput) (*GetDiskSnapshotsOutput, error) { - req, out := c.GetDiskSnapshotsRequest(input) - return out, req.Send() -} - -// GetDiskSnapshotsWithContext is the same as GetDiskSnapshots with the addition of -// the ability to pass a context and additional request options. -// -// See GetDiskSnapshots for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDiskSnapshotsWithContext(ctx aws.Context, input *GetDiskSnapshotsInput, opts ...request.Option) (*GetDiskSnapshotsOutput, error) { - req, out := c.GetDiskSnapshotsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDisks = "GetDisks" - -// GetDisksRequest generates a "aws/request.Request" representing the -// client's request for the GetDisks operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDisks for more information on using the GetDisks -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDisksRequest method. -// req, resp := client.GetDisksRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisks -func (c *Lightsail) GetDisksRequest(input *GetDisksInput) (req *request.Request, output *GetDisksOutput) { - op := &request.Operation{ - Name: opGetDisks, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDisksInput{} - } - - output = &GetDisksOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDisks API operation for Amazon Lightsail. -// -// Returns information about all block storage disks in your AWS account and -// region. -// -// If you are describing a long list of disks, you can paginate the output to -// make the list more manageable. You can use the pageToken and nextPageToken -// values to retrieve the next items in the list. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDisks for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisks -func (c *Lightsail) GetDisks(input *GetDisksInput) (*GetDisksOutput, error) { - req, out := c.GetDisksRequest(input) - return out, req.Send() -} - -// GetDisksWithContext is the same as GetDisks with the addition of -// the ability to pass a context and additional request options. -// -// See GetDisks for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDisksWithContext(ctx aws.Context, input *GetDisksInput, opts ...request.Option) (*GetDisksOutput, error) { - req, out := c.GetDisksRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDomain = "GetDomain" - -// GetDomainRequest generates a "aws/request.Request" representing the -// client's request for the GetDomain operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDomain for more information on using the GetDomain -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDomainRequest method. -// req, resp := client.GetDomainRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain -func (c *Lightsail) GetDomainRequest(input *GetDomainInput) (req *request.Request, output *GetDomainOutput) { - op := &request.Operation{ - Name: opGetDomain, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDomainInput{} - } - - output = &GetDomainOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDomain API operation for Amazon Lightsail. -// -// Returns information about a specific domain recordset. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDomain for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain -func (c *Lightsail) GetDomain(input *GetDomainInput) (*GetDomainOutput, error) { - req, out := c.GetDomainRequest(input) - return out, req.Send() -} - -// GetDomainWithContext is the same as GetDomain with the addition of -// the ability to pass a context and additional request options. -// -// See GetDomain for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDomainWithContext(ctx aws.Context, input *GetDomainInput, opts ...request.Option) (*GetDomainOutput, error) { - req, out := c.GetDomainRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDomains = "GetDomains" - -// GetDomainsRequest generates a "aws/request.Request" representing the -// client's request for the GetDomains operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDomains for more information on using the GetDomains -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDomainsRequest method. -// req, resp := client.GetDomainsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains -func (c *Lightsail) GetDomainsRequest(input *GetDomainsInput) (req *request.Request, output *GetDomainsOutput) { - op := &request.Operation{ - Name: opGetDomains, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDomainsInput{} - } - - output = &GetDomainsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDomains API operation for Amazon Lightsail. -// -// Returns a list of all domains in the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDomains for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains -func (c *Lightsail) GetDomains(input *GetDomainsInput) (*GetDomainsOutput, error) { - req, out := c.GetDomainsRequest(input) - return out, req.Send() -} - -// GetDomainsWithContext is the same as GetDomains with the addition of -// the ability to pass a context and additional request options. -// -// See GetDomains for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDomainsWithContext(ctx aws.Context, input *GetDomainsInput, opts ...request.Option) (*GetDomainsOutput, error) { - req, out := c.GetDomainsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstance = "GetInstance" - -// GetInstanceRequest generates a "aws/request.Request" representing the -// client's request for the GetInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstance for more information on using the GetInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceRequest method. -// req, resp := client.GetInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance -func (c *Lightsail) GetInstanceRequest(input *GetInstanceInput) (req *request.Request, output *GetInstanceOutput) { - op := &request.Operation{ - Name: opGetInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceInput{} - } - - output = &GetInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstance API operation for Amazon Lightsail. -// -// Returns information about a specific Amazon Lightsail instance, which is -// a virtual private server. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance -func (c *Lightsail) GetInstance(input *GetInstanceInput) (*GetInstanceOutput, error) { - req, out := c.GetInstanceRequest(input) - return out, req.Send() -} - -// GetInstanceWithContext is the same as GetInstance with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceWithContext(ctx aws.Context, input *GetInstanceInput, opts ...request.Option) (*GetInstanceOutput, error) { - req, out := c.GetInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceAccessDetails = "GetInstanceAccessDetails" - -// GetInstanceAccessDetailsRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceAccessDetails operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceAccessDetails for more information on using the GetInstanceAccessDetails -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceAccessDetailsRequest method. -// req, resp := client.GetInstanceAccessDetailsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails -func (c *Lightsail) GetInstanceAccessDetailsRequest(input *GetInstanceAccessDetailsInput) (req *request.Request, output *GetInstanceAccessDetailsOutput) { - op := &request.Operation{ - Name: opGetInstanceAccessDetails, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceAccessDetailsInput{} - } - - output = &GetInstanceAccessDetailsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceAccessDetails API operation for Amazon Lightsail. -// -// Returns temporary SSH keys you can use to connect to a specific virtual private -// server, or instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceAccessDetails for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails -func (c *Lightsail) GetInstanceAccessDetails(input *GetInstanceAccessDetailsInput) (*GetInstanceAccessDetailsOutput, error) { - req, out := c.GetInstanceAccessDetailsRequest(input) - return out, req.Send() -} - -// GetInstanceAccessDetailsWithContext is the same as GetInstanceAccessDetails with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceAccessDetails for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceAccessDetailsWithContext(ctx aws.Context, input *GetInstanceAccessDetailsInput, opts ...request.Option) (*GetInstanceAccessDetailsOutput, error) { - req, out := c.GetInstanceAccessDetailsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceMetricData = "GetInstanceMetricData" - -// GetInstanceMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceMetricData operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceMetricData for more information on using the GetInstanceMetricData -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceMetricDataRequest method. -// req, resp := client.GetInstanceMetricDataRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData -func (c *Lightsail) GetInstanceMetricDataRequest(input *GetInstanceMetricDataInput) (req *request.Request, output *GetInstanceMetricDataOutput) { - op := &request.Operation{ - Name: opGetInstanceMetricData, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceMetricDataInput{} - } - - output = &GetInstanceMetricDataOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceMetricData API operation for Amazon Lightsail. -// -// Returns the data points for the specified Amazon Lightsail instance metric, -// given an instance name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceMetricData for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData -func (c *Lightsail) GetInstanceMetricData(input *GetInstanceMetricDataInput) (*GetInstanceMetricDataOutput, error) { - req, out := c.GetInstanceMetricDataRequest(input) - return out, req.Send() -} - -// GetInstanceMetricDataWithContext is the same as GetInstanceMetricData with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceMetricData for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceMetricDataWithContext(ctx aws.Context, input *GetInstanceMetricDataInput, opts ...request.Option) (*GetInstanceMetricDataOutput, error) { - req, out := c.GetInstanceMetricDataRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstancePortStates = "GetInstancePortStates" - -// GetInstancePortStatesRequest generates a "aws/request.Request" representing the -// client's request for the GetInstancePortStates operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstancePortStates for more information on using the GetInstancePortStates -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstancePortStatesRequest method. -// req, resp := client.GetInstancePortStatesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates -func (c *Lightsail) GetInstancePortStatesRequest(input *GetInstancePortStatesInput) (req *request.Request, output *GetInstancePortStatesOutput) { - op := &request.Operation{ - Name: opGetInstancePortStates, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstancePortStatesInput{} - } - - output = &GetInstancePortStatesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstancePortStates API operation for Amazon Lightsail. -// -// Returns the port states for a specific virtual private server, or instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstancePortStates for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates -func (c *Lightsail) GetInstancePortStates(input *GetInstancePortStatesInput) (*GetInstancePortStatesOutput, error) { - req, out := c.GetInstancePortStatesRequest(input) - return out, req.Send() -} - -// GetInstancePortStatesWithContext is the same as GetInstancePortStates with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstancePortStates for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstancePortStatesWithContext(ctx aws.Context, input *GetInstancePortStatesInput, opts ...request.Option) (*GetInstancePortStatesOutput, error) { - req, out := c.GetInstancePortStatesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceSnapshot = "GetInstanceSnapshot" - -// GetInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceSnapshot for more information on using the GetInstanceSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceSnapshotRequest method. -// req, resp := client.GetInstanceSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot -func (c *Lightsail) GetInstanceSnapshotRequest(input *GetInstanceSnapshotInput) (req *request.Request, output *GetInstanceSnapshotOutput) { - op := &request.Operation{ - Name: opGetInstanceSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceSnapshotInput{} - } - - output = &GetInstanceSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceSnapshot API operation for Amazon Lightsail. -// -// Returns information about a specific instance snapshot. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot -func (c *Lightsail) GetInstanceSnapshot(input *GetInstanceSnapshotInput) (*GetInstanceSnapshotOutput, error) { - req, out := c.GetInstanceSnapshotRequest(input) - return out, req.Send() -} - -// GetInstanceSnapshotWithContext is the same as GetInstanceSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceSnapshotWithContext(ctx aws.Context, input *GetInstanceSnapshotInput, opts ...request.Option) (*GetInstanceSnapshotOutput, error) { - req, out := c.GetInstanceSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceSnapshots = "GetInstanceSnapshots" - -// GetInstanceSnapshotsRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceSnapshots operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceSnapshots for more information on using the GetInstanceSnapshots -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceSnapshotsRequest method. -// req, resp := client.GetInstanceSnapshotsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots -func (c *Lightsail) GetInstanceSnapshotsRequest(input *GetInstanceSnapshotsInput) (req *request.Request, output *GetInstanceSnapshotsOutput) { - op := &request.Operation{ - Name: opGetInstanceSnapshots, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceSnapshotsInput{} - } - - output = &GetInstanceSnapshotsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceSnapshots API operation for Amazon Lightsail. -// -// Returns all instance snapshots for the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceSnapshots for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots -func (c *Lightsail) GetInstanceSnapshots(input *GetInstanceSnapshotsInput) (*GetInstanceSnapshotsOutput, error) { - req, out := c.GetInstanceSnapshotsRequest(input) - return out, req.Send() -} - -// GetInstanceSnapshotsWithContext is the same as GetInstanceSnapshots with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceSnapshots for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceSnapshotsWithContext(ctx aws.Context, input *GetInstanceSnapshotsInput, opts ...request.Option) (*GetInstanceSnapshotsOutput, error) { - req, out := c.GetInstanceSnapshotsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceState = "GetInstanceState" - -// GetInstanceStateRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceState operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceState for more information on using the GetInstanceState -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceStateRequest method. -// req, resp := client.GetInstanceStateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState -func (c *Lightsail) GetInstanceStateRequest(input *GetInstanceStateInput) (req *request.Request, output *GetInstanceStateOutput) { - op := &request.Operation{ - Name: opGetInstanceState, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceStateInput{} - } - - output = &GetInstanceStateOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceState API operation for Amazon Lightsail. -// -// Returns the state of a specific instance. Works on one instance at a time. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceState for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState -func (c *Lightsail) GetInstanceState(input *GetInstanceStateInput) (*GetInstanceStateOutput, error) { - req, out := c.GetInstanceStateRequest(input) - return out, req.Send() -} - -// GetInstanceStateWithContext is the same as GetInstanceState with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceState for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceStateWithContext(ctx aws.Context, input *GetInstanceStateInput, opts ...request.Option) (*GetInstanceStateOutput, error) { - req, out := c.GetInstanceStateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstances = "GetInstances" - -// GetInstancesRequest generates a "aws/request.Request" representing the -// client's request for the GetInstances operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstances for more information on using the GetInstances -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstancesRequest method. -// req, resp := client.GetInstancesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances -func (c *Lightsail) GetInstancesRequest(input *GetInstancesInput) (req *request.Request, output *GetInstancesOutput) { - op := &request.Operation{ - Name: opGetInstances, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstancesInput{} - } - - output = &GetInstancesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstances API operation for Amazon Lightsail. -// -// Returns information about all Amazon Lightsail virtual private servers, or -// instances. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstances for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances -func (c *Lightsail) GetInstances(input *GetInstancesInput) (*GetInstancesOutput, error) { - req, out := c.GetInstancesRequest(input) - return out, req.Send() -} - -// GetInstancesWithContext is the same as GetInstances with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstances for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstancesWithContext(ctx aws.Context, input *GetInstancesInput, opts ...request.Option) (*GetInstancesOutput, error) { - req, out := c.GetInstancesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetKeyPair = "GetKeyPair" - -// GetKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the GetKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetKeyPair for more information on using the GetKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetKeyPairRequest method. -// req, resp := client.GetKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair -func (c *Lightsail) GetKeyPairRequest(input *GetKeyPairInput) (req *request.Request, output *GetKeyPairOutput) { - op := &request.Operation{ - Name: opGetKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetKeyPairInput{} - } - - output = &GetKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetKeyPair API operation for Amazon Lightsail. -// -// Returns information about a specific key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair -func (c *Lightsail) GetKeyPair(input *GetKeyPairInput) (*GetKeyPairOutput, error) { - req, out := c.GetKeyPairRequest(input) - return out, req.Send() -} - -// GetKeyPairWithContext is the same as GetKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See GetKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetKeyPairWithContext(ctx aws.Context, input *GetKeyPairInput, opts ...request.Option) (*GetKeyPairOutput, error) { - req, out := c.GetKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetKeyPairs = "GetKeyPairs" - -// GetKeyPairsRequest generates a "aws/request.Request" representing the -// client's request for the GetKeyPairs operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetKeyPairs for more information on using the GetKeyPairs -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetKeyPairsRequest method. -// req, resp := client.GetKeyPairsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs -func (c *Lightsail) GetKeyPairsRequest(input *GetKeyPairsInput) (req *request.Request, output *GetKeyPairsOutput) { - op := &request.Operation{ - Name: opGetKeyPairs, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetKeyPairsInput{} - } - - output = &GetKeyPairsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetKeyPairs API operation for Amazon Lightsail. -// -// Returns information about all key pairs in the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetKeyPairs for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs -func (c *Lightsail) GetKeyPairs(input *GetKeyPairsInput) (*GetKeyPairsOutput, error) { - req, out := c.GetKeyPairsRequest(input) - return out, req.Send() -} - -// GetKeyPairsWithContext is the same as GetKeyPairs with the addition of -// the ability to pass a context and additional request options. -// -// See GetKeyPairs for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetKeyPairsWithContext(ctx aws.Context, input *GetKeyPairsInput, opts ...request.Option) (*GetKeyPairsOutput, error) { - req, out := c.GetKeyPairsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancer = "GetLoadBalancer" - -// GetLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancer for more information on using the GetLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancerRequest method. -// req, resp := client.GetLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer -func (c *Lightsail) GetLoadBalancerRequest(input *GetLoadBalancerInput) (req *request.Request, output *GetLoadBalancerOutput) { - op := &request.Operation{ - Name: opGetLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancerInput{} - } - - output = &GetLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancer API operation for Amazon Lightsail. -// -// Returns information about the specified Lightsail load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer -func (c *Lightsail) GetLoadBalancer(input *GetLoadBalancerInput) (*GetLoadBalancerOutput, error) { - req, out := c.GetLoadBalancerRequest(input) - return out, req.Send() -} - -// GetLoadBalancerWithContext is the same as GetLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancerWithContext(ctx aws.Context, input *GetLoadBalancerInput, opts ...request.Option) (*GetLoadBalancerOutput, error) { - req, out := c.GetLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancerMetricData = "GetLoadBalancerMetricData" - -// GetLoadBalancerMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancerMetricData operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancerMetricData for more information on using the GetLoadBalancerMetricData -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancerMetricDataRequest method. -// req, resp := client.GetLoadBalancerMetricDataRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData -func (c *Lightsail) GetLoadBalancerMetricDataRequest(input *GetLoadBalancerMetricDataInput) (req *request.Request, output *GetLoadBalancerMetricDataOutput) { - op := &request.Operation{ - Name: opGetLoadBalancerMetricData, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancerMetricDataInput{} - } - - output = &GetLoadBalancerMetricDataOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancerMetricData API operation for Amazon Lightsail. -// -// Returns information about health metrics for your Lightsail load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancerMetricData for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData -func (c *Lightsail) GetLoadBalancerMetricData(input *GetLoadBalancerMetricDataInput) (*GetLoadBalancerMetricDataOutput, error) { - req, out := c.GetLoadBalancerMetricDataRequest(input) - return out, req.Send() -} - -// GetLoadBalancerMetricDataWithContext is the same as GetLoadBalancerMetricData with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancerMetricData for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancerMetricDataWithContext(ctx aws.Context, input *GetLoadBalancerMetricDataInput, opts ...request.Option) (*GetLoadBalancerMetricDataOutput, error) { - req, out := c.GetLoadBalancerMetricDataRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancerTlsCertificates = "GetLoadBalancerTlsCertificates" - -// GetLoadBalancerTlsCertificatesRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancerTlsCertificates operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancerTlsCertificates for more information on using the GetLoadBalancerTlsCertificates -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancerTlsCertificatesRequest method. -// req, resp := client.GetLoadBalancerTlsCertificatesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates -func (c *Lightsail) GetLoadBalancerTlsCertificatesRequest(input *GetLoadBalancerTlsCertificatesInput) (req *request.Request, output *GetLoadBalancerTlsCertificatesOutput) { - op := &request.Operation{ - Name: opGetLoadBalancerTlsCertificates, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancerTlsCertificatesInput{} - } - - output = &GetLoadBalancerTlsCertificatesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancerTlsCertificates API operation for Amazon Lightsail. -// -// Returns information about the TLS certificates that are associated with the -// specified Lightsail load balancer. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -// -// You can have a maximum of 2 certificates associated with a Lightsail load -// balancer. One is active and the other is inactive. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancerTlsCertificates for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates -func (c *Lightsail) GetLoadBalancerTlsCertificates(input *GetLoadBalancerTlsCertificatesInput) (*GetLoadBalancerTlsCertificatesOutput, error) { - req, out := c.GetLoadBalancerTlsCertificatesRequest(input) - return out, req.Send() -} - -// GetLoadBalancerTlsCertificatesWithContext is the same as GetLoadBalancerTlsCertificates with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancerTlsCertificates for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancerTlsCertificatesWithContext(ctx aws.Context, input *GetLoadBalancerTlsCertificatesInput, opts ...request.Option) (*GetLoadBalancerTlsCertificatesOutput, error) { - req, out := c.GetLoadBalancerTlsCertificatesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancers = "GetLoadBalancers" - -// GetLoadBalancersRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancers operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancers for more information on using the GetLoadBalancers -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancersRequest method. -// req, resp := client.GetLoadBalancersRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers -func (c *Lightsail) GetLoadBalancersRequest(input *GetLoadBalancersInput) (req *request.Request, output *GetLoadBalancersOutput) { - op := &request.Operation{ - Name: opGetLoadBalancers, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancersInput{} - } - - output = &GetLoadBalancersOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancers API operation for Amazon Lightsail. -// -// Returns information about all load balancers in an account. -// -// If you are describing a long list of load balancers, you can paginate the -// output to make the list more manageable. You can use the pageToken and nextPageToken -// values to retrieve the next items in the list. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancers for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers -func (c *Lightsail) GetLoadBalancers(input *GetLoadBalancersInput) (*GetLoadBalancersOutput, error) { - req, out := c.GetLoadBalancersRequest(input) - return out, req.Send() -} - -// GetLoadBalancersWithContext is the same as GetLoadBalancers with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancers for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancersWithContext(ctx aws.Context, input *GetLoadBalancersInput, opts ...request.Option) (*GetLoadBalancersOutput, error) { - req, out := c.GetLoadBalancersRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetOperation = "GetOperation" - -// GetOperationRequest generates a "aws/request.Request" representing the -// client's request for the GetOperation operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetOperation for more information on using the GetOperation -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetOperationRequest method. -// req, resp := client.GetOperationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation -func (c *Lightsail) GetOperationRequest(input *GetOperationInput) (req *request.Request, output *GetOperationOutput) { - op := &request.Operation{ - Name: opGetOperation, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetOperationInput{} - } - - output = &GetOperationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetOperation API operation for Amazon Lightsail. -// -// Returns information about a specific operation. Operations include events -// such as when you create an instance, allocate a static IP, attach a static -// IP, and so on. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperation for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation -func (c *Lightsail) GetOperation(input *GetOperationInput) (*GetOperationOutput, error) { - req, out := c.GetOperationRequest(input) - return out, req.Send() -} - -// GetOperationWithContext is the same as GetOperation with the addition of -// the ability to pass a context and additional request options. -// -// See GetOperation for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetOperationWithContext(ctx aws.Context, input *GetOperationInput, opts ...request.Option) (*GetOperationOutput, error) { - req, out := c.GetOperationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetOperations = "GetOperations" - -// GetOperationsRequest generates a "aws/request.Request" representing the -// client's request for the GetOperations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetOperations for more information on using the GetOperations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetOperationsRequest method. -// req, resp := client.GetOperationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations -func (c *Lightsail) GetOperationsRequest(input *GetOperationsInput) (req *request.Request, output *GetOperationsOutput) { - op := &request.Operation{ - Name: opGetOperations, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetOperationsInput{} - } - - output = &GetOperationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetOperations API operation for Amazon Lightsail. -// -// Returns information about all operations. -// -// Results are returned from oldest to newest, up to a maximum of 200. Results -// can be paged by making each subsequent call to GetOperations use the maximum -// (last) statusChangedAt value from the previous request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperations for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations -func (c *Lightsail) GetOperations(input *GetOperationsInput) (*GetOperationsOutput, error) { - req, out := c.GetOperationsRequest(input) - return out, req.Send() -} - -// GetOperationsWithContext is the same as GetOperations with the addition of -// the ability to pass a context and additional request options. -// -// See GetOperations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetOperationsWithContext(ctx aws.Context, input *GetOperationsInput, opts ...request.Option) (*GetOperationsOutput, error) { - req, out := c.GetOperationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetOperationsForResource = "GetOperationsForResource" - -// GetOperationsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the GetOperationsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetOperationsForResource for more information on using the GetOperationsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetOperationsForResourceRequest method. -// req, resp := client.GetOperationsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource -func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResourceInput) (req *request.Request, output *GetOperationsForResourceOutput) { - op := &request.Operation{ - Name: opGetOperationsForResource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetOperationsForResourceInput{} - } - - output = &GetOperationsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetOperationsForResource API operation for Amazon Lightsail. -// -// Gets operations for a specific resource (e.g., an instance or a static IP). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperationsForResource for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource -func (c *Lightsail) GetOperationsForResource(input *GetOperationsForResourceInput) (*GetOperationsForResourceOutput, error) { - req, out := c.GetOperationsForResourceRequest(input) - return out, req.Send() -} - -// GetOperationsForResourceWithContext is the same as GetOperationsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See GetOperationsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetOperationsForResourceWithContext(ctx aws.Context, input *GetOperationsForResourceInput, opts ...request.Option) (*GetOperationsForResourceOutput, error) { - req, out := c.GetOperationsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetRegions = "GetRegions" - -// GetRegionsRequest generates a "aws/request.Request" representing the -// client's request for the GetRegions operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetRegions for more information on using the GetRegions -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetRegionsRequest method. -// req, resp := client.GetRegionsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions -func (c *Lightsail) GetRegionsRequest(input *GetRegionsInput) (req *request.Request, output *GetRegionsOutput) { - op := &request.Operation{ - Name: opGetRegions, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetRegionsInput{} - } - - output = &GetRegionsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetRegions API operation for Amazon Lightsail. -// -// Returns a list of all valid regions for Amazon Lightsail. Use the include -// availability zones parameter to also return the availability zones in a region. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetRegions for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions -func (c *Lightsail) GetRegions(input *GetRegionsInput) (*GetRegionsOutput, error) { - req, out := c.GetRegionsRequest(input) - return out, req.Send() -} - -// GetRegionsWithContext is the same as GetRegions with the addition of -// the ability to pass a context and additional request options. -// -// See GetRegions for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetRegionsWithContext(ctx aws.Context, input *GetRegionsInput, opts ...request.Option) (*GetRegionsOutput, error) { - req, out := c.GetRegionsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetStaticIp = "GetStaticIp" - -// GetStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the GetStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetStaticIp for more information on using the GetStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetStaticIpRequest method. -// req, resp := client.GetStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp -func (c *Lightsail) GetStaticIpRequest(input *GetStaticIpInput) (req *request.Request, output *GetStaticIpOutput) { - op := &request.Operation{ - Name: opGetStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetStaticIpInput{} - } - - output = &GetStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetStaticIp API operation for Amazon Lightsail. -// -// Returns information about a specific static IP. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp -func (c *Lightsail) GetStaticIp(input *GetStaticIpInput) (*GetStaticIpOutput, error) { - req, out := c.GetStaticIpRequest(input) - return out, req.Send() -} - -// GetStaticIpWithContext is the same as GetStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See GetStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetStaticIpWithContext(ctx aws.Context, input *GetStaticIpInput, opts ...request.Option) (*GetStaticIpOutput, error) { - req, out := c.GetStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetStaticIps = "GetStaticIps" - -// GetStaticIpsRequest generates a "aws/request.Request" representing the -// client's request for the GetStaticIps operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetStaticIps for more information on using the GetStaticIps -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetStaticIpsRequest method. -// req, resp := client.GetStaticIpsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps -func (c *Lightsail) GetStaticIpsRequest(input *GetStaticIpsInput) (req *request.Request, output *GetStaticIpsOutput) { - op := &request.Operation{ - Name: opGetStaticIps, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetStaticIpsInput{} - } - - output = &GetStaticIpsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetStaticIps API operation for Amazon Lightsail. -// -// Returns information about all static IPs in the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetStaticIps for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps -func (c *Lightsail) GetStaticIps(input *GetStaticIpsInput) (*GetStaticIpsOutput, error) { - req, out := c.GetStaticIpsRequest(input) - return out, req.Send() -} - -// GetStaticIpsWithContext is the same as GetStaticIps with the addition of -// the ability to pass a context and additional request options. -// -// See GetStaticIps for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetStaticIpsWithContext(ctx aws.Context, input *GetStaticIpsInput, opts ...request.Option) (*GetStaticIpsOutput, error) { - req, out := c.GetStaticIpsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opImportKeyPair = "ImportKeyPair" - -// ImportKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the ImportKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ImportKeyPair for more information on using the ImportKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ImportKeyPairRequest method. -// req, resp := client.ImportKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair -func (c *Lightsail) ImportKeyPairRequest(input *ImportKeyPairInput) (req *request.Request, output *ImportKeyPairOutput) { - op := &request.Operation{ - Name: opImportKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &ImportKeyPairInput{} - } - - output = &ImportKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// ImportKeyPair API operation for Amazon Lightsail. -// -// Imports a public SSH key from a specific key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation ImportKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair -func (c *Lightsail) ImportKeyPair(input *ImportKeyPairInput) (*ImportKeyPairOutput, error) { - req, out := c.ImportKeyPairRequest(input) - return out, req.Send() -} - -// ImportKeyPairWithContext is the same as ImportKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See ImportKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) ImportKeyPairWithContext(ctx aws.Context, input *ImportKeyPairInput, opts ...request.Option) (*ImportKeyPairOutput, error) { - req, out := c.ImportKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opIsVpcPeered = "IsVpcPeered" - -// IsVpcPeeredRequest generates a "aws/request.Request" representing the -// client's request for the IsVpcPeered operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See IsVpcPeered for more information on using the IsVpcPeered -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the IsVpcPeeredRequest method. -// req, resp := client.IsVpcPeeredRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered -func (c *Lightsail) IsVpcPeeredRequest(input *IsVpcPeeredInput) (req *request.Request, output *IsVpcPeeredOutput) { - op := &request.Operation{ - Name: opIsVpcPeered, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &IsVpcPeeredInput{} - } - - output = &IsVpcPeeredOutput{} - req = c.newRequest(op, input, output) - return -} - -// IsVpcPeered API operation for Amazon Lightsail. -// -// Returns a Boolean value indicating whether your Lightsail VPC is peered. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation IsVpcPeered for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered -func (c *Lightsail) IsVpcPeered(input *IsVpcPeeredInput) (*IsVpcPeeredOutput, error) { - req, out := c.IsVpcPeeredRequest(input) - return out, req.Send() -} - -// IsVpcPeeredWithContext is the same as IsVpcPeered with the addition of -// the ability to pass a context and additional request options. -// -// See IsVpcPeered for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) IsVpcPeeredWithContext(ctx aws.Context, input *IsVpcPeeredInput, opts ...request.Option) (*IsVpcPeeredOutput, error) { - req, out := c.IsVpcPeeredRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opOpenInstancePublicPorts = "OpenInstancePublicPorts" - -// OpenInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the OpenInstancePublicPorts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OpenInstancePublicPorts for more information on using the OpenInstancePublicPorts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OpenInstancePublicPortsRequest method. -// req, resp := client.OpenInstancePublicPortsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts -func (c *Lightsail) OpenInstancePublicPortsRequest(input *OpenInstancePublicPortsInput) (req *request.Request, output *OpenInstancePublicPortsOutput) { - op := &request.Operation{ - Name: opOpenInstancePublicPorts, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &OpenInstancePublicPortsInput{} - } - - output = &OpenInstancePublicPortsOutput{} - req = c.newRequest(op, input, output) - return -} - -// OpenInstancePublicPorts API operation for Amazon Lightsail. -// -// Adds public ports to an Amazon Lightsail instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation OpenInstancePublicPorts for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts -func (c *Lightsail) OpenInstancePublicPorts(input *OpenInstancePublicPortsInput) (*OpenInstancePublicPortsOutput, error) { - req, out := c.OpenInstancePublicPortsRequest(input) - return out, req.Send() -} - -// OpenInstancePublicPortsWithContext is the same as OpenInstancePublicPorts with the addition of -// the ability to pass a context and additional request options. -// -// See OpenInstancePublicPorts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) OpenInstancePublicPortsWithContext(ctx aws.Context, input *OpenInstancePublicPortsInput, opts ...request.Option) (*OpenInstancePublicPortsOutput, error) { - req, out := c.OpenInstancePublicPortsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPeerVpc = "PeerVpc" - -// PeerVpcRequest generates a "aws/request.Request" representing the -// client's request for the PeerVpc operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PeerVpc for more information on using the PeerVpc -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PeerVpcRequest method. -// req, resp := client.PeerVpcRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc -func (c *Lightsail) PeerVpcRequest(input *PeerVpcInput) (req *request.Request, output *PeerVpcOutput) { - op := &request.Operation{ - Name: opPeerVpc, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PeerVpcInput{} - } - - output = &PeerVpcOutput{} - req = c.newRequest(op, input, output) - return -} - -// PeerVpc API operation for Amazon Lightsail. -// -// Tries to peer the Lightsail VPC with the user's default VPC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation PeerVpc for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc -func (c *Lightsail) PeerVpc(input *PeerVpcInput) (*PeerVpcOutput, error) { - req, out := c.PeerVpcRequest(input) - return out, req.Send() -} - -// PeerVpcWithContext is the same as PeerVpc with the addition of -// the ability to pass a context and additional request options. -// -// See PeerVpc for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) PeerVpcWithContext(ctx aws.Context, input *PeerVpcInput, opts ...request.Option) (*PeerVpcOutput, error) { - req, out := c.PeerVpcRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutInstancePublicPorts = "PutInstancePublicPorts" - -// PutInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the PutInstancePublicPorts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutInstancePublicPorts for more information on using the PutInstancePublicPorts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutInstancePublicPortsRequest method. -// req, resp := client.PutInstancePublicPortsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts -func (c *Lightsail) PutInstancePublicPortsRequest(input *PutInstancePublicPortsInput) (req *request.Request, output *PutInstancePublicPortsOutput) { - op := &request.Operation{ - Name: opPutInstancePublicPorts, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutInstancePublicPortsInput{} - } - - output = &PutInstancePublicPortsOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutInstancePublicPorts API operation for Amazon Lightsail. -// -// Sets the specified open ports for an Amazon Lightsail instance, and closes -// all ports for every protocol not included in the current request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation PutInstancePublicPorts for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts -func (c *Lightsail) PutInstancePublicPorts(input *PutInstancePublicPortsInput) (*PutInstancePublicPortsOutput, error) { - req, out := c.PutInstancePublicPortsRequest(input) - return out, req.Send() -} - -// PutInstancePublicPortsWithContext is the same as PutInstancePublicPorts with the addition of -// the ability to pass a context and additional request options. -// -// See PutInstancePublicPorts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) PutInstancePublicPortsWithContext(ctx aws.Context, input *PutInstancePublicPortsInput, opts ...request.Option) (*PutInstancePublicPortsOutput, error) { - req, out := c.PutInstancePublicPortsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opRebootInstance = "RebootInstance" - -// RebootInstanceRequest generates a "aws/request.Request" representing the -// client's request for the RebootInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See RebootInstance for more information on using the RebootInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the RebootInstanceRequest method. -// req, resp := client.RebootInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance -func (c *Lightsail) RebootInstanceRequest(input *RebootInstanceInput) (req *request.Request, output *RebootInstanceOutput) { - op := &request.Operation{ - Name: opRebootInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &RebootInstanceInput{} - } - - output = &RebootInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// RebootInstance API operation for Amazon Lightsail. -// -// Restarts a specific instance. When your Amazon Lightsail instance is finished -// rebooting, Lightsail assigns a new public IP address. To use the same IP -// address after restarting, create a static IP address and attach it to the -// instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation RebootInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance -func (c *Lightsail) RebootInstance(input *RebootInstanceInput) (*RebootInstanceOutput, error) { - req, out := c.RebootInstanceRequest(input) - return out, req.Send() -} - -// RebootInstanceWithContext is the same as RebootInstance with the addition of -// the ability to pass a context and additional request options. -// -// See RebootInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) RebootInstanceWithContext(ctx aws.Context, input *RebootInstanceInput, opts ...request.Option) (*RebootInstanceOutput, error) { - req, out := c.RebootInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opReleaseStaticIp = "ReleaseStaticIp" - -// ReleaseStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the ReleaseStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ReleaseStaticIp for more information on using the ReleaseStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ReleaseStaticIpRequest method. -// req, resp := client.ReleaseStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp -func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *request.Request, output *ReleaseStaticIpOutput) { - op := &request.Operation{ - Name: opReleaseStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &ReleaseStaticIpInput{} - } - - output = &ReleaseStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// ReleaseStaticIp API operation for Amazon Lightsail. -// -// Deletes a specific static IP from your account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation ReleaseStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp -func (c *Lightsail) ReleaseStaticIp(input *ReleaseStaticIpInput) (*ReleaseStaticIpOutput, error) { - req, out := c.ReleaseStaticIpRequest(input) - return out, req.Send() -} - -// ReleaseStaticIpWithContext is the same as ReleaseStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See ReleaseStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) ReleaseStaticIpWithContext(ctx aws.Context, input *ReleaseStaticIpInput, opts ...request.Option) (*ReleaseStaticIpOutput, error) { - req, out := c.ReleaseStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStartInstance = "StartInstance" - -// StartInstanceRequest generates a "aws/request.Request" representing the -// client's request for the StartInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StartInstance for more information on using the StartInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the StartInstanceRequest method. -// req, resp := client.StartInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance -func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *request.Request, output *StartInstanceOutput) { - op := &request.Operation{ - Name: opStartInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StartInstanceInput{} - } - - output = &StartInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// StartInstance API operation for Amazon Lightsail. -// -// Starts a specific Amazon Lightsail instance from a stopped state. To restart -// an instance, use the reboot instance operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation StartInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance -func (c *Lightsail) StartInstance(input *StartInstanceInput) (*StartInstanceOutput, error) { - req, out := c.StartInstanceRequest(input) - return out, req.Send() -} - -// StartInstanceWithContext is the same as StartInstance with the addition of -// the ability to pass a context and additional request options. -// -// See StartInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) StartInstanceWithContext(ctx aws.Context, input *StartInstanceInput, opts ...request.Option) (*StartInstanceOutput, error) { - req, out := c.StartInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStopInstance = "StopInstance" - -// StopInstanceRequest generates a "aws/request.Request" representing the -// client's request for the StopInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StopInstance for more information on using the StopInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the StopInstanceRequest method. -// req, resp := client.StopInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance -func (c *Lightsail) StopInstanceRequest(input *StopInstanceInput) (req *request.Request, output *StopInstanceOutput) { - op := &request.Operation{ - Name: opStopInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StopInstanceInput{} - } - - output = &StopInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// StopInstance API operation for Amazon Lightsail. -// -// Stops a specific Amazon Lightsail instance that is currently running. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation StopInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance -func (c *Lightsail) StopInstance(input *StopInstanceInput) (*StopInstanceOutput, error) { - req, out := c.StopInstanceRequest(input) - return out, req.Send() -} - -// StopInstanceWithContext is the same as StopInstance with the addition of -// the ability to pass a context and additional request options. -// -// See StopInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) StopInstanceWithContext(ctx aws.Context, input *StopInstanceInput, opts ...request.Option) (*StopInstanceOutput, error) { - req, out := c.StopInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUnpeerVpc = "UnpeerVpc" - -// UnpeerVpcRequest generates a "aws/request.Request" representing the -// client's request for the UnpeerVpc operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UnpeerVpc for more information on using the UnpeerVpc -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UnpeerVpcRequest method. -// req, resp := client.UnpeerVpcRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc -func (c *Lightsail) UnpeerVpcRequest(input *UnpeerVpcInput) (req *request.Request, output *UnpeerVpcOutput) { - op := &request.Operation{ - Name: opUnpeerVpc, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UnpeerVpcInput{} - } - - output = &UnpeerVpcOutput{} - req = c.newRequest(op, input, output) - return -} - -// UnpeerVpc API operation for Amazon Lightsail. -// -// Attempts to unpeer the Lightsail VPC from the user's default VPC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation UnpeerVpc for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc -func (c *Lightsail) UnpeerVpc(input *UnpeerVpcInput) (*UnpeerVpcOutput, error) { - req, out := c.UnpeerVpcRequest(input) - return out, req.Send() -} - -// UnpeerVpcWithContext is the same as UnpeerVpc with the addition of -// the ability to pass a context and additional request options. -// -// See UnpeerVpc for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) UnpeerVpcWithContext(ctx aws.Context, input *UnpeerVpcInput, opts ...request.Option) (*UnpeerVpcOutput, error) { - req, out := c.UnpeerVpcRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateDomainEntry = "UpdateDomainEntry" - -// UpdateDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDomainEntry operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateDomainEntry for more information on using the UpdateDomainEntry -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateDomainEntryRequest method. -// req, resp := client.UpdateDomainEntryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry -func (c *Lightsail) UpdateDomainEntryRequest(input *UpdateDomainEntryInput) (req *request.Request, output *UpdateDomainEntryOutput) { - op := &request.Operation{ - Name: opUpdateDomainEntry, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UpdateDomainEntryInput{} - } - - output = &UpdateDomainEntryOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateDomainEntry API operation for Amazon Lightsail. -// -// Updates a domain recordset after it is created. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation UpdateDomainEntry for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry -func (c *Lightsail) UpdateDomainEntry(input *UpdateDomainEntryInput) (*UpdateDomainEntryOutput, error) { - req, out := c.UpdateDomainEntryRequest(input) - return out, req.Send() -} - -// UpdateDomainEntryWithContext is the same as UpdateDomainEntry with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateDomainEntry for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) UpdateDomainEntryWithContext(ctx aws.Context, input *UpdateDomainEntryInput, opts ...request.Option) (*UpdateDomainEntryOutput, error) { - req, out := c.UpdateDomainEntryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateLoadBalancerAttribute = "UpdateLoadBalancerAttribute" - -// UpdateLoadBalancerAttributeRequest generates a "aws/request.Request" representing the -// client's request for the UpdateLoadBalancerAttribute operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateLoadBalancerAttribute for more information on using the UpdateLoadBalancerAttribute -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateLoadBalancerAttributeRequest method. -// req, resp := client.UpdateLoadBalancerAttributeRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute -func (c *Lightsail) UpdateLoadBalancerAttributeRequest(input *UpdateLoadBalancerAttributeInput) (req *request.Request, output *UpdateLoadBalancerAttributeOutput) { - op := &request.Operation{ - Name: opUpdateLoadBalancerAttribute, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UpdateLoadBalancerAttributeInput{} - } - - output = &UpdateLoadBalancerAttributeOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateLoadBalancerAttribute API operation for Amazon Lightsail. -// -// Updates the specified attribute for a load balancer. You can only update -// one attribute at a time. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation UpdateLoadBalancerAttribute for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute -func (c *Lightsail) UpdateLoadBalancerAttribute(input *UpdateLoadBalancerAttributeInput) (*UpdateLoadBalancerAttributeOutput, error) { - req, out := c.UpdateLoadBalancerAttributeRequest(input) - return out, req.Send() -} - -// UpdateLoadBalancerAttributeWithContext is the same as UpdateLoadBalancerAttribute with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateLoadBalancerAttribute for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) UpdateLoadBalancerAttributeWithContext(ctx aws.Context, input *UpdateLoadBalancerAttributeInput, opts ...request.Option) (*UpdateLoadBalancerAttributeOutput, error) { - req, out := c.UpdateLoadBalancerAttributeRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type AllocateStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP address. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AllocateStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AllocateStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AllocateStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AllocateStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *AllocateStaticIpInput) SetStaticIpName(v string) *AllocateStaticIpInput { - s.StaticIpName = &v - return s -} - -type AllocateStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the static IP address - // you allocated. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AllocateStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AllocateStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AllocateStaticIpOutput) SetOperations(v []*Operation) *AllocateStaticIpOutput { - s.Operations = v - return s -} - -type AttachDiskInput struct { - _ struct{} `type:"structure"` - - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The disk path to expose to the instance (e.g., /dev/xvdf). - // - // DiskPath is a required field - DiskPath *string `locationName:"diskPath" type:"string" required:"true"` - - // The name of the Lightsail instance where you want to utilize the storage - // disk. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskPath == nil { - invalidParams.Add(request.NewErrParamRequired("DiskPath")) - } - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *AttachDiskInput) SetDiskName(v string) *AttachDiskInput { - s.DiskName = &v - return s -} - -// SetDiskPath sets the DiskPath field's value. -func (s *AttachDiskInput) SetDiskPath(v string) *AttachDiskInput { - s.DiskPath = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *AttachDiskInput) SetInstanceName(v string) *AttachDiskInput { - s.InstanceName = &v - return s -} - -type AttachDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachDiskOutput) SetOperations(v []*Operation) *AttachDiskOutput { - s.Operations = v - return s -} - -type AttachInstancesToLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // An array of strings representing the instance name(s) you want to attach - // to your load balancer. - // - // An instance must be running before you can attach it to your load balancer. - // - // There are no additional limits on the number of instances you can attach - // to your load balancer, aside from the limit of Lightsail instances you can - // create in your account (20). - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachInstancesToLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachInstancesToLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachInstancesToLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachInstancesToLoadBalancerInput"} - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *AttachInstancesToLoadBalancerInput) SetInstanceNames(v []*string) *AttachInstancesToLoadBalancerInput { - s.InstanceNames = v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *AttachInstancesToLoadBalancerInput) SetLoadBalancerName(v string) *AttachInstancesToLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type AttachInstancesToLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object representing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachInstancesToLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachInstancesToLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachInstancesToLoadBalancerOutput) SetOperations(v []*Operation) *AttachInstancesToLoadBalancerOutput { - s.Operations = v - return s -} - -type AttachLoadBalancerTlsCertificateInput struct { - _ struct{} `type:"structure"` - - // The name of your SSL/TLS certificate. - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // The name of the load balancer to which you want to associate the SSL/TLS - // certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachLoadBalancerTlsCertificateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachLoadBalancerTlsCertificateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachLoadBalancerTlsCertificateInput"} - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateName sets the CertificateName field's value. -func (s *AttachLoadBalancerTlsCertificateInput) SetCertificateName(v string) *AttachLoadBalancerTlsCertificateInput { - s.CertificateName = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *AttachLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *AttachLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -type AttachLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` - - // An object representing the API operations. - // - // These SSL/TLS certificates are only usable by Lightsail load balancers. You - // can't get the certificate and use it for another purpose. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *AttachLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} - -type AttachStaticIpInput struct { - _ struct{} `type:"structure"` - - // The instance name to which you want to attach the static IP address. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The name of the static IP. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachStaticIpInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *AttachStaticIpInput) SetInstanceName(v string) *AttachStaticIpInput { - s.InstanceName = &v - return s -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *AttachStaticIpInput) SetStaticIpName(v string) *AttachStaticIpInput { - s.StaticIpName = &v - return s -} - -type AttachStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachStaticIpOutput) SetOperations(v []*Operation) *AttachStaticIpOutput { - s.Operations = v - return s -} - -// Describes an Availability Zone. -type AvailabilityZone struct { - _ struct{} `type:"structure"` - - // The state of the Availability Zone. - State *string `locationName:"state" type:"string"` - - // The name of the Availability Zone. The format is us-east-2a (case-sensitive). - ZoneName *string `locationName:"zoneName" type:"string"` -} - -// String returns the string representation -func (s AvailabilityZone) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AvailabilityZone) GoString() string { - return s.String() -} - -// SetState sets the State field's value. -func (s *AvailabilityZone) SetState(v string) *AvailabilityZone { - s.State = &v - return s -} - -// SetZoneName sets the ZoneName field's value. -func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { - s.ZoneName = &v - return s -} - -// Describes a blueprint (a virtual private server image). -type Blueprint struct { - _ struct{} `type:"structure"` - - // The ID for the virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). - BlueprintId *string `locationName:"blueprintId" type:"string"` - - // The description of the blueprint. - Description *string `locationName:"description" type:"string"` - - // The group name of the blueprint (e.g., amazon-linux). - Group *string `locationName:"group" type:"string"` - - // A Boolean value indicating whether the blueprint is active. When you update - // your blueprints, you will inactivate old blueprints and keep the most recent - // versions active. - IsActive *bool `locationName:"isActive" type:"boolean"` - - // The end-user license agreement URL for the image or blueprint. - LicenseUrl *string `locationName:"licenseUrl" type:"string"` - - // The minimum bundle power required to run this blueprint. For example, you - // need a bundle with a power value of 500 or more to create an instance that - // uses a blueprint with a minimum power value of 500. 0 indicates that the - // blueprint runs on all instance sizes. - MinPower *int64 `locationName:"minPower" type:"integer"` - - // The friendly name of the blueprint (e.g., Amazon Linux). - Name *string `locationName:"name" type:"string"` - - // The operating system platform (either Linux/Unix-based or Windows Server-based) - // of the blueprint. - Platform *string `locationName:"platform" type:"string" enum:"InstancePlatform"` - - // The product URL to learn more about the image or blueprint. - ProductUrl *string `locationName:"productUrl" type:"string"` - - // The type of the blueprint (e.g., os or app). - Type *string `locationName:"type" type:"string" enum:"BlueprintType"` - - // The version number of the operating system, application, or stack (e.g., - // 2016.03.0). - Version *string `locationName:"version" type:"string"` - - // The version code. - VersionCode *string `locationName:"versionCode" type:"string"` -} - -// String returns the string representation -func (s Blueprint) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Blueprint) GoString() string { - return s.String() -} - -// SetBlueprintId sets the BlueprintId field's value. -func (s *Blueprint) SetBlueprintId(v string) *Blueprint { - s.BlueprintId = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *Blueprint) SetDescription(v string) *Blueprint { - s.Description = &v - return s -} - -// SetGroup sets the Group field's value. -func (s *Blueprint) SetGroup(v string) *Blueprint { - s.Group = &v - return s -} - -// SetIsActive sets the IsActive field's value. -func (s *Blueprint) SetIsActive(v bool) *Blueprint { - s.IsActive = &v - return s -} - -// SetLicenseUrl sets the LicenseUrl field's value. -func (s *Blueprint) SetLicenseUrl(v string) *Blueprint { - s.LicenseUrl = &v - return s -} - -// SetMinPower sets the MinPower field's value. -func (s *Blueprint) SetMinPower(v int64) *Blueprint { - s.MinPower = &v - return s -} - -// SetName sets the Name field's value. -func (s *Blueprint) SetName(v string) *Blueprint { - s.Name = &v - return s -} - -// SetPlatform sets the Platform field's value. -func (s *Blueprint) SetPlatform(v string) *Blueprint { - s.Platform = &v - return s -} - -// SetProductUrl sets the ProductUrl field's value. -func (s *Blueprint) SetProductUrl(v string) *Blueprint { - s.ProductUrl = &v - return s -} - -// SetType sets the Type field's value. -func (s *Blueprint) SetType(v string) *Blueprint { - s.Type = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *Blueprint) SetVersion(v string) *Blueprint { - s.Version = &v - return s -} - -// SetVersionCode sets the VersionCode field's value. -func (s *Blueprint) SetVersionCode(v string) *Blueprint { - s.VersionCode = &v - return s -} - -// Describes a bundle, which is a set of specs describing your virtual private -// server (or instance). -type Bundle struct { - _ struct{} `type:"structure"` - - // The bundle ID (e.g., micro_1_0). - BundleId *string `locationName:"bundleId" type:"string"` - - // The number of vCPUs included in the bundle (e.g., 2). - CpuCount *int64 `locationName:"cpuCount" type:"integer"` - - // The size of the SSD (e.g., 30). - DiskSizeInGb *int64 `locationName:"diskSizeInGb" type:"integer"` - - // The Amazon EC2 instance type (e.g., t2.micro). - InstanceType *string `locationName:"instanceType" type:"string"` - - // A Boolean value indicating whether the bundle is active. - IsActive *bool `locationName:"isActive" type:"boolean"` - - // A friendly name for the bundle (e.g., Micro). - Name *string `locationName:"name" type:"string"` - - // A numeric value that represents the power of the bundle (e.g., 500). You - // can use the bundle's power value in conjunction with a blueprint's minimum - // power value to determine whether the blueprint will run on the bundle. For - // example, you need a bundle with a power value of 500 or more to create an - // instance that uses a blueprint with a minimum power value of 500. - Power *int64 `locationName:"power" type:"integer"` - - // The price in US dollars (e.g., 5.0). - Price *float64 `locationName:"price" type:"float"` - - // The amount of RAM in GB (e.g., 2.0). - RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` - - // The operating system platform (Linux/Unix-based or Windows Server-based) - // that the bundle supports. You can only launch a WINDOWS bundle on a blueprint - // that supports the WINDOWS platform. LINUX_UNIX blueprints require a LINUX_UNIX - // bundle. - SupportedPlatforms []*string `locationName:"supportedPlatforms" type:"list"` - - // The data transfer rate per month in GB (e.g., 2000). - TransferPerMonthInGb *int64 `locationName:"transferPerMonthInGb" type:"integer"` -} - -// String returns the string representation -func (s Bundle) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Bundle) GoString() string { - return s.String() -} - -// SetBundleId sets the BundleId field's value. -func (s *Bundle) SetBundleId(v string) *Bundle { - s.BundleId = &v - return s -} - -// SetCpuCount sets the CpuCount field's value. -func (s *Bundle) SetCpuCount(v int64) *Bundle { - s.CpuCount = &v - return s -} - -// SetDiskSizeInGb sets the DiskSizeInGb field's value. -func (s *Bundle) SetDiskSizeInGb(v int64) *Bundle { - s.DiskSizeInGb = &v - return s -} - -// SetInstanceType sets the InstanceType field's value. -func (s *Bundle) SetInstanceType(v string) *Bundle { - s.InstanceType = &v - return s -} - -// SetIsActive sets the IsActive field's value. -func (s *Bundle) SetIsActive(v bool) *Bundle { - s.IsActive = &v - return s -} - -// SetName sets the Name field's value. -func (s *Bundle) SetName(v string) *Bundle { - s.Name = &v - return s -} - -// SetPower sets the Power field's value. -func (s *Bundle) SetPower(v int64) *Bundle { - s.Power = &v - return s -} - -// SetPrice sets the Price field's value. -func (s *Bundle) SetPrice(v float64) *Bundle { - s.Price = &v - return s -} - -// SetRamSizeInGb sets the RamSizeInGb field's value. -func (s *Bundle) SetRamSizeInGb(v float64) *Bundle { - s.RamSizeInGb = &v - return s -} - -// SetSupportedPlatforms sets the SupportedPlatforms field's value. -func (s *Bundle) SetSupportedPlatforms(v []*string) *Bundle { - s.SupportedPlatforms = v - return s -} - -// SetTransferPerMonthInGb sets the TransferPerMonthInGb field's value. -func (s *Bundle) SetTransferPerMonthInGb(v int64) *Bundle { - s.TransferPerMonthInGb = &v - return s -} - -type CloseInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance on which you're attempting to close the public ports. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // Information about the public port you are trying to close. - // - // PortInfo is a required field - PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` -} - -// String returns the string representation -func (s CloseInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloseInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CloseInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CloseInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfo == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfo")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *CloseInstancePublicPortsInput) SetInstanceName(v string) *CloseInstancePublicPortsInput { - s.InstanceName = &v - return s -} - -// SetPortInfo sets the PortInfo field's value. -func (s *CloseInstancePublicPortsInput) SetPortInfo(v *PortInfo) *CloseInstancePublicPortsInput { - s.PortInfo = v - return s -} - -type CloseInstancePublicPortsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs that contains information about the operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CloseInstancePublicPortsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloseInstancePublicPortsOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *CloseInstancePublicPortsOutput) SetOperation(v *Operation) *CloseInstancePublicPortsOutput { - s.Operation = v - return s -} - -type CreateDiskFromSnapshotInput struct { - _ struct{} `type:"structure"` - - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Choose the same Availability Zone as the Lightsail instance where you want - // to create the disk. - // - // Use the GetRegions operation to list the Availability Zones where Lightsail - // is currently available. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The name of the disk snapshot (e.g., my-snapshot) from which to create the - // new storage disk. - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` - - // The size of the disk in GB (e.g., 32). - // - // SizeInGb is a required field - SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` -} - -// String returns the string representation -func (s CreateDiskFromSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskFromSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskFromSnapshotInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - if s.SizeInGb == nil { - invalidParams.Add(request.NewErrParamRequired("SizeInGb")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateDiskFromSnapshotInput) SetAvailabilityZone(v string) *CreateDiskFromSnapshotInput { - s.AvailabilityZone = &v - return s -} - -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskFromSnapshotInput) SetDiskName(v string) *CreateDiskFromSnapshotInput { - s.DiskName = &v - return s -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *CreateDiskFromSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskFromSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *CreateDiskFromSnapshotInput) SetSizeInGb(v int64) *CreateDiskFromSnapshotInput { - s.SizeInGb = &v - return s -} - -type CreateDiskFromSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskFromSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskFromSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskFromSnapshotOutput) SetOperations(v []*Operation) *CreateDiskFromSnapshotOutput { - s.Operations = v - return s -} - -type CreateDiskInput struct { - _ struct{} `type:"structure"` - - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Choose the same Availability Zone as the Lightsail instance where you want - // to create the disk. - // - // Use the GetRegions operation to list the Availability Zones where Lightsail - // is currently available. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The size of the disk in GB (e.g., 32). - // - // SizeInGb is a required field - SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` -} - -// String returns the string representation -func (s CreateDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.SizeInGb == nil { - invalidParams.Add(request.NewErrParamRequired("SizeInGb")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateDiskInput) SetAvailabilityZone(v string) *CreateDiskInput { - s.AvailabilityZone = &v - return s -} - -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskInput) SetDiskName(v string) *CreateDiskInput { - s.DiskName = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *CreateDiskInput) SetSizeInGb(v int64) *CreateDiskInput { - s.SizeInGb = &v - return s -} - -type CreateDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskOutput) SetOperations(v []*Operation) *CreateDiskOutput { - s.Operations = v - return s -} - -type CreateDiskSnapshotInput struct { - _ struct{} `type:"structure"` - - // The unique name of the source disk (e.g., my-source-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The name of the destination disk snapshot (e.g., my-disk-snapshot) based - // on the source disk. - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateDiskSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskSnapshotInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskSnapshotInput) SetDiskName(v string) *CreateDiskSnapshotInput { - s.DiskName = &v - return s -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *CreateDiskSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -type CreateDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskSnapshotOutput) SetOperations(v []*Operation) *CreateDiskSnapshotOutput { - s.Operations = v - return s -} - -type CreateDomainEntryInput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the domain entry - // request. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - - // The domain name (e.g., example.com) for which you want to create the domain - // entry. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateDomainEntryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainEntryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainEntry sets the DomainEntry field's value. -func (s *CreateDomainEntryInput) SetDomainEntry(v *DomainEntry) *CreateDomainEntryInput { - s.DomainEntry = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *CreateDomainEntryInput) SetDomainName(v string) *CreateDomainEntryInput { - s.DomainName = &v - return s -} - -type CreateDomainEntryOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CreateDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainEntryOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *CreateDomainEntryOutput) SetOperation(v *Operation) *CreateDomainEntryOutput { - s.Operation = v - return s -} - -type CreateDomainInput struct { - _ struct{} `type:"structure"` - - // The domain name to manage (e.g., example.com). - // - // You cannot register a new domain name using Lightsail. You must register - // a domain name using Amazon Route 53 or another domain name registrar. If - // you have already registered your domain, you can enter its name in this parameter - // to manage the DNS records for that domain. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateDomainInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainName sets the DomainName field's value. -func (s *CreateDomainInput) SetDomainName(v string) *CreateDomainInput { - s.DomainName = &v - return s -} - -type CreateDomainOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the domain resource - // you created. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CreateDomainOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *CreateDomainOutput) SetOperation(v *Operation) *CreateDomainOutput { - s.Operation = v - return s -} - -type CreateInstanceSnapshotInput struct { - _ struct{} `type:"structure"` - - // The Lightsail instance on which to base your snapshot. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The name for your new snapshot. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateInstanceSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstanceSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstanceSnapshotInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *CreateInstanceSnapshotInput) SetInstanceName(v string) *CreateInstanceSnapshotInput { - s.InstanceName = &v - return s -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *CreateInstanceSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstanceSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -type CreateInstanceSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create instances snapshot request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateInstanceSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstanceSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateInstanceSnapshotOutput) SetOperations(v []*Operation) *CreateInstanceSnapshotOutput { - s.Operations = v - return s -} - -type CreateInstancesFromSnapshotInput struct { - _ struct{} `type:"structure"` - - // An object containing information about one or more disk mappings. - AttachedDiskMapping map[string][]*DiskMap `locationName:"attachedDiskMapping" type:"map"` - - // The Availability Zone where you want to create your instances. Use the following - // formatting: us-east-2a (case sensitive). You can get a list of availability - // zones by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) - // operation. Be sure to add the include availability zones parameter to your - // request. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). - // - // BundleId is a required field - BundleId *string `locationName:"bundleId" type:"string" required:"true"` - - // The names for your new instances. - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the instance snapshot on which you are basing your new instances. - // Use the get instance snapshots operation to return information about your - // existing snapshots. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` - - // The name for your key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` - - // You can create a launch script that configures a server with additional user - // data. For example, apt-get -y update. - // - // Depending on the machine image you choose, the command to get software on - // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu - // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide - // (http://lightsail.aws.amazon.com/ls/docs/getting-started/articles/pre-installed-apps). - UserData *string `locationName:"userData" type:"string"` -} - -// String returns the string representation -func (s CreateInstancesFromSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesFromSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstancesFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstancesFromSnapshotInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.BundleId == nil { - invalidParams.Add(request.NewErrParamRequired("BundleId")) - } - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAttachedDiskMapping sets the AttachedDiskMapping field's value. -func (s *CreateInstancesFromSnapshotInput) SetAttachedDiskMapping(v map[string][]*DiskMap) *CreateInstancesFromSnapshotInput { - s.AttachedDiskMapping = v - return s -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateInstancesFromSnapshotInput) SetAvailabilityZone(v string) *CreateInstancesFromSnapshotInput { - s.AvailabilityZone = &v - return s -} - -// SetBundleId sets the BundleId field's value. -func (s *CreateInstancesFromSnapshotInput) SetBundleId(v string) *CreateInstancesFromSnapshotInput { - s.BundleId = &v - return s -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *CreateInstancesFromSnapshotInput) SetInstanceNames(v []*string) *CreateInstancesFromSnapshotInput { - s.InstanceNames = v - return s -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *CreateInstancesFromSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstancesFromSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateInstancesFromSnapshotInput) SetKeyPairName(v string) *CreateInstancesFromSnapshotInput { - s.KeyPairName = &v - return s -} - -// SetUserData sets the UserData field's value. -func (s *CreateInstancesFromSnapshotInput) SetUserData(v string) *CreateInstancesFromSnapshotInput { - s.UserData = &v - return s -} - -type CreateInstancesFromSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create instances from snapshot request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateInstancesFromSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesFromSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateInstancesFromSnapshotOutput) SetOperations(v []*Operation) *CreateInstancesFromSnapshotOutput { - s.Operations = v - return s -} - -type CreateInstancesInput struct { - _ struct{} `type:"structure"` - - // The Availability Zone in which to create your instance. Use the following - // format: us-east-2a (case sensitive). You can get a list of availability zones - // by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) - // operation. Be sure to add the include availability zones parameter to your - // request. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The ID for a virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). - // Use the get blueprints operation to return a list of available images (or - // blueprints). - // - // BlueprintId is a required field - BlueprintId *string `locationName:"blueprintId" type:"string" required:"true"` - - // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). - // - // BundleId is a required field - BundleId *string `locationName:"bundleId" type:"string" required:"true"` - - // (Deprecated) The name for your custom image. - // - // In releases prior to June 12, 2017, this parameter was ignored by the API. - // It is now deprecated. - CustomImageName *string `locationName:"customImageName" deprecated:"true" type:"string"` - - // The names to use for your new Lightsail instances. Separate multiple values - // using quotation marks and commas, for example: ["MyFirstInstance","MySecondInstance"] - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of your key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` - - // A launch script you can create that configures a server with additional user - // data. For example, you might want to run apt-get -y update. - // - // Depending on the machine image you choose, the command to get software on - // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu - // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide - // (https://lightsail.aws.amazon.com/ls/docs/getting-started/article/compare-options-choose-lightsail-instance-image). - UserData *string `locationName:"userData" type:"string"` -} - -// String returns the string representation -func (s CreateInstancesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstancesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstancesInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.BlueprintId == nil { - invalidParams.Add(request.NewErrParamRequired("BlueprintId")) - } - if s.BundleId == nil { - invalidParams.Add(request.NewErrParamRequired("BundleId")) - } - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateInstancesInput) SetAvailabilityZone(v string) *CreateInstancesInput { - s.AvailabilityZone = &v - return s -} - -// SetBlueprintId sets the BlueprintId field's value. -func (s *CreateInstancesInput) SetBlueprintId(v string) *CreateInstancesInput { - s.BlueprintId = &v - return s -} - -// SetBundleId sets the BundleId field's value. -func (s *CreateInstancesInput) SetBundleId(v string) *CreateInstancesInput { - s.BundleId = &v - return s -} - -// SetCustomImageName sets the CustomImageName field's value. -func (s *CreateInstancesInput) SetCustomImageName(v string) *CreateInstancesInput { - s.CustomImageName = &v - return s -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *CreateInstancesInput) SetInstanceNames(v []*string) *CreateInstancesInput { - s.InstanceNames = v - return s -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateInstancesInput) SetKeyPairName(v string) *CreateInstancesInput { - s.KeyPairName = &v - return s -} - -// SetUserData sets the UserData field's value. -func (s *CreateInstancesInput) SetUserData(v string) *CreateInstancesInput { - s.UserData = &v - return s -} - -type CreateInstancesOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create instances request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateInstancesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateInstancesOutput) SetOperations(v []*Operation) *CreateInstancesOutput { - s.Operations = v - return s -} - -type CreateKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name for your new key pair. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateKeyPairInput) SetKeyPairName(v string) *CreateKeyPairInput { - s.KeyPairName = &v - return s -} - -type CreateKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the new key pair - // you just created. - KeyPair *KeyPair `locationName:"keyPair" type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create key pair request. - Operation *Operation `locationName:"operation" type:"structure"` - - // A base64-encoded RSA private key. - PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - - // A base64-encoded public key of the ssh-rsa type. - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` -} - -// String returns the string representation -func (s CreateKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateKeyPairOutput) GoString() string { - return s.String() -} - -// SetKeyPair sets the KeyPair field's value. -func (s *CreateKeyPairOutput) SetKeyPair(v *KeyPair) *CreateKeyPairOutput { - s.KeyPair = v - return s -} - -// SetOperation sets the Operation field's value. -func (s *CreateKeyPairOutput) SetOperation(v *Operation) *CreateKeyPairOutput { - s.Operation = v - return s -} - -// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. -func (s *CreateKeyPairOutput) SetPrivateKeyBase64(v string) *CreateKeyPairOutput { - s.PrivateKeyBase64 = &v - return s -} - -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *CreateKeyPairOutput) SetPublicKeyBase64(v string) *CreateKeyPairOutput { - s.PublicKeyBase64 = &v - return s -} - -type CreateLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // The optional alternative domains and subdomains to use with your SSL/TLS - // certificate (e.g., www.example.com, example.com, m.example.com, blog.example.com). - CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - - // The domain name with which your certificate is associated (e.g., example.com). - // - // If you specify certificateDomainName, then certificateName is required (and - // vice-versa). - CertificateDomainName *string `locationName:"certificateDomainName" type:"string"` - - // The name of the SSL/TLS certificate. - // - // If you specify certificateName, then certificateDomainName is required (and - // vice-versa). - CertificateName *string `locationName:"certificateName" type:"string"` - - // The path you provided to perform the load balancer health check. If you didn't - // specify a health check path, Lightsail uses the root path of your website - // (e.g., "/"). - // - // You may want to specify a custom health check path other than the root of - // your application if your home page loads slowly or has a lot of media or - // scripting on it. - HealthCheckPath *string `locationName:"healthCheckPath" type:"string"` - - // The instance port where you're creating your load balancer. - // - // InstancePort is a required field - InstancePort *int64 `locationName:"instancePort" type:"integer" required:"true"` - - // The name of your load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerInput"} - if s.InstancePort == nil { - invalidParams.Add(request.NewErrParamRequired("InstancePort")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. -func (s *CreateLoadBalancerInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerInput { - s.CertificateAlternativeNames = v - return s -} - -// SetCertificateDomainName sets the CertificateDomainName field's value. -func (s *CreateLoadBalancerInput) SetCertificateDomainName(v string) *CreateLoadBalancerInput { - s.CertificateDomainName = &v - return s -} - -// SetCertificateName sets the CertificateName field's value. -func (s *CreateLoadBalancerInput) SetCertificateName(v string) *CreateLoadBalancerInput { - s.CertificateName = &v - return s -} - -// SetHealthCheckPath sets the HealthCheckPath field's value. -func (s *CreateLoadBalancerInput) SetHealthCheckPath(v string) *CreateLoadBalancerInput { - s.HealthCheckPath = &v - return s -} - -// SetInstancePort sets the InstancePort field's value. -func (s *CreateLoadBalancerInput) SetInstancePort(v int64) *CreateLoadBalancerInput { - s.InstancePort = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *CreateLoadBalancerInput) SetLoadBalancerName(v string) *CreateLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type CreateLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateLoadBalancerOutput) SetOperations(v []*Operation) *CreateLoadBalancerOutput { - s.Operations = v - return s -} - -type CreateLoadBalancerTlsCertificateInput struct { - _ struct{} `type:"structure"` - - // An array of strings listing alternative domains and subdomains for your SSL/TLS - // certificate. Lightsail will de-dupe the names for you. You can have a maximum - // of 9 alternative names (in addition to the 1 primary domain). We do not support - // wildcards (e.g., *.example.com). - CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - - // The domain name (e.g., example.com) for your SSL/TLS certificate. - // - // CertificateDomainName is a required field - CertificateDomainName *string `locationName:"certificateDomainName" type:"string" required:"true"` - - // The SSL/TLS certificate name. - // - // You can have up to 10 certificates in your account at one time. Each Lightsail - // load balancer can have up to 2 certificates associated with it at one time. - // There is also an overall limit to the number of certificates that can be - // issue in a 365-day period. For more information, see Limits (http://docs.aws.amazon.com/acm/latest/userguide/acm-limits.html). - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // The load balancer name where you want to create the SSL/TLS certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateLoadBalancerTlsCertificateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerTlsCertificateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerTlsCertificateInput"} - if s.CertificateDomainName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateDomainName")) - } - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateAlternativeNames = v - return s -} - -// SetCertificateDomainName sets the CertificateDomainName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateDomainName(v string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateDomainName = &v - return s -} - -// SetCertificateName sets the CertificateName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateName(v string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateName = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *CreateLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -type CreateLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *CreateLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} - -type DeleteDiskInput struct { - _ struct{} `type:"structure"` - - // The unique name of the disk you want to delete (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *DeleteDiskInput) SetDiskName(v string) *DeleteDiskInput { - s.DiskName = &v - return s -} - -type DeleteDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteDiskOutput) SetOperations(v []*Operation) *DeleteDiskOutput { - s.Operations = v - return s -} - -type DeleteDiskSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the disk snapshot you want to delete (e.g., my-disk-snapshot). - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDiskSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *DeleteDiskSnapshotInput) SetDiskSnapshotName(v string) *DeleteDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -type DeleteDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteDiskSnapshotOutput) SetOperations(v []*Operation) *DeleteDiskSnapshotOutput { - s.Operations = v - return s -} - -type DeleteDomainEntryInput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your domain entries. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - - // The name of the domain entry to delete. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDomainEntryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainEntryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainEntry sets the DomainEntry field's value. -func (s *DeleteDomainEntryInput) SetDomainEntry(v *DomainEntry) *DeleteDomainEntryInput { - s.DomainEntry = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *DeleteDomainEntryInput) SetDomainName(v string) *DeleteDomainEntryInput { - s.DomainName = &v - return s -} - -type DeleteDomainEntryOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete domain entry request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s DeleteDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainEntryOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *DeleteDomainEntryOutput) SetOperation(v *Operation) *DeleteDomainEntryOutput { - s.Operation = v - return s -} - -type DeleteDomainInput struct { - _ struct{} `type:"structure"` - - // The specific domain name to delete. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDomainInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainName sets the DomainName field's value. -func (s *DeleteDomainInput) SetDomainName(v string) *DeleteDomainInput { - s.DomainName = &v - return s -} - -type DeleteDomainOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete domain request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s DeleteDomainOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *DeleteDomainOutput) SetOperation(v *Operation) *DeleteDomainOutput { - s.Operation = v - return s -} - -type DeleteInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to delete. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *DeleteInstanceInput) SetInstanceName(v string) *DeleteInstanceInput { - s.InstanceName = &v - return s -} - -type DeleteInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete instance request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteInstanceOutput) SetOperations(v []*Operation) *DeleteInstanceOutput { - s.Operations = v - return s -} - -type DeleteInstanceSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the snapshot to delete. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteInstanceSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceSnapshotInput"} - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *DeleteInstanceSnapshotInput) SetInstanceSnapshotName(v string) *DeleteInstanceSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -type DeleteInstanceSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete instance snapshot request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteInstanceSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteInstanceSnapshotOutput) SetOperations(v []*Operation) *DeleteInstanceSnapshotOutput { - s.Operations = v - return s -} - -type DeleteKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name of the key pair to delete. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *DeleteKeyPairInput) SetKeyPairName(v string) *DeleteKeyPairInput { - s.KeyPairName = &v - return s -} - -type DeleteKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete key pair request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s DeleteKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteKeyPairOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *DeleteKeyPairOutput) SetOperation(v *Operation) *DeleteKeyPairOutput { - s.Operation = v - return s -} - -type DeleteLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // The name of the load balancer you want to delete. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DeleteLoadBalancerInput) SetLoadBalancerName(v string) *DeleteLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type DeleteLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteLoadBalancerOutput) SetOperations(v []*Operation) *DeleteLoadBalancerOutput { - s.Operations = v - return s -} - -type DeleteLoadBalancerTlsCertificateInput struct { - _ struct{} `type:"structure"` - - // The SSL/TLS certificate name. - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // When true, forces the deletion of an SSL/TLS certificate. - // - // There can be two certificates associated with a Lightsail load balancer: - // the primary and the backup. The force parameter is required when the primary - // SSL/TLS certificate is in use by an instance attached to the load balancer. - Force *bool `locationName:"force" type:"boolean"` - - // The load balancer name. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteLoadBalancerTlsCertificateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerTlsCertificateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerTlsCertificateInput"} - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateName sets the CertificateName field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetCertificateName(v string) *DeleteLoadBalancerTlsCertificateInput { - s.CertificateName = &v - return s -} - -// SetForce sets the Force field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetForce(v bool) *DeleteLoadBalancerTlsCertificateInput { - s.Force = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *DeleteLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -type DeleteLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *DeleteLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} - -type DetachDiskInput struct { - _ struct{} `type:"structure"` - - // The unique name of the disk you want to detach from your instance (e.g., - // my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DetachDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *DetachDiskInput) SetDiskName(v string) *DetachDiskInput { - s.DiskName = &v - return s -} - -type DetachDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DetachDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DetachDiskOutput) SetOperations(v []*Operation) *DetachDiskOutput { - s.Operations = v - return s -} - -type DetachInstancesFromLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // An array of strings containing the names of the instances you want to detach - // from the load balancer. - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the Lightsail load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DetachInstancesFromLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachInstancesFromLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachInstancesFromLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachInstancesFromLoadBalancerInput"} - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *DetachInstancesFromLoadBalancerInput) SetInstanceNames(v []*string) *DetachInstancesFromLoadBalancerInput { - s.InstanceNames = v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DetachInstancesFromLoadBalancerInput) SetLoadBalancerName(v string) *DetachInstancesFromLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type DetachInstancesFromLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DetachInstancesFromLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachInstancesFromLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DetachInstancesFromLoadBalancerOutput) SetOperations(v []*Operation) *DetachInstancesFromLoadBalancerOutput { - s.Operations = v - return s -} - -type DetachStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP to detach from the instance. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DetachStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *DetachStaticIpInput) SetStaticIpName(v string) *DetachStaticIpInput { - s.StaticIpName = &v - return s -} - -type DetachStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // detach static IP request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DetachStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DetachStaticIpOutput) SetOperations(v []*Operation) *DetachStaticIpOutput { - s.Operations = v - return s -} - -// Describes a system disk or an block storage disk. -type Disk struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the disk. - Arn *string `locationName:"arn" type:"string"` - - // The resources to which the disk is attached. - AttachedTo *string `locationName:"attachedTo" type:"string"` - - // (Deprecated) The attachment state of the disk. - // - // In releases prior to November 14, 2017, this parameter returned attached - // for system disks in the API response. It is now deprecated, but still included - // in the response. Use isAttached instead. - AttachmentState *string `locationName:"attachmentState" deprecated:"true" type:"string"` - - // The date when the disk was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // (Deprecated) The number of GB in use by the disk. - // - // In releases prior to November 14, 2017, this parameter was not included in - // the API response. It is now deprecated. - GbInUse *int64 `locationName:"gbInUse" deprecated:"true" type:"integer"` - - // The input/output operations per second (IOPS) of the disk. - Iops *int64 `locationName:"iops" type:"integer"` - - // A Boolean value indicating whether the disk is attached. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // A Boolean value indicating whether this disk is a system disk (has an operating - // system loaded on it). - IsSystemDisk *bool `locationName:"isSystemDisk" type:"boolean"` - - // The AWS Region and Availability Zone where the disk is located. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The unique name of the disk. - Name *string `locationName:"name" type:"string"` - - // The disk path. - Path *string `locationName:"path" type:"string"` - - // The Lightsail resource type (e.g., Disk). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // Describes the status of the disk. - State *string `locationName:"state" type:"string" enum:"DiskState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s Disk) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Disk) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Disk) SetArn(v string) *Disk { - s.Arn = &v - return s -} - -// SetAttachedTo sets the AttachedTo field's value. -func (s *Disk) SetAttachedTo(v string) *Disk { - s.AttachedTo = &v - return s -} - -// SetAttachmentState sets the AttachmentState field's value. -func (s *Disk) SetAttachmentState(v string) *Disk { - s.AttachmentState = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Disk) SetCreatedAt(v time.Time) *Disk { - s.CreatedAt = &v - return s -} - -// SetGbInUse sets the GbInUse field's value. -func (s *Disk) SetGbInUse(v int64) *Disk { - s.GbInUse = &v - return s -} - -// SetIops sets the Iops field's value. -func (s *Disk) SetIops(v int64) *Disk { - s.Iops = &v - return s -} - -// SetIsAttached sets the IsAttached field's value. -func (s *Disk) SetIsAttached(v bool) *Disk { - s.IsAttached = &v - return s -} - -// SetIsSystemDisk sets the IsSystemDisk field's value. -func (s *Disk) SetIsSystemDisk(v bool) *Disk { - s.IsSystemDisk = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *Disk) SetLocation(v *ResourceLocation) *Disk { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *Disk) SetName(v string) *Disk { - s.Name = &v - return s -} - -// SetPath sets the Path field's value. -func (s *Disk) SetPath(v string) *Disk { - s.Path = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Disk) SetResourceType(v string) *Disk { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *Disk) SetSizeInGb(v int64) *Disk { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *Disk) SetState(v string) *Disk { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *Disk) SetSupportCode(v string) *Disk { - s.SupportCode = &v - return s -} - -// Describes a block storage disk mapping. -type DiskMap struct { - _ struct{} `type:"structure"` - - // The new disk name (e.g., my-new-disk). - NewDiskName *string `locationName:"newDiskName" type:"string"` - - // The original disk path exposed to the instance (for example, /dev/sdh). - OriginalDiskPath *string `locationName:"originalDiskPath" type:"string"` -} - -// String returns the string representation -func (s DiskMap) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DiskMap) GoString() string { - return s.String() -} - -// SetNewDiskName sets the NewDiskName field's value. -func (s *DiskMap) SetNewDiskName(v string) *DiskMap { - s.NewDiskName = &v - return s -} - -// SetOriginalDiskPath sets the OriginalDiskPath field's value. -func (s *DiskMap) SetOriginalDiskPath(v string) *DiskMap { - s.OriginalDiskPath = &v - return s -} - -// Describes a block storage disk snapshot. -type DiskSnapshot struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the disk snapshot. - Arn *string `locationName:"arn" type:"string"` - - // The date when the disk snapshot was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The Amazon Resource Name (ARN) of the source disk from which you are creating - // the disk snapshot. - FromDiskArn *string `locationName:"fromDiskArn" type:"string"` - - // The unique name of the source disk from which you are creating the disk snapshot. - FromDiskName *string `locationName:"fromDiskName" type:"string"` - - // The AWS Region and Availability Zone where the disk snapshot was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the disk snapshot (e.g., my-disk-snapshot). - Name *string `locationName:"name" type:"string"` - - // The progress of the disk snapshot operation. - Progress *string `locationName:"progress" type:"string"` - - // The Lightsail resource type (e.g., DiskSnapshot). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // The status of the disk snapshot operation. - State *string `locationName:"state" type:"string" enum:"DiskSnapshotState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s DiskSnapshot) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DiskSnapshot) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *DiskSnapshot) SetArn(v string) *DiskSnapshot { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *DiskSnapshot) SetCreatedAt(v time.Time) *DiskSnapshot { - s.CreatedAt = &v - return s -} - -// SetFromDiskArn sets the FromDiskArn field's value. -func (s *DiskSnapshot) SetFromDiskArn(v string) *DiskSnapshot { - s.FromDiskArn = &v - return s -} - -// SetFromDiskName sets the FromDiskName field's value. -func (s *DiskSnapshot) SetFromDiskName(v string) *DiskSnapshot { - s.FromDiskName = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *DiskSnapshot) SetLocation(v *ResourceLocation) *DiskSnapshot { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *DiskSnapshot) SetName(v string) *DiskSnapshot { - s.Name = &v - return s -} - -// SetProgress sets the Progress field's value. -func (s *DiskSnapshot) SetProgress(v string) *DiskSnapshot { - s.Progress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *DiskSnapshot) SetResourceType(v string) *DiskSnapshot { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *DiskSnapshot) SetSizeInGb(v int64) *DiskSnapshot { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *DiskSnapshot) SetState(v string) *DiskSnapshot { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *DiskSnapshot) SetSupportCode(v string) *DiskSnapshot { - s.SupportCode = &v - return s -} - -// Describes a domain where you are storing recordsets in Lightsail. -type Domain struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the domain recordset (e.g., arn:aws:lightsail:global:123456789101:Domain/824cede0-abc7-4f84-8dbc-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The date when the domain recordset was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // An array of key-value pairs containing information about the domain entries. - DomainEntries []*DomainEntry `locationName:"domainEntries" type:"list"` - - // The AWS Region and Availability Zones where the domain recordset was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the domain. - Name *string `locationName:"name" type:"string"` - - // The resource type. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s Domain) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Domain) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Domain) SetArn(v string) *Domain { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Domain) SetCreatedAt(v time.Time) *Domain { - s.CreatedAt = &v - return s -} - -// SetDomainEntries sets the DomainEntries field's value. -func (s *Domain) SetDomainEntries(v []*DomainEntry) *Domain { - s.DomainEntries = v - return s -} - -// SetLocation sets the Location field's value. -func (s *Domain) SetLocation(v *ResourceLocation) *Domain { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *Domain) SetName(v string) *Domain { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Domain) SetResourceType(v string) *Domain { - s.ResourceType = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *Domain) SetSupportCode(v string) *Domain { - s.SupportCode = &v - return s -} - -// Describes a domain recordset entry. -type DomainEntry struct { - _ struct{} `type:"structure"` - - // The ID of the domain recordset entry. - Id *string `locationName:"id" type:"string"` - - // When true, specifies whether the domain entry is an alias used by the Lightsail - // load balancer. You can include an alias (A type) record in your request, - // which points to a load balancer DNS name and routes traffic to your load - // balancer - IsAlias *bool `locationName:"isAlias" type:"boolean"` - - // The name of the domain. - Name *string `locationName:"name" type:"string"` - - // (Deprecated) The options for the domain entry. - // - // In releases prior to November 29, 2017, this parameter was not included in - // the API response. It is now deprecated. - Options map[string]*string `locationName:"options" deprecated:"true" type:"map"` - - // The target AWS name server (e.g., ns-111.awsdns-22.com.). - // - // For Lightsail load balancers, the value looks like ab1234c56789c6b86aba6fb203d443bc-123456789.us-east-2.elb.amazonaws.com. - // Be sure to also set isAlias to true when setting up an A record for a load - // balancer. - Target *string `locationName:"target" type:"string"` - - // The type of domain entry (e.g., SOA or NS). - Type *string `locationName:"type" type:"string"` -} - -// String returns the string representation -func (s DomainEntry) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DomainEntry) GoString() string { - return s.String() -} - -// SetId sets the Id field's value. -func (s *DomainEntry) SetId(v string) *DomainEntry { - s.Id = &v - return s -} - -// SetIsAlias sets the IsAlias field's value. -func (s *DomainEntry) SetIsAlias(v bool) *DomainEntry { - s.IsAlias = &v - return s -} - -// SetName sets the Name field's value. -func (s *DomainEntry) SetName(v string) *DomainEntry { - s.Name = &v - return s -} - -// SetOptions sets the Options field's value. -func (s *DomainEntry) SetOptions(v map[string]*string) *DomainEntry { - s.Options = v - return s -} - -// SetTarget sets the Target field's value. -func (s *DomainEntry) SetTarget(v string) *DomainEntry { - s.Target = &v - return s -} - -// SetType sets the Type field's value. -func (s *DomainEntry) SetType(v string) *DomainEntry { - s.Type = &v - return s -} - -type DownloadDefaultKeyPairInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DownloadDefaultKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DownloadDefaultKeyPairInput) GoString() string { - return s.String() -} - -type DownloadDefaultKeyPairOutput struct { - _ struct{} `type:"structure"` - - // A base64-encoded RSA private key. - PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - - // A base64-encoded public key of the ssh-rsa type. - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` -} - -// String returns the string representation -func (s DownloadDefaultKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DownloadDefaultKeyPairOutput) GoString() string { - return s.String() -} - -// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. -func (s *DownloadDefaultKeyPairOutput) SetPrivateKeyBase64(v string) *DownloadDefaultKeyPairOutput { - s.PrivateKeyBase64 = &v - return s -} - -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *DownloadDefaultKeyPairOutput) SetPublicKeyBase64(v string) *DownloadDefaultKeyPairOutput { - s.PublicKeyBase64 = &v - return s -} - -type GetActiveNamesInput struct { - _ struct{} `type:"structure"` - - // A token used for paginating results from your get active names request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetActiveNamesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetActiveNamesInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetActiveNamesInput) SetPageToken(v string) *GetActiveNamesInput { - s.PageToken = &v - return s -} - -type GetActiveNamesOutput struct { - _ struct{} `type:"structure"` - - // The list of active names returned by the get active names request. - ActiveNames []*string `locationName:"activeNames" type:"list"` - - // A token used for advancing to the next page of results from your get active - // names request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetActiveNamesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetActiveNamesOutput) GoString() string { - return s.String() -} - -// SetActiveNames sets the ActiveNames field's value. -func (s *GetActiveNamesOutput) SetActiveNames(v []*string) *GetActiveNamesOutput { - s.ActiveNames = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetActiveNamesOutput) SetNextPageToken(v string) *GetActiveNamesOutput { - s.NextPageToken = &v - return s -} - -type GetBlueprintsInput struct { - _ struct{} `type:"structure"` - - // A Boolean value indicating whether to include inactive results in your request. - IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - - // A token used for advancing to the next page of results from your get blueprints - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetBlueprintsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBlueprintsInput) GoString() string { - return s.String() -} - -// SetIncludeInactive sets the IncludeInactive field's value. -func (s *GetBlueprintsInput) SetIncludeInactive(v bool) *GetBlueprintsInput { - s.IncludeInactive = &v - return s -} - -// SetPageToken sets the PageToken field's value. -func (s *GetBlueprintsInput) SetPageToken(v string) *GetBlueprintsInput { - s.PageToken = &v - return s -} - -type GetBlueprintsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs that contains information about the available - // blueprints. - Blueprints []*Blueprint `locationName:"blueprints" type:"list"` - - // A token used for advancing to the next page of results from your get blueprints - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetBlueprintsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBlueprintsOutput) GoString() string { - return s.String() -} - -// SetBlueprints sets the Blueprints field's value. -func (s *GetBlueprintsOutput) SetBlueprints(v []*Blueprint) *GetBlueprintsOutput { - s.Blueprints = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetBlueprintsOutput) SetNextPageToken(v string) *GetBlueprintsOutput { - s.NextPageToken = &v - return s -} - -type GetBundlesInput struct { - _ struct{} `type:"structure"` - - // A Boolean value that indicates whether to include inactive bundle results - // in your request. - IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - - // A token used for advancing to the next page of results from your get bundles - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetBundlesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBundlesInput) GoString() string { - return s.String() -} - -// SetIncludeInactive sets the IncludeInactive field's value. -func (s *GetBundlesInput) SetIncludeInactive(v bool) *GetBundlesInput { - s.IncludeInactive = &v - return s -} - -// SetPageToken sets the PageToken field's value. -func (s *GetBundlesInput) SetPageToken(v string) *GetBundlesInput { - s.PageToken = &v - return s -} - -type GetBundlesOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs that contains information about the available - // bundles. - Bundles []*Bundle `locationName:"bundles" type:"list"` - - // A token used for advancing to the next page of results from your get active - // names request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetBundlesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBundlesOutput) GoString() string { - return s.String() -} - -// SetBundles sets the Bundles field's value. -func (s *GetBundlesOutput) SetBundles(v []*Bundle) *GetBundlesOutput { - s.Bundles = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetBundlesOutput) SetNextPageToken(v string) *GetBundlesOutput { - s.NextPageToken = &v - return s -} - -type GetDiskInput struct { - _ struct{} `type:"structure"` - - // The name of the disk (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *GetDiskInput) SetDiskName(v string) *GetDiskInput { - s.DiskName = &v - return s -} - -type GetDiskOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the disk. - Disk *Disk `locationName:"disk" type:"structure"` -} - -// String returns the string representation -func (s GetDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskOutput) GoString() string { - return s.String() -} - -// SetDisk sets the Disk field's value. -func (s *GetDiskOutput) SetDisk(v *Disk) *GetDiskOutput { - s.Disk = v - return s -} - -type GetDiskSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the disk snapshot (e.g., my-disk-snapshot). - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetDiskSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *GetDiskSnapshotInput) SetDiskSnapshotName(v string) *GetDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -type GetDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the disk snapshot. - DiskSnapshot *DiskSnapshot `locationName:"diskSnapshot" type:"structure"` -} - -// String returns the string representation -func (s GetDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetDiskSnapshot sets the DiskSnapshot field's value. -func (s *GetDiskSnapshotOutput) SetDiskSnapshot(v *DiskSnapshot) *GetDiskSnapshotOutput { - s.DiskSnapshot = v - return s -} - -type GetDiskSnapshotsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your GetDiskSnapshots - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetDiskSnapshotsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetDiskSnapshotsInput) SetPageToken(v string) *GetDiskSnapshotsInput { - s.PageToken = &v - return s -} - -type GetDiskSnapshotsOutput struct { - _ struct{} `type:"structure"` - - // An array of objects containing information about all block storage disk snapshots. - DiskSnapshots []*DiskSnapshot `locationName:"diskSnapshots" type:"list"` - - // A token used for advancing to the next page of results from your GetDiskSnapshots - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetDiskSnapshotsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotsOutput) GoString() string { - return s.String() -} - -// SetDiskSnapshots sets the DiskSnapshots field's value. -func (s *GetDiskSnapshotsOutput) SetDiskSnapshots(v []*DiskSnapshot) *GetDiskSnapshotsOutput { - s.DiskSnapshots = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDiskSnapshotsOutput) SetNextPageToken(v string) *GetDiskSnapshotsOutput { - s.NextPageToken = &v - return s -} - -type GetDisksInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your GetDisks - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetDisksInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDisksInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetDisksInput) SetPageToken(v string) *GetDisksInput { - s.PageToken = &v - return s -} - -type GetDisksOutput struct { - _ struct{} `type:"structure"` - - // An array of objects containing information about all block storage disks. - Disks []*Disk `locationName:"disks" type:"list"` - - // A token used for advancing to the next page of results from your GetDisks - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetDisksOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDisksOutput) GoString() string { - return s.String() -} - -// SetDisks sets the Disks field's value. -func (s *GetDisksOutput) SetDisks(v []*Disk) *GetDisksOutput { - s.Disks = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDisksOutput) SetNextPageToken(v string) *GetDisksOutput { - s.NextPageToken = &v - return s -} - -type GetDomainInput struct { - _ struct{} `type:"structure"` - - // The domain name for which your want to return information about. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetDomainInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainName sets the DomainName field's value. -func (s *GetDomainInput) SetDomainName(v string) *GetDomainInput { - s.DomainName = &v - return s -} - -type GetDomainOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your get domain - // request. - Domain *Domain `locationName:"domain" type:"structure"` -} - -// String returns the string representation -func (s GetDomainOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainOutput) GoString() string { - return s.String() -} - -// SetDomain sets the Domain field's value. -func (s *GetDomainOutput) SetDomain(v *Domain) *GetDomainOutput { - s.Domain = v - return s -} - -type GetDomainsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get domains - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetDomainsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetDomainsInput) SetPageToken(v string) *GetDomainsInput { - s.PageToken = &v - return s -} - -type GetDomainsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about each of the domain - // entries in the user's account. - Domains []*Domain `locationName:"domains" type:"list"` - - // A token used for advancing to the next page of results from your get active - // names request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetDomainsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainsOutput) GoString() string { - return s.String() -} - -// SetDomains sets the Domains field's value. -func (s *GetDomainsOutput) SetDomains(v []*Domain) *GetDomainsOutput { - s.Domains = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDomainsOutput) SetNextPageToken(v string) *GetDomainsOutput { - s.NextPageToken = &v - return s -} - -type GetInstanceAccessDetailsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to access. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The protocol to use to connect to your instance. Defaults to ssh. - Protocol *string `locationName:"protocol" type:"string" enum:"InstanceAccessProtocol"` -} - -// String returns the string representation -func (s GetInstanceAccessDetailsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceAccessDetailsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceAccessDetailsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceAccessDetailsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceAccessDetailsInput) SetInstanceName(v string) *GetInstanceAccessDetailsInput { - s.InstanceName = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *GetInstanceAccessDetailsInput) SetProtocol(v string) *GetInstanceAccessDetailsInput { - s.Protocol = &v - return s -} - -type GetInstanceAccessDetailsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about a get instance access - // request. - AccessDetails *InstanceAccessDetails `locationName:"accessDetails" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceAccessDetailsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceAccessDetailsOutput) GoString() string { - return s.String() -} - -// SetAccessDetails sets the AccessDetails field's value. -func (s *GetInstanceAccessDetailsOutput) SetAccessDetails(v *InstanceAccessDetails) *GetInstanceAccessDetailsOutput { - s.AccessDetails = v - return s -} - -type GetInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceInput) SetInstanceName(v string) *GetInstanceInput { - s.InstanceName = &v - return s -} - -type GetInstanceMetricDataInput struct { - _ struct{} `type:"structure"` - - // The end time of the time period. - // - // EndTime is a required field - EndTime *time.Time `locationName:"endTime" type:"timestamp" required:"true"` - - // The name of the instance for which you want to get metrics data. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The metric name to get data about. - // - // MetricName is a required field - MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"InstanceMetricName"` - - // The time period for which you are requesting data. - // - // Period is a required field - Period *int64 `locationName:"period" min:"60" type:"integer" required:"true"` - - // The start time of the time period. - // - // StartTime is a required field - StartTime *time.Time `locationName:"startTime" type:"timestamp" required:"true"` - - // The instance statistics. - // - // Statistics is a required field - Statistics []*string `locationName:"statistics" type:"list" required:"true"` - - // The unit. The list of valid values is below. - // - // Unit is a required field - Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` -} - -// String returns the string representation -func (s GetInstanceMetricDataInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceMetricDataInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceMetricDataInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceMetricDataInput"} - if s.EndTime == nil { - invalidParams.Add(request.NewErrParamRequired("EndTime")) - } - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.MetricName == nil { - invalidParams.Add(request.NewErrParamRequired("MetricName")) - } - if s.Period == nil { - invalidParams.Add(request.NewErrParamRequired("Period")) - } - if s.Period != nil && *s.Period < 60 { - invalidParams.Add(request.NewErrParamMinValue("Period", 60)) - } - if s.StartTime == nil { - invalidParams.Add(request.NewErrParamRequired("StartTime")) - } - if s.Statistics == nil { - invalidParams.Add(request.NewErrParamRequired("Statistics")) - } - if s.Unit == nil { - invalidParams.Add(request.NewErrParamRequired("Unit")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *GetInstanceMetricDataInput) SetEndTime(v time.Time) *GetInstanceMetricDataInput { - s.EndTime = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceMetricDataInput) SetInstanceName(v string) *GetInstanceMetricDataInput { - s.InstanceName = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetInstanceMetricDataInput) SetMetricName(v string) *GetInstanceMetricDataInput { - s.MetricName = &v - return s -} - -// SetPeriod sets the Period field's value. -func (s *GetInstanceMetricDataInput) SetPeriod(v int64) *GetInstanceMetricDataInput { - s.Period = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *GetInstanceMetricDataInput) SetStartTime(v time.Time) *GetInstanceMetricDataInput { - s.StartTime = &v - return s -} - -// SetStatistics sets the Statistics field's value. -func (s *GetInstanceMetricDataInput) SetStatistics(v []*string) *GetInstanceMetricDataInput { - s.Statistics = v - return s -} - -// SetUnit sets the Unit field's value. -func (s *GetInstanceMetricDataInput) SetUnit(v string) *GetInstanceMetricDataInput { - s.Unit = &v - return s -} - -type GetInstanceMetricDataOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get instance metric data request. - MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - - // The metric name to return data for. - MetricName *string `locationName:"metricName" type:"string" enum:"InstanceMetricName"` -} - -// String returns the string representation -func (s GetInstanceMetricDataOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceMetricDataOutput) GoString() string { - return s.String() -} - -// SetMetricData sets the MetricData field's value. -func (s *GetInstanceMetricDataOutput) SetMetricData(v []*MetricDatapoint) *GetInstanceMetricDataOutput { - s.MetricData = v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetInstanceMetricDataOutput) SetMetricName(v string) *GetInstanceMetricDataOutput { - s.MetricName = &v - return s -} - -type GetInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the specified instance. - Instance *Instance `locationName:"instance" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceOutput) GoString() string { - return s.String() -} - -// SetInstance sets the Instance field's value. -func (s *GetInstanceOutput) SetInstance(v *Instance) *GetInstanceOutput { - s.Instance = v - return s -} - -type GetInstancePortStatesInput struct { - _ struct{} `type:"structure"` - - // The name of the instance. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstancePortStatesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancePortStatesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstancePortStatesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstancePortStatesInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstancePortStatesInput) SetInstanceName(v string) *GetInstancePortStatesInput { - s.InstanceName = &v - return s -} - -type GetInstancePortStatesOutput struct { - _ struct{} `type:"structure"` - - // Information about the port states resulting from your request. - PortStates []*InstancePortState `locationName:"portStates" type:"list"` -} - -// String returns the string representation -func (s GetInstancePortStatesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancePortStatesOutput) GoString() string { - return s.String() -} - -// SetPortStates sets the PortStates field's value. -func (s *GetInstancePortStatesOutput) SetPortStates(v []*InstancePortState) *GetInstancePortStatesOutput { - s.PortStates = v - return s -} - -type GetInstanceSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the snapshot for which you are requesting information. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstanceSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceSnapshotInput"} - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *GetInstanceSnapshotInput) SetInstanceSnapshotName(v string) *GetInstanceSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -type GetInstanceSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get instance snapshot request. - InstanceSnapshot *InstanceSnapshot `locationName:"instanceSnapshot" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotOutput) GoString() string { - return s.String() -} - -// SetInstanceSnapshot sets the InstanceSnapshot field's value. -func (s *GetInstanceSnapshotOutput) SetInstanceSnapshot(v *InstanceSnapshot) *GetInstanceSnapshotOutput { - s.InstanceSnapshot = v - return s -} - -type GetInstanceSnapshotsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get instance - // snapshots request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstanceSnapshotsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetInstanceSnapshotsInput) SetPageToken(v string) *GetInstanceSnapshotsInput { - s.PageToken = &v - return s -} - -type GetInstanceSnapshotsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get instance snapshots request. - InstanceSnapshots []*InstanceSnapshot `locationName:"instanceSnapshots" type:"list"` - - // A token used for advancing to the next page of results from your get instance - // snapshots request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstanceSnapshotsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotsOutput) GoString() string { - return s.String() -} - -// SetInstanceSnapshots sets the InstanceSnapshots field's value. -func (s *GetInstanceSnapshotsOutput) SetInstanceSnapshots(v []*InstanceSnapshot) *GetInstanceSnapshotsOutput { - s.InstanceSnapshots = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetInstanceSnapshotsOutput) SetNextPageToken(v string) *GetInstanceSnapshotsOutput { - s.NextPageToken = &v - return s -} - -type GetInstanceStateInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to get state information about. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstanceStateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceStateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceStateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceStateInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceStateInput) SetInstanceName(v string) *GetInstanceStateInput { - s.InstanceName = &v - return s -} - -type GetInstanceStateOutput struct { - _ struct{} `type:"structure"` - - // The state of the instance. - State *InstanceState `locationName:"state" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceStateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceStateOutput) GoString() string { - return s.String() -} - -// SetState sets the State field's value. -func (s *GetInstanceStateOutput) SetState(v *InstanceState) *GetInstanceStateOutput { - s.State = v - return s -} - -type GetInstancesInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get instances - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstancesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancesInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetInstancesInput) SetPageToken(v string) *GetInstancesInput { - s.PageToken = &v - return s -} - -type GetInstancesOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your instances. - Instances []*Instance `locationName:"instances" type:"list"` - - // A token used for advancing to the next page of results from your get instances - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstancesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancesOutput) GoString() string { - return s.String() -} - -// SetInstances sets the Instances field's value. -func (s *GetInstancesOutput) SetInstances(v []*Instance) *GetInstancesOutput { - s.Instances = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetInstancesOutput) SetNextPageToken(v string) *GetInstancesOutput { - s.NextPageToken = &v - return s -} - -type GetKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name of the key pair for which you are requesting information. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *GetKeyPairInput) SetKeyPairName(v string) *GetKeyPairInput { - s.KeyPairName = &v - return s -} - -type GetKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the key pair. - KeyPair *KeyPair `locationName:"keyPair" type:"structure"` -} - -// String returns the string representation -func (s GetKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairOutput) GoString() string { - return s.String() -} - -// SetKeyPair sets the KeyPair field's value. -func (s *GetKeyPairOutput) SetKeyPair(v *KeyPair) *GetKeyPairOutput { - s.KeyPair = v - return s -} - -type GetKeyPairsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get key - // pairs request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetKeyPairsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetKeyPairsInput) SetPageToken(v string) *GetKeyPairsInput { - s.PageToken = &v - return s -} - -type GetKeyPairsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the key pairs. - KeyPairs []*KeyPair `locationName:"keyPairs" type:"list"` - - // A token used for advancing to the next page of results from your get key - // pairs request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetKeyPairsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairsOutput) GoString() string { - return s.String() -} - -// SetKeyPairs sets the KeyPairs field's value. -func (s *GetKeyPairsOutput) SetKeyPairs(v []*KeyPair) *GetKeyPairsOutput { - s.KeyPairs = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetKeyPairsOutput) SetNextPageToken(v string) *GetKeyPairsOutput { - s.NextPageToken = &v - return s -} - -type GetLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // The name of the load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLoadBalancerInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *GetLoadBalancerInput) SetLoadBalancerName(v string) *GetLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type GetLoadBalancerMetricDataInput struct { - _ struct{} `type:"structure"` - - // The end time of the period. - // - // EndTime is a required field - EndTime *time.Time `locationName:"endTime" type:"timestamp" required:"true"` - - // The name of the load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` - - // The metric about which you want to return information. Valid values are listed - // below, along with the most useful statistics to include in your request. - // - // * ClientTLSNegotiationErrorCount - The number of TLS connections initiated - // by the client that did not establish a session with the load balancer. - // Possible causes include a mismatch of ciphers or protocols. - // - // Statistics: The most useful statistic is Sum. - // - // * HealthyHostCount - The number of target instances that are considered - // healthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * UnhealthyHostCount - The number of target instances that are considered - // unhealthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * HTTPCode_LB_4XX_Count - The number of HTTP 4XX client error codes that - // originate from the load balancer. Client errors are generated when requests - // are malformed or incomplete. These requests have not been received by - // the target instance. This count does not include any response codes generated - // by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_LB_5XX_Count - The number of HTTP 5XX server error codes that - // originate from the load balancer. This count does not include any response - // codes generated by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. Note that Minimum, Maximum, and Average all - // return 1. - // - // * HTTPCode_Instance_2XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_3XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_4XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_5XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * InstanceResponseTime - The time elapsed, in seconds, after the request - // leaves the load balancer until a response from the target instance is - // received. - // - // Statistics: The most useful statistic is Average. - // - // * RejectedConnectionCount - The number of connections that were rejected - // because the load balancer had reached its maximum number of connections. - // - // Statistics: The most useful statistic is Sum. - // - // * RequestCount - The number of requests processed over IPv4. This count - // includes only the requests with a response generated by a target instance - // of the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // MetricName is a required field - MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"LoadBalancerMetricName"` - - // The time period duration for your health data request. - // - // Period is a required field - Period *int64 `locationName:"period" min:"60" type:"integer" required:"true"` - - // The start time of the period. - // - // StartTime is a required field - StartTime *time.Time `locationName:"startTime" type:"timestamp" required:"true"` - - // An array of statistics that you want to request metrics for. Valid values - // are listed below. - // - // * SampleCount - The count (number) of data points used for the statistical - // calculation. - // - // * Average - The value of Sum / SampleCount during the specified period. - // By comparing this statistic with the Minimum and Maximum, you can determine - // the full scope of a metric and how close the average use is to the Minimum - // and Maximum. This comparison helps you to know when to increase or decrease - // your resources as needed. - // - // * Sum - All values submitted for the matching metric added together. This - // statistic can be useful for determining the total volume of a metric. - // - // * Minimum - The lowest value observed during the specified period. You - // can use this value to determine low volumes of activity for your application. - // - // * Maximum - The highest value observed during the specified period. You - // can use this value to determine high volumes of activity for your application. - // - // Statistics is a required field - Statistics []*string `locationName:"statistics" type:"list" required:"true"` - - // The unit for the time period request. Valid values are listed below. - // - // Unit is a required field - Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` -} - -// String returns the string representation -func (s GetLoadBalancerMetricDataInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerMetricDataInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLoadBalancerMetricDataInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLoadBalancerMetricDataInput"} - if s.EndTime == nil { - invalidParams.Add(request.NewErrParamRequired("EndTime")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - if s.MetricName == nil { - invalidParams.Add(request.NewErrParamRequired("MetricName")) - } - if s.Period == nil { - invalidParams.Add(request.NewErrParamRequired("Period")) - } - if s.Period != nil && *s.Period < 60 { - invalidParams.Add(request.NewErrParamMinValue("Period", 60)) - } - if s.StartTime == nil { - invalidParams.Add(request.NewErrParamRequired("StartTime")) - } - if s.Statistics == nil { - invalidParams.Add(request.NewErrParamRequired("Statistics")) - } - if s.Unit == nil { - invalidParams.Add(request.NewErrParamRequired("Unit")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *GetLoadBalancerMetricDataInput) SetEndTime(v time.Time) *GetLoadBalancerMetricDataInput { - s.EndTime = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *GetLoadBalancerMetricDataInput) SetLoadBalancerName(v string) *GetLoadBalancerMetricDataInput { - s.LoadBalancerName = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetLoadBalancerMetricDataInput) SetMetricName(v string) *GetLoadBalancerMetricDataInput { - s.MetricName = &v - return s -} - -// SetPeriod sets the Period field's value. -func (s *GetLoadBalancerMetricDataInput) SetPeriod(v int64) *GetLoadBalancerMetricDataInput { - s.Period = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *GetLoadBalancerMetricDataInput) SetStartTime(v time.Time) *GetLoadBalancerMetricDataInput { - s.StartTime = &v - return s -} - -// SetStatistics sets the Statistics field's value. -func (s *GetLoadBalancerMetricDataInput) SetStatistics(v []*string) *GetLoadBalancerMetricDataInput { - s.Statistics = v - return s -} - -// SetUnit sets the Unit field's value. -func (s *GetLoadBalancerMetricDataInput) SetUnit(v string) *GetLoadBalancerMetricDataInput { - s.Unit = &v - return s -} - -type GetLoadBalancerMetricDataOutput struct { - _ struct{} `type:"structure"` - - // An array of metric datapoint objects. - MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - - // The metric about which you are receiving information. Valid values are listed - // below, along with the most useful statistics to include in your request. - // - // * ClientTLSNegotiationErrorCount - The number of TLS connections initiated - // by the client that did not establish a session with the load balancer. - // Possible causes include a mismatch of ciphers or protocols. - // - // Statistics: The most useful statistic is Sum. - // - // * HealthyHostCount - The number of target instances that are considered - // healthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * UnhealthyHostCount - The number of target instances that are considered - // unhealthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * HTTPCode_LB_4XX_Count - The number of HTTP 4XX client error codes that - // originate from the load balancer. Client errors are generated when requests - // are malformed or incomplete. These requests have not been received by - // the target instance. This count does not include any response codes generated - // by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_LB_5XX_Count - The number of HTTP 5XX server error codes that - // originate from the load balancer. This count does not include any response - // codes generated by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. Note that Minimum, Maximum, and Average all - // return 1. - // - // * HTTPCode_Instance_2XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_3XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_4XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_5XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * InstanceResponseTime - The time elapsed, in seconds, after the request - // leaves the load balancer until a response from the target instance is - // received. - // - // Statistics: The most useful statistic is Average. - // - // * RejectedConnectionCount - The number of connections that were rejected - // because the load balancer had reached its maximum number of connections. - // - // Statistics: The most useful statistic is Sum. - // - // * RequestCount - The number of requests processed over IPv4. This count - // includes only the requests with a response generated by a target instance - // of the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - MetricName *string `locationName:"metricName" type:"string" enum:"LoadBalancerMetricName"` -} - -// String returns the string representation -func (s GetLoadBalancerMetricDataOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerMetricDataOutput) GoString() string { - return s.String() -} - -// SetMetricData sets the MetricData field's value. -func (s *GetLoadBalancerMetricDataOutput) SetMetricData(v []*MetricDatapoint) *GetLoadBalancerMetricDataOutput { - s.MetricData = v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetLoadBalancerMetricDataOutput) SetMetricName(v string) *GetLoadBalancerMetricDataOutput { - s.MetricName = &v - return s -} - -type GetLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about your load balancer. - LoadBalancer *LoadBalancer `locationName:"loadBalancer" type:"structure"` -} - -// String returns the string representation -func (s GetLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetLoadBalancer sets the LoadBalancer field's value. -func (s *GetLoadBalancerOutput) SetLoadBalancer(v *LoadBalancer) *GetLoadBalancerOutput { - s.LoadBalancer = v - return s -} - -type GetLoadBalancerTlsCertificatesInput struct { - _ struct{} `type:"structure"` - - // The name of the load balancer you associated with your SSL/TLS certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetLoadBalancerTlsCertificatesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerTlsCertificatesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLoadBalancerTlsCertificatesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLoadBalancerTlsCertificatesInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *GetLoadBalancerTlsCertificatesInput) SetLoadBalancerName(v string) *GetLoadBalancerTlsCertificatesInput { - s.LoadBalancerName = &v - return s -} - -type GetLoadBalancerTlsCertificatesOutput struct { - _ struct{} `type:"structure"` - - // An array of LoadBalancerTlsCertificate objects describing your SSL/TLS certificates. - TlsCertificates []*LoadBalancerTlsCertificate `locationName:"tlsCertificates" type:"list"` -} - -// String returns the string representation -func (s GetLoadBalancerTlsCertificatesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerTlsCertificatesOutput) GoString() string { - return s.String() -} - -// SetTlsCertificates sets the TlsCertificates field's value. -func (s *GetLoadBalancerTlsCertificatesOutput) SetTlsCertificates(v []*LoadBalancerTlsCertificate) *GetLoadBalancerTlsCertificatesOutput { - s.TlsCertificates = v - return s -} - -type GetLoadBalancersInput struct { - _ struct{} `type:"structure"` - - // A token used for paginating the results from your GetLoadBalancers request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetLoadBalancersInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancersInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetLoadBalancersInput) SetPageToken(v string) *GetLoadBalancersInput { - s.PageToken = &v - return s -} - -type GetLoadBalancersOutput struct { - _ struct{} `type:"structure"` - - // An array of LoadBalancer objects describing your load balancers. - LoadBalancers []*LoadBalancer `locationName:"loadBalancers" type:"list"` - - // A token used for advancing to the next page of results from your GetLoadBalancers - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetLoadBalancersOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancersOutput) GoString() string { - return s.String() -} - -// SetLoadBalancers sets the LoadBalancers field's value. -func (s *GetLoadBalancersOutput) SetLoadBalancers(v []*LoadBalancer) *GetLoadBalancersOutput { - s.LoadBalancers = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetLoadBalancersOutput) SetNextPageToken(v string) *GetLoadBalancersOutput { - s.NextPageToken = &v - return s -} - -type GetOperationInput struct { - _ struct{} `type:"structure"` - - // A GUID used to identify the operation. - // - // OperationId is a required field - OperationId *string `locationName:"operationId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetOperationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetOperationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetOperationInput"} - if s.OperationId == nil { - invalidParams.Add(request.NewErrParamRequired("OperationId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetOperationId sets the OperationId field's value. -func (s *GetOperationInput) SetOperationId(v string) *GetOperationInput { - s.OperationId = &v - return s -} - -type GetOperationOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get operation request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s GetOperationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *GetOperationOutput) SetOperation(v *Operation) *GetOperationOutput { - s.Operation = v - return s -} - -type GetOperationsForResourceInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get operations - // for resource request. - PageToken *string `locationName:"pageToken" type:"string"` - - // The name of the resource for which you are requesting information. - // - // ResourceName is a required field - ResourceName *string `locationName:"resourceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetOperationsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetOperationsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetOperationsForResourceInput"} - if s.ResourceName == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPageToken sets the PageToken field's value. -func (s *GetOperationsForResourceInput) SetPageToken(v string) *GetOperationsForResourceInput { - s.PageToken = &v - return s -} - -// SetResourceName sets the ResourceName field's value. -func (s *GetOperationsForResourceInput) SetResourceName(v string) *GetOperationsForResourceInput { - s.ResourceName = &v - return s -} - -type GetOperationsForResourceOutput struct { - _ struct{} `type:"structure"` - - // (Deprecated) Returns the number of pages of results that remain. - // - // In releases prior to June 12, 2017, this parameter returned null by the API. - // It is now deprecated, and the API returns the nextPageToken parameter instead. - NextPageCount *string `locationName:"nextPageCount" deprecated:"true" type:"string"` - - // An identifier that was returned from the previous call to this operation, - // which can be used to return the next set of items in the list. - NextPageToken *string `locationName:"nextPageToken" type:"string"` - - // An array of key-value pairs containing information about the results of your - // get operations for resource request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s GetOperationsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsForResourceOutput) GoString() string { - return s.String() -} - -// SetNextPageCount sets the NextPageCount field's value. -func (s *GetOperationsForResourceOutput) SetNextPageCount(v string) *GetOperationsForResourceOutput { - s.NextPageCount = &v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetOperationsForResourceOutput) SetNextPageToken(v string) *GetOperationsForResourceOutput { - s.NextPageToken = &v - return s -} - -// SetOperations sets the Operations field's value. -func (s *GetOperationsForResourceOutput) SetOperations(v []*Operation) *GetOperationsForResourceOutput { - s.Operations = v - return s -} - -type GetOperationsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get operations - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetOperationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetOperationsInput) SetPageToken(v string) *GetOperationsInput { - s.PageToken = &v - return s -} - -type GetOperationsOutput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get operations - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` - - // An array of key-value pairs containing information about the results of your - // get operations request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s GetOperationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsOutput) GoString() string { - return s.String() -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetOperationsOutput) SetNextPageToken(v string) *GetOperationsOutput { - s.NextPageToken = &v - return s -} - -// SetOperations sets the Operations field's value. -func (s *GetOperationsOutput) SetOperations(v []*Operation) *GetOperationsOutput { - s.Operations = v - return s -} - -type GetRegionsInput struct { - _ struct{} `type:"structure"` - - // A Boolean value indicating whether to also include Availability Zones in - // your get regions request. Availability Zones are indicated with a letter: - // e.g., us-east-2a. - IncludeAvailabilityZones *bool `locationName:"includeAvailabilityZones" type:"boolean"` -} - -// String returns the string representation -func (s GetRegionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetRegionsInput) GoString() string { - return s.String() -} - -// SetIncludeAvailabilityZones sets the IncludeAvailabilityZones field's value. -func (s *GetRegionsInput) SetIncludeAvailabilityZones(v bool) *GetRegionsInput { - s.IncludeAvailabilityZones = &v - return s -} - -type GetRegionsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your get regions - // request. - Regions []*Region `locationName:"regions" type:"list"` -} - -// String returns the string representation -func (s GetRegionsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetRegionsOutput) GoString() string { - return s.String() -} - -// SetRegions sets the Regions field's value. -func (s *GetRegionsOutput) SetRegions(v []*Region) *GetRegionsOutput { - s.Regions = v - return s -} - -type GetStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP in Lightsail. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *GetStaticIpInput) SetStaticIpName(v string) *GetStaticIpInput { - s.StaticIpName = &v - return s -} - -type GetStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the requested static - // IP. - StaticIp *StaticIp `locationName:"staticIp" type:"structure"` -} - -// String returns the string representation -func (s GetStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpOutput) GoString() string { - return s.String() -} - -// SetStaticIp sets the StaticIp field's value. -func (s *GetStaticIpOutput) SetStaticIp(v *StaticIp) *GetStaticIpOutput { - s.StaticIp = v - return s -} - -type GetStaticIpsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get static - // IPs request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetStaticIpsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetStaticIpsInput) SetPageToken(v string) *GetStaticIpsInput { - s.PageToken = &v - return s -} - -type GetStaticIpsOutput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get static - // IPs request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` - - // An array of key-value pairs containing information about your get static - // IPs request. - StaticIps []*StaticIp `locationName:"staticIps" type:"list"` -} - -// String returns the string representation -func (s GetStaticIpsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpsOutput) GoString() string { - return s.String() -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetStaticIpsOutput) SetNextPageToken(v string) *GetStaticIpsOutput { - s.NextPageToken = &v - return s -} - -// SetStaticIps sets the StaticIps field's value. -func (s *GetStaticIpsOutput) SetStaticIps(v []*StaticIp) *GetStaticIpsOutput { - s.StaticIps = v - return s -} - -type ImportKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name of the key pair for which you want to import the public key. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` - - // A base64-encoded public key of the ssh-rsa type. - // - // PublicKeyBase64 is a required field - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string" required:"true"` -} - -// String returns the string representation -func (s ImportKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ImportKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ImportKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ImportKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - if s.PublicKeyBase64 == nil { - invalidParams.Add(request.NewErrParamRequired("PublicKeyBase64")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *ImportKeyPairInput) SetKeyPairName(v string) *ImportKeyPairInput { - s.KeyPairName = &v - return s -} - -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *ImportKeyPairInput) SetPublicKeyBase64(v string) *ImportKeyPairInput { - s.PublicKeyBase64 = &v - return s -} - -type ImportKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s ImportKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ImportKeyPairOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *ImportKeyPairOutput) SetOperation(v *Operation) *ImportKeyPairOutput { - s.Operation = v - return s -} - -// Describes an instance (a virtual private server). -type Instance struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the instance (e.g., arn:aws:lightsail:us-east-2:123456789101:Instance/244ad76f-8aad-4741-809f-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The blueprint ID (e.g., os_amlinux_2016_03). - BlueprintId *string `locationName:"blueprintId" type:"string"` - - // The friendly name of the blueprint (e.g., Amazon Linux). - BlueprintName *string `locationName:"blueprintName" type:"string"` - - // The bundle for the instance (e.g., micro_1_0). - BundleId *string `locationName:"bundleId" type:"string"` - - // The timestamp when the instance was created (e.g., 1479734909.17). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The size of the vCPU and the amount of RAM for the instance. - Hardware *InstanceHardware `locationName:"hardware" type:"structure"` - - // The IPv6 address of the instance. - Ipv6Address *string `locationName:"ipv6Address" type:"string"` - - // A Boolean value indicating whether this instance has a static IP assigned - // to it. - IsStaticIp *bool `locationName:"isStaticIp" type:"boolean"` - - // The region name and availability zone where the instance is located. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name the user gave the instance (e.g., Amazon_Linux-1GB-Ohio-1). - Name *string `locationName:"name" type:"string"` - - // Information about the public ports and monthly data transfer rates for the - // instance. - Networking *InstanceNetworking `locationName:"networking" type:"structure"` - - // The private IP address of the instance. - PrivateIpAddress *string `locationName:"privateIpAddress" type:"string"` - - // The public IP address of the instance. - PublicIpAddress *string `locationName:"publicIpAddress" type:"string"` - - // The type of resource (usually Instance). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The name of the SSH key being used to connect to the instance (e.g., LightsailDefaultKeyPair). - SshKeyName *string `locationName:"sshKeyName" type:"string"` - - // The status code and the state (e.g., running) for the instance. - State *InstanceState `locationName:"state" type:"structure"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` - - // The user name for connecting to the instance (e.g., ec2-user). - Username *string `locationName:"username" type:"string"` -} - -// String returns the string representation -func (s Instance) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Instance) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Instance) SetArn(v string) *Instance { - s.Arn = &v - return s -} - -// SetBlueprintId sets the BlueprintId field's value. -func (s *Instance) SetBlueprintId(v string) *Instance { - s.BlueprintId = &v - return s -} - -// SetBlueprintName sets the BlueprintName field's value. -func (s *Instance) SetBlueprintName(v string) *Instance { - s.BlueprintName = &v - return s -} - -// SetBundleId sets the BundleId field's value. -func (s *Instance) SetBundleId(v string) *Instance { - s.BundleId = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Instance) SetCreatedAt(v time.Time) *Instance { - s.CreatedAt = &v - return s -} - -// SetHardware sets the Hardware field's value. -func (s *Instance) SetHardware(v *InstanceHardware) *Instance { - s.Hardware = v - return s -} - -// SetIpv6Address sets the Ipv6Address field's value. -func (s *Instance) SetIpv6Address(v string) *Instance { - s.Ipv6Address = &v - return s -} - -// SetIsStaticIp sets the IsStaticIp field's value. -func (s *Instance) SetIsStaticIp(v bool) *Instance { - s.IsStaticIp = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *Instance) SetLocation(v *ResourceLocation) *Instance { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *Instance) SetName(v string) *Instance { - s.Name = &v - return s -} - -// SetNetworking sets the Networking field's value. -func (s *Instance) SetNetworking(v *InstanceNetworking) *Instance { - s.Networking = v - return s -} - -// SetPrivateIpAddress sets the PrivateIpAddress field's value. -func (s *Instance) SetPrivateIpAddress(v string) *Instance { - s.PrivateIpAddress = &v - return s -} - -// SetPublicIpAddress sets the PublicIpAddress field's value. -func (s *Instance) SetPublicIpAddress(v string) *Instance { - s.PublicIpAddress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Instance) SetResourceType(v string) *Instance { - s.ResourceType = &v - return s -} - -// SetSshKeyName sets the SshKeyName field's value. -func (s *Instance) SetSshKeyName(v string) *Instance { - s.SshKeyName = &v - return s -} - -// SetState sets the State field's value. -func (s *Instance) SetState(v *InstanceState) *Instance { - s.State = v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *Instance) SetSupportCode(v string) *Instance { - s.SupportCode = &v - return s -} - -// SetUsername sets the Username field's value. -func (s *Instance) SetUsername(v string) *Instance { - s.Username = &v - return s -} - -// The parameters for gaining temporary access to one of your Amazon Lightsail -// instances. -type InstanceAccessDetails struct { - _ struct{} `type:"structure"` - - // For SSH access, the public key to use when accessing your instance For OpenSSH - // clients (e.g., command line SSH), you should save this value to tempkey-cert.pub. - CertKey *string `locationName:"certKey" type:"string"` - - // For SSH access, the date on which the temporary keys expire. - ExpiresAt *time.Time `locationName:"expiresAt" type:"timestamp"` - - // The name of this Amazon Lightsail instance. - InstanceName *string `locationName:"instanceName" type:"string"` - - // The public IP address of the Amazon Lightsail instance. - IpAddress *string `locationName:"ipAddress" type:"string"` - - // For RDP access, the password for your Amazon Lightsail instance. Password - // will be an empty string if the password for your new instance is not ready - // yet. When you create an instance, it can take up to 15 minutes for the instance - // to be ready. - // - // If you create an instance using any key pair other than the default (LightsailDefaultKeyPair), - // password will always be an empty string. - // - // If you change the Administrator password on the instance, Lightsail will - // continue to return the original password value. When accessing the instance - // using RDP, you need to manually enter the Administrator password after changing - // it from the default. - Password *string `locationName:"password" type:"string"` - - // For a Windows Server-based instance, an object with the data you can use - // to retrieve your password. This is only needed if password is empty and the - // instance is not new (and therefore the password is not ready yet). When you - // create an instance, it can take up to 15 minutes for the instance to be ready. - PasswordData *PasswordData `locationName:"passwordData" type:"structure"` - - // For SSH access, the temporary private key. For OpenSSH clients (e.g., command - // line SSH), you should save this value to tempkey). - PrivateKey *string `locationName:"privateKey" type:"string"` - - // The protocol for these Amazon Lightsail instance access details. - Protocol *string `locationName:"protocol" type:"string" enum:"InstanceAccessProtocol"` - - // The user name to use when logging in to the Amazon Lightsail instance. - Username *string `locationName:"username" type:"string"` -} - -// String returns the string representation -func (s InstanceAccessDetails) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceAccessDetails) GoString() string { - return s.String() -} - -// SetCertKey sets the CertKey field's value. -func (s *InstanceAccessDetails) SetCertKey(v string) *InstanceAccessDetails { - s.CertKey = &v - return s -} - -// SetExpiresAt sets the ExpiresAt field's value. -func (s *InstanceAccessDetails) SetExpiresAt(v time.Time) *InstanceAccessDetails { - s.ExpiresAt = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *InstanceAccessDetails) SetInstanceName(v string) *InstanceAccessDetails { - s.InstanceName = &v - return s -} - -// SetIpAddress sets the IpAddress field's value. -func (s *InstanceAccessDetails) SetIpAddress(v string) *InstanceAccessDetails { - s.IpAddress = &v - return s -} - -// SetPassword sets the Password field's value. -func (s *InstanceAccessDetails) SetPassword(v string) *InstanceAccessDetails { - s.Password = &v - return s -} - -// SetPasswordData sets the PasswordData field's value. -func (s *InstanceAccessDetails) SetPasswordData(v *PasswordData) *InstanceAccessDetails { - s.PasswordData = v - return s -} - -// SetPrivateKey sets the PrivateKey field's value. -func (s *InstanceAccessDetails) SetPrivateKey(v string) *InstanceAccessDetails { - s.PrivateKey = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *InstanceAccessDetails) SetProtocol(v string) *InstanceAccessDetails { - s.Protocol = &v - return s -} - -// SetUsername sets the Username field's value. -func (s *InstanceAccessDetails) SetUsername(v string) *InstanceAccessDetails { - s.Username = &v - return s -} - -// Describes the hardware for the instance. -type InstanceHardware struct { - _ struct{} `type:"structure"` - - // The number of vCPUs the instance has. - CpuCount *int64 `locationName:"cpuCount" type:"integer"` - - // The disks attached to the instance. - Disks []*Disk `locationName:"disks" type:"list"` - - // The amount of RAM in GB on the instance (e.g., 1.0). - RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` -} - -// String returns the string representation -func (s InstanceHardware) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceHardware) GoString() string { - return s.String() -} - -// SetCpuCount sets the CpuCount field's value. -func (s *InstanceHardware) SetCpuCount(v int64) *InstanceHardware { - s.CpuCount = &v - return s -} - -// SetDisks sets the Disks field's value. -func (s *InstanceHardware) SetDisks(v []*Disk) *InstanceHardware { - s.Disks = v - return s -} - -// SetRamSizeInGb sets the RamSizeInGb field's value. -func (s *InstanceHardware) SetRamSizeInGb(v float64) *InstanceHardware { - s.RamSizeInGb = &v - return s -} - -// Describes information about the health of the instance. -type InstanceHealthSummary struct { - _ struct{} `type:"structure"` - - // Describes the overall instance health. Valid values are below. - InstanceHealth *string `locationName:"instanceHealth" type:"string" enum:"InstanceHealthState"` - - // More information about the instance health. If the instanceHealth is healthy, - // then an instanceHealthReason value is not provided. - // - // If instanceHealth is initial, the instanceHealthReason value can be one of - // the following: - // - // * Lb.RegistrationInProgress - The target instance is in the process of - // being registered with the load balancer. - // - // * Lb.InitialHealthChecking - The Lightsail load balancer is still sending - // the target instance the minimum number of health checks required to determine - // its health status. - // - // If instanceHealth is unhealthy, the instanceHealthReason value can be one - // of the following: - // - // * Instance.ResponseCodeMismatch - The health checks did not return an - // expected HTTP code. - // - // * Instance.Timeout - The health check requests timed out. - // - // * Instance.FailedHealthChecks - The health checks failed because the connection - // to the target instance timed out, the target instance response was malformed, - // or the target instance failed the health check for an unknown reason. - // - // * Lb.InternalError - The health checks failed due to an internal error. - // - // If instanceHealth is unused, the instanceHealthReason value can be one of - // the following: - // - // * Instance.NotRegistered - The target instance is not registered with - // the target group. - // - // * Instance.NotInUse - The target group is not used by any load balancer, - // or the target instance is in an Availability Zone that is not enabled - // for its load balancer. - // - // * Instance.IpUnusable - The target IP address is reserved for use by a - // Lightsail load balancer. - // - // * Instance.InvalidState - The target is in the stopped or terminated state. - // - // If instanceHealth is draining, the instanceHealthReason value can be one - // of the following: - // - // * Instance.DeregistrationInProgress - The target instance is in the process - // of being deregistered and the deregistration delay period has not expired. - InstanceHealthReason *string `locationName:"instanceHealthReason" type:"string" enum:"InstanceHealthReason"` - - // The name of the Lightsail instance for which you are requesting health check - // data. - InstanceName *string `locationName:"instanceName" type:"string"` -} - -// String returns the string representation -func (s InstanceHealthSummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceHealthSummary) GoString() string { - return s.String() -} - -// SetInstanceHealth sets the InstanceHealth field's value. -func (s *InstanceHealthSummary) SetInstanceHealth(v string) *InstanceHealthSummary { - s.InstanceHealth = &v - return s -} - -// SetInstanceHealthReason sets the InstanceHealthReason field's value. -func (s *InstanceHealthSummary) SetInstanceHealthReason(v string) *InstanceHealthSummary { - s.InstanceHealthReason = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *InstanceHealthSummary) SetInstanceName(v string) *InstanceHealthSummary { - s.InstanceName = &v - return s -} - -// Describes monthly data transfer rates and port information for an instance. -type InstanceNetworking struct { - _ struct{} `type:"structure"` - - // The amount of data in GB allocated for monthly data transfers. - MonthlyTransfer *MonthlyTransfer `locationName:"monthlyTransfer" type:"structure"` - - // An array of key-value pairs containing information about the ports on the - // instance. - Ports []*InstancePortInfo `locationName:"ports" type:"list"` -} - -// String returns the string representation -func (s InstanceNetworking) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceNetworking) GoString() string { - return s.String() -} - -// SetMonthlyTransfer sets the MonthlyTransfer field's value. -func (s *InstanceNetworking) SetMonthlyTransfer(v *MonthlyTransfer) *InstanceNetworking { - s.MonthlyTransfer = v - return s -} - -// SetPorts sets the Ports field's value. -func (s *InstanceNetworking) SetPorts(v []*InstancePortInfo) *InstanceNetworking { - s.Ports = v - return s -} - -// Describes information about the instance ports. -type InstancePortInfo struct { - _ struct{} `type:"structure"` - - // The access direction (inbound or outbound). - AccessDirection *string `locationName:"accessDirection" type:"string" enum:"AccessDirection"` - - // The location from which access is allowed (e.g., Anywhere (0.0.0.0/0)). - AccessFrom *string `locationName:"accessFrom" type:"string"` - - // The type of access (Public or Private). - AccessType *string `locationName:"accessType" type:"string" enum:"PortAccessType"` - - // The common name. - CommonName *string `locationName:"commonName" type:"string"` - - // The first port in the range. - FromPort *int64 `locationName:"fromPort" type:"integer"` - - // The protocol being used. Can be one of the following. - // - // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, - // and error-checked delivery of streamed data between applications running - // on hosts communicating by an IP network. If you have an application that - // doesn't require reliable data stream service, use UDP instead. - // - // * all - All transport layer protocol types. For more general information, - // see Transport layer (https://en.wikipedia.org/wiki/Transport_layer) on - // Wikipedia. - // - // * udp - With User Datagram Protocol (UDP), computer applications can send - // messages (or datagrams) to other hosts on an Internet Protocol (IP) network. - // Prior communications are not required to set up transmission channels - // or data paths. Applications that don't require reliable data stream service - // can use UDP, which provides a connectionless datagram service that emphasizes - // reduced latency over reliability. If you do require reliable data stream - // service, use TCP instead. - Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - - // The last port in the range. - ToPort *int64 `locationName:"toPort" type:"integer"` -} - -// String returns the string representation -func (s InstancePortInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstancePortInfo) GoString() string { - return s.String() -} - -// SetAccessDirection sets the AccessDirection field's value. -func (s *InstancePortInfo) SetAccessDirection(v string) *InstancePortInfo { - s.AccessDirection = &v - return s -} - -// SetAccessFrom sets the AccessFrom field's value. -func (s *InstancePortInfo) SetAccessFrom(v string) *InstancePortInfo { - s.AccessFrom = &v - return s -} - -// SetAccessType sets the AccessType field's value. -func (s *InstancePortInfo) SetAccessType(v string) *InstancePortInfo { - s.AccessType = &v - return s -} - -// SetCommonName sets the CommonName field's value. -func (s *InstancePortInfo) SetCommonName(v string) *InstancePortInfo { - s.CommonName = &v - return s -} - -// SetFromPort sets the FromPort field's value. -func (s *InstancePortInfo) SetFromPort(v int64) *InstancePortInfo { - s.FromPort = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *InstancePortInfo) SetProtocol(v string) *InstancePortInfo { - s.Protocol = &v - return s -} - -// SetToPort sets the ToPort field's value. -func (s *InstancePortInfo) SetToPort(v int64) *InstancePortInfo { - s.ToPort = &v - return s -} - -// Describes the port state. -type InstancePortState struct { - _ struct{} `type:"structure"` - - // The first port in the range. - FromPort *int64 `locationName:"fromPort" type:"integer"` - - // The protocol being used. Can be one of the following. - // - // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, - // and error-checked delivery of streamed data between applications running - // on hosts communicating by an IP network. If you have an application that - // doesn't require reliable data stream service, use UDP instead. - // - // * all - All transport layer protocol types. For more general information, - // see Transport layer (https://en.wikipedia.org/wiki/Transport_layer) on - // Wikipedia. - // - // * udp - With User Datagram Protocol (UDP), computer applications can send - // messages (or datagrams) to other hosts on an Internet Protocol (IP) network. - // Prior communications are not required to set up transmission channels - // or data paths. Applications that don't require reliable data stream service - // can use UDP, which provides a connectionless datagram service that emphasizes - // reduced latency over reliability. If you do require reliable data stream - // service, use TCP instead. - Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - - // Specifies whether the instance port is open or closed. - State *string `locationName:"state" type:"string" enum:"PortState"` - - // The last port in the range. - ToPort *int64 `locationName:"toPort" type:"integer"` -} - -// String returns the string representation -func (s InstancePortState) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstancePortState) GoString() string { - return s.String() -} - -// SetFromPort sets the FromPort field's value. -func (s *InstancePortState) SetFromPort(v int64) *InstancePortState { - s.FromPort = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *InstancePortState) SetProtocol(v string) *InstancePortState { - s.Protocol = &v - return s -} - -// SetState sets the State field's value. -func (s *InstancePortState) SetState(v string) *InstancePortState { - s.State = &v - return s -} - -// SetToPort sets the ToPort field's value. -func (s *InstancePortState) SetToPort(v int64) *InstancePortState { - s.ToPort = &v - return s -} - -// Describes the snapshot of the virtual private server, or instance. -type InstanceSnapshot struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the snapshot (e.g., arn:aws:lightsail:us-east-2:123456789101:InstanceSnapshot/d23b5706-3322-4d83-81e5-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The timestamp when the snapshot was created (e.g., 1479907467.024). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // An array of disk objects containing information about all block storage disks. - FromAttachedDisks []*Disk `locationName:"fromAttachedDisks" type:"list"` - - // The blueprint ID from which you created the snapshot (e.g., os_debian_8_3). - // A blueprint is a virtual private server (or instance) image used to create - // instances quickly. - FromBlueprintId *string `locationName:"fromBlueprintId" type:"string"` - - // The bundle ID from which you created the snapshot (e.g., micro_1_0). - FromBundleId *string `locationName:"fromBundleId" type:"string"` - - // The Amazon Resource Name (ARN) of the instance from which the snapshot was - // created (e.g., arn:aws:lightsail:us-east-2:123456789101:Instance/64b8404c-ccb1-430b-8daf-12345EXAMPLE). - FromInstanceArn *string `locationName:"fromInstanceArn" type:"string"` - - // The instance from which the snapshot was created. - FromInstanceName *string `locationName:"fromInstanceName" type:"string"` - - // The region name and availability zone where you created the snapshot. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the snapshot. - Name *string `locationName:"name" type:"string"` - - // The progress of the snapshot. - Progress *string `locationName:"progress" type:"string"` - - // The type of resource (usually InstanceSnapshot). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size in GB of the SSD. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // The state the snapshot is in. - State *string `locationName:"state" type:"string" enum:"InstanceSnapshotState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s InstanceSnapshot) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceSnapshot) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *InstanceSnapshot) SetArn(v string) *InstanceSnapshot { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *InstanceSnapshot) SetCreatedAt(v time.Time) *InstanceSnapshot { - s.CreatedAt = &v - return s -} - -// SetFromAttachedDisks sets the FromAttachedDisks field's value. -func (s *InstanceSnapshot) SetFromAttachedDisks(v []*Disk) *InstanceSnapshot { - s.FromAttachedDisks = v - return s -} - -// SetFromBlueprintId sets the FromBlueprintId field's value. -func (s *InstanceSnapshot) SetFromBlueprintId(v string) *InstanceSnapshot { - s.FromBlueprintId = &v - return s -} - -// SetFromBundleId sets the FromBundleId field's value. -func (s *InstanceSnapshot) SetFromBundleId(v string) *InstanceSnapshot { - s.FromBundleId = &v - return s -} - -// SetFromInstanceArn sets the FromInstanceArn field's value. -func (s *InstanceSnapshot) SetFromInstanceArn(v string) *InstanceSnapshot { - s.FromInstanceArn = &v - return s -} - -// SetFromInstanceName sets the FromInstanceName field's value. -func (s *InstanceSnapshot) SetFromInstanceName(v string) *InstanceSnapshot { - s.FromInstanceName = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *InstanceSnapshot) SetLocation(v *ResourceLocation) *InstanceSnapshot { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *InstanceSnapshot) SetName(v string) *InstanceSnapshot { - s.Name = &v - return s -} - -// SetProgress sets the Progress field's value. -func (s *InstanceSnapshot) SetProgress(v string) *InstanceSnapshot { - s.Progress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *InstanceSnapshot) SetResourceType(v string) *InstanceSnapshot { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *InstanceSnapshot) SetSizeInGb(v int64) *InstanceSnapshot { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *InstanceSnapshot) SetState(v string) *InstanceSnapshot { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *InstanceSnapshot) SetSupportCode(v string) *InstanceSnapshot { - s.SupportCode = &v - return s -} - -// Describes the virtual private server (or instance) status. -type InstanceState struct { - _ struct{} `type:"structure"` - - // The status code for the instance. - Code *int64 `locationName:"code" type:"integer"` - - // The state of the instance (e.g., running or pending). - Name *string `locationName:"name" type:"string"` -} - -// String returns the string representation -func (s InstanceState) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceState) GoString() string { - return s.String() -} - -// SetCode sets the Code field's value. -func (s *InstanceState) SetCode(v int64) *InstanceState { - s.Code = &v - return s -} - -// SetName sets the Name field's value. -func (s *InstanceState) SetName(v string) *InstanceState { - s.Name = &v - return s -} - -type IsVpcPeeredInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s IsVpcPeeredInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s IsVpcPeeredInput) GoString() string { - return s.String() -} - -type IsVpcPeeredOutput struct { - _ struct{} `type:"structure"` - - // Returns true if the Lightsail VPC is peered; otherwise, false. - IsPeered *bool `locationName:"isPeered" type:"boolean"` -} - -// String returns the string representation -func (s IsVpcPeeredOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s IsVpcPeeredOutput) GoString() string { - return s.String() -} - -// SetIsPeered sets the IsPeered field's value. -func (s *IsVpcPeeredOutput) SetIsPeered(v bool) *IsVpcPeeredOutput { - s.IsPeered = &v - return s -} - -// Describes the SSH key pair. -type KeyPair struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the key pair (e.g., arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The timestamp when the key pair was created (e.g., 1479816991.349). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The RSA fingerprint of the key pair. - Fingerprint *string `locationName:"fingerprint" type:"string"` - - // The region name and Availability Zone where the key pair was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The friendly name of the SSH key pair. - Name *string `locationName:"name" type:"string"` - - // The resource type (usually KeyPair). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s KeyPair) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s KeyPair) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *KeyPair) SetArn(v string) *KeyPair { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *KeyPair) SetCreatedAt(v time.Time) *KeyPair { - s.CreatedAt = &v - return s -} - -// SetFingerprint sets the Fingerprint field's value. -func (s *KeyPair) SetFingerprint(v string) *KeyPair { - s.Fingerprint = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *KeyPair) SetLocation(v *ResourceLocation) *KeyPair { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *KeyPair) SetName(v string) *KeyPair { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *KeyPair) SetResourceType(v string) *KeyPair { - s.ResourceType = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *KeyPair) SetSupportCode(v string) *KeyPair { - s.SupportCode = &v - return s -} - -// Describes the Lightsail load balancer. -type LoadBalancer struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the load balancer. - Arn *string `locationName:"arn" type:"string"` - - // A string to string map of the configuration options for your load balancer. - // Valid values are listed below. - ConfigurationOptions map[string]*string `locationName:"configurationOptions" type:"map"` - - // The date when your load balancer was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The DNS name of your Lightsail load balancer. - DnsName *string `locationName:"dnsName" type:"string"` - - // The path you specified to perform your health checks. If no path is specified, - // the load balancer tries to make a request to the default (root) page. - HealthCheckPath *string `locationName:"healthCheckPath" type:"string"` - - // An array of InstanceHealthSummary objects describing the health of the load - // balancer. - InstanceHealthSummary []*InstanceHealthSummary `locationName:"instanceHealthSummary" type:"list"` - - // The port where the load balancer will direct traffic to your Lightsail instances. - // For HTTP traffic, it's port 80. For HTTPS traffic, it's port 443. - InstancePort *int64 `locationName:"instancePort" type:"integer"` - - // The AWS Region where your load balancer was created (e.g., us-east-2a). Lightsail - // automatically creates your load balancer across Availability Zones. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the load balancer (e.g., my-load-balancer). - Name *string `locationName:"name" type:"string"` - - // The protocol you have enabled for your load balancer. Valid values are below. - // - // You can't just have HTTP_HTTPS, but you can have just HTTP. - Protocol *string `locationName:"protocol" type:"string" enum:"LoadBalancerProtocol"` - - // An array of public port settings for your load balancer. For HTTP, use port - // 80. For HTTPS, use port 443. - PublicPorts []*int64 `locationName:"publicPorts" type:"list"` - - // The resource type (e.g., LoadBalancer. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The status of your load balancer. Valid values are below. - State *string `locationName:"state" type:"string" enum:"LoadBalancerState"` - - // The support code. Include this code in your email to support when you have - // questions about your Lightsail load balancer. This code enables our support - // team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` - - // An array of LoadBalancerTlsCertificateSummary objects that provide additional - // information about the SSL/TLS certificates. For example, if true, the certificate - // is attached to the load balancer. - TlsCertificateSummaries []*LoadBalancerTlsCertificateSummary `locationName:"tlsCertificateSummaries" type:"list"` -} - -// String returns the string representation -func (s LoadBalancer) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancer) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *LoadBalancer) SetArn(v string) *LoadBalancer { - s.Arn = &v - return s -} - -// SetConfigurationOptions sets the ConfigurationOptions field's value. -func (s *LoadBalancer) SetConfigurationOptions(v map[string]*string) *LoadBalancer { - s.ConfigurationOptions = v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *LoadBalancer) SetCreatedAt(v time.Time) *LoadBalancer { - s.CreatedAt = &v - return s -} - -// SetDnsName sets the DnsName field's value. -func (s *LoadBalancer) SetDnsName(v string) *LoadBalancer { - s.DnsName = &v - return s -} - -// SetHealthCheckPath sets the HealthCheckPath field's value. -func (s *LoadBalancer) SetHealthCheckPath(v string) *LoadBalancer { - s.HealthCheckPath = &v - return s -} - -// SetInstanceHealthSummary sets the InstanceHealthSummary field's value. -func (s *LoadBalancer) SetInstanceHealthSummary(v []*InstanceHealthSummary) *LoadBalancer { - s.InstanceHealthSummary = v - return s -} - -// SetInstancePort sets the InstancePort field's value. -func (s *LoadBalancer) SetInstancePort(v int64) *LoadBalancer { - s.InstancePort = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *LoadBalancer) SetLocation(v *ResourceLocation) *LoadBalancer { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancer) SetName(v string) *LoadBalancer { - s.Name = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *LoadBalancer) SetProtocol(v string) *LoadBalancer { - s.Protocol = &v - return s -} - -// SetPublicPorts sets the PublicPorts field's value. -func (s *LoadBalancer) SetPublicPorts(v []*int64) *LoadBalancer { - s.PublicPorts = v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *LoadBalancer) SetResourceType(v string) *LoadBalancer { - s.ResourceType = &v - return s -} - -// SetState sets the State field's value. -func (s *LoadBalancer) SetState(v string) *LoadBalancer { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *LoadBalancer) SetSupportCode(v string) *LoadBalancer { - s.SupportCode = &v - return s -} - -// SetTlsCertificateSummaries sets the TlsCertificateSummaries field's value. -func (s *LoadBalancer) SetTlsCertificateSummaries(v []*LoadBalancerTlsCertificateSummary) *LoadBalancer { - s.TlsCertificateSummaries = v - return s -} - -// Describes a load balancer SSL/TLS certificate. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -type LoadBalancerTlsCertificate struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the SSL/TLS certificate. - Arn *string `locationName:"arn" type:"string"` - - // The time when you created your SSL/TLS certificate. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The domain name for your SSL/TLS certificate. - DomainName *string `locationName:"domainName" type:"string"` - - // An array of LoadBalancerTlsCertificateDomainValidationRecord objects describing - // the records. - DomainValidationRecords []*LoadBalancerTlsCertificateDomainValidationRecord `locationName:"domainValidationRecords" type:"list"` - - // The reason for the SSL/TLS certificate validation failure. - FailureReason *string `locationName:"failureReason" type:"string" enum:"LoadBalancerTlsCertificateFailureReason"` - - // When true, the SSL/TLS certificate is attached to the Lightsail load balancer. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // The time when the SSL/TLS certificate was issued. - IssuedAt *time.Time `locationName:"issuedAt" type:"timestamp"` - - // The issuer of the certificate. - Issuer *string `locationName:"issuer" type:"string"` - - // The algorithm that was used to generate the key pair (the public and private - // key). - KeyAlgorithm *string `locationName:"keyAlgorithm" type:"string"` - - // The load balancer name where your SSL/TLS certificate is attached. - LoadBalancerName *string `locationName:"loadBalancerName" type:"string"` - - // The AWS Region and Availability Zone where you created your certificate. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the SSL/TLS certificate (e.g., my-certificate). - Name *string `locationName:"name" type:"string"` - - // The timestamp when the SSL/TLS certificate expires. - NotAfter *time.Time `locationName:"notAfter" type:"timestamp"` - - // The timestamp when the SSL/TLS certificate is first valid. - NotBefore *time.Time `locationName:"notBefore" type:"timestamp"` - - // An object containing information about the status of Lightsail's managed - // renewal for the certificate. - RenewalSummary *LoadBalancerTlsCertificateRenewalSummary `locationName:"renewalSummary" type:"structure"` - - // The resource type (e.g., LoadBalancerTlsCertificate). - // - // * Instance - A Lightsail instance (a virtual private server) - // - // * StaticIp - A static IP address - // - // * KeyPair - The key pair used to connect to a Lightsail instance - // - // * InstanceSnapshot - A Lightsail instance snapshot - // - // * Domain - A DNS zone - // - // * PeeredVpc - A peered VPC - // - // * LoadBalancer - A Lightsail load balancer - // - // * LoadBalancerTlsCertificate - An SSL/TLS certificate associated with - // a Lightsail load balancer - // - // * Disk - A Lightsail block storage disk - // - // * DiskSnapshot - A block storage disk snapshot - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The reason the certificate was revoked. Valid values are below. - RevocationReason *string `locationName:"revocationReason" type:"string" enum:"LoadBalancerTlsCertificateRevocationReason"` - - // The timestamp when the SSL/TLS certificate was revoked. - RevokedAt *time.Time `locationName:"revokedAt" type:"timestamp"` - - // The serial number of the certificate. - Serial *string `locationName:"serial" type:"string"` - - // The algorithm that was used to sign the certificate. - SignatureAlgorithm *string `locationName:"signatureAlgorithm" type:"string"` - - // The status of the SSL/TLS certificate. Valid values are below. - Status *string `locationName:"status" type:"string" enum:"LoadBalancerTlsCertificateStatus"` - - // The name of the entity that is associated with the public key contained in - // the certificate. - Subject *string `locationName:"subject" type:"string"` - - // One or more domains or subdomains included in the certificate. This list - // contains the domain names that are bound to the public key that is contained - // in the certificate. The subject alternative names include the canonical domain - // name (CNAME) of the certificate and additional domain names that can be used - // to connect to the website, such as example.com, www.example.com, or m.example.com. - SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` - - // The support code. Include this code in your email to support when you have - // questions about your Lightsail load balancer or SSL/TLS certificate. This - // code enables our support team to look up your Lightsail information more - // easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificate) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificate) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *LoadBalancerTlsCertificate) SetArn(v string) *LoadBalancerTlsCertificate { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *LoadBalancerTlsCertificate) SetCreatedAt(v time.Time) *LoadBalancerTlsCertificate { - s.CreatedAt = &v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *LoadBalancerTlsCertificate) SetDomainName(v string) *LoadBalancerTlsCertificate { - s.DomainName = &v - return s -} - -// SetDomainValidationRecords sets the DomainValidationRecords field's value. -func (s *LoadBalancerTlsCertificate) SetDomainValidationRecords(v []*LoadBalancerTlsCertificateDomainValidationRecord) *LoadBalancerTlsCertificate { - s.DomainValidationRecords = v - return s -} - -// SetFailureReason sets the FailureReason field's value. -func (s *LoadBalancerTlsCertificate) SetFailureReason(v string) *LoadBalancerTlsCertificate { - s.FailureReason = &v - return s -} - -// SetIsAttached sets the IsAttached field's value. -func (s *LoadBalancerTlsCertificate) SetIsAttached(v bool) *LoadBalancerTlsCertificate { - s.IsAttached = &v - return s -} - -// SetIssuedAt sets the IssuedAt field's value. -func (s *LoadBalancerTlsCertificate) SetIssuedAt(v time.Time) *LoadBalancerTlsCertificate { - s.IssuedAt = &v - return s -} - -// SetIssuer sets the Issuer field's value. -func (s *LoadBalancerTlsCertificate) SetIssuer(v string) *LoadBalancerTlsCertificate { - s.Issuer = &v - return s -} - -// SetKeyAlgorithm sets the KeyAlgorithm field's value. -func (s *LoadBalancerTlsCertificate) SetKeyAlgorithm(v string) *LoadBalancerTlsCertificate { - s.KeyAlgorithm = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *LoadBalancerTlsCertificate) SetLoadBalancerName(v string) *LoadBalancerTlsCertificate { - s.LoadBalancerName = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *LoadBalancerTlsCertificate) SetLocation(v *ResourceLocation) *LoadBalancerTlsCertificate { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancerTlsCertificate) SetName(v string) *LoadBalancerTlsCertificate { - s.Name = &v - return s -} - -// SetNotAfter sets the NotAfter field's value. -func (s *LoadBalancerTlsCertificate) SetNotAfter(v time.Time) *LoadBalancerTlsCertificate { - s.NotAfter = &v - return s -} - -// SetNotBefore sets the NotBefore field's value. -func (s *LoadBalancerTlsCertificate) SetNotBefore(v time.Time) *LoadBalancerTlsCertificate { - s.NotBefore = &v - return s -} - -// SetRenewalSummary sets the RenewalSummary field's value. -func (s *LoadBalancerTlsCertificate) SetRenewalSummary(v *LoadBalancerTlsCertificateRenewalSummary) *LoadBalancerTlsCertificate { - s.RenewalSummary = v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *LoadBalancerTlsCertificate) SetResourceType(v string) *LoadBalancerTlsCertificate { - s.ResourceType = &v - return s -} - -// SetRevocationReason sets the RevocationReason field's value. -func (s *LoadBalancerTlsCertificate) SetRevocationReason(v string) *LoadBalancerTlsCertificate { - s.RevocationReason = &v - return s -} - -// SetRevokedAt sets the RevokedAt field's value. -func (s *LoadBalancerTlsCertificate) SetRevokedAt(v time.Time) *LoadBalancerTlsCertificate { - s.RevokedAt = &v - return s -} - -// SetSerial sets the Serial field's value. -func (s *LoadBalancerTlsCertificate) SetSerial(v string) *LoadBalancerTlsCertificate { - s.Serial = &v - return s -} - -// SetSignatureAlgorithm sets the SignatureAlgorithm field's value. -func (s *LoadBalancerTlsCertificate) SetSignatureAlgorithm(v string) *LoadBalancerTlsCertificate { - s.SignatureAlgorithm = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *LoadBalancerTlsCertificate) SetStatus(v string) *LoadBalancerTlsCertificate { - s.Status = &v - return s -} - -// SetSubject sets the Subject field's value. -func (s *LoadBalancerTlsCertificate) SetSubject(v string) *LoadBalancerTlsCertificate { - s.Subject = &v - return s -} - -// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value. -func (s *LoadBalancerTlsCertificate) SetSubjectAlternativeNames(v []*string) *LoadBalancerTlsCertificate { - s.SubjectAlternativeNames = v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *LoadBalancerTlsCertificate) SetSupportCode(v string) *LoadBalancerTlsCertificate { - s.SupportCode = &v - return s -} - -// Contains information about the domain names on an SSL/TLS certificate that -// you will use to validate domain ownership. -type LoadBalancerTlsCertificateDomainValidationOption struct { - _ struct{} `type:"structure"` - - // The fully qualified domain name in the certificate request. - DomainName *string `locationName:"domainName" type:"string"` - - // The status of the domain validation. Valid values are listed below. - ValidationStatus *string `locationName:"validationStatus" type:"string" enum:"LoadBalancerTlsCertificateDomainStatus"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationOption) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationOption) GoString() string { - return s.String() -} - -// SetDomainName sets the DomainName field's value. -func (s *LoadBalancerTlsCertificateDomainValidationOption) SetDomainName(v string) *LoadBalancerTlsCertificateDomainValidationOption { - s.DomainName = &v - return s -} - -// SetValidationStatus sets the ValidationStatus field's value. -func (s *LoadBalancerTlsCertificateDomainValidationOption) SetValidationStatus(v string) *LoadBalancerTlsCertificateDomainValidationOption { - s.ValidationStatus = &v - return s -} - -// Describes the validation record of each domain name in the SSL/TLS certificate. -type LoadBalancerTlsCertificateDomainValidationRecord struct { - _ struct{} `type:"structure"` - - // The domain name against which your SSL/TLS certificate was validated. - DomainName *string `locationName:"domainName" type:"string"` - - // A fully qualified domain name in the certificate. For example, example.com. - Name *string `locationName:"name" type:"string"` - - // The type of validation record. For example, CNAME for domain validation. - Type *string `locationName:"type" type:"string"` - - // The validation status. Valid values are listed below. - ValidationStatus *string `locationName:"validationStatus" type:"string" enum:"LoadBalancerTlsCertificateDomainStatus"` - - // The value for that type. - Value *string `locationName:"value" type:"string"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationRecord) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationRecord) GoString() string { - return s.String() -} - -// SetDomainName sets the DomainName field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetDomainName(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.DomainName = &v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetName(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.Name = &v - return s -} - -// SetType sets the Type field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetType(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.Type = &v - return s -} - -// SetValidationStatus sets the ValidationStatus field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetValidationStatus(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.ValidationStatus = &v - return s -} - -// SetValue sets the Value field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetValue(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.Value = &v - return s -} - -// Contains information about the status of Lightsail's managed renewal for -// the certificate. -type LoadBalancerTlsCertificateRenewalSummary struct { - _ struct{} `type:"structure"` - - // Contains information about the validation of each domain name in the certificate, - // as it pertains to Lightsail's managed renewal. This is different from the - // initial validation that occurs as a result of the RequestCertificate request. - DomainValidationOptions []*LoadBalancerTlsCertificateDomainValidationOption `locationName:"domainValidationOptions" type:"list"` - - // The status of Lightsail's managed renewal of the certificate. Valid values - // are listed below. - RenewalStatus *string `locationName:"renewalStatus" type:"string" enum:"LoadBalancerTlsCertificateRenewalStatus"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateRenewalSummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateRenewalSummary) GoString() string { - return s.String() -} - -// SetDomainValidationOptions sets the DomainValidationOptions field's value. -func (s *LoadBalancerTlsCertificateRenewalSummary) SetDomainValidationOptions(v []*LoadBalancerTlsCertificateDomainValidationOption) *LoadBalancerTlsCertificateRenewalSummary { - s.DomainValidationOptions = v - return s -} - -// SetRenewalStatus sets the RenewalStatus field's value. -func (s *LoadBalancerTlsCertificateRenewalSummary) SetRenewalStatus(v string) *LoadBalancerTlsCertificateRenewalSummary { - s.RenewalStatus = &v - return s -} - -// Provides a summary of SSL/TLS certificate metadata. -type LoadBalancerTlsCertificateSummary struct { - _ struct{} `type:"structure"` - - // When true, the SSL/TLS certificate is attached to the Lightsail load balancer. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // The name of the SSL/TLS certificate. - Name *string `locationName:"name" type:"string"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateSummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateSummary) GoString() string { - return s.String() -} - -// SetIsAttached sets the IsAttached field's value. -func (s *LoadBalancerTlsCertificateSummary) SetIsAttached(v bool) *LoadBalancerTlsCertificateSummary { - s.IsAttached = &v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancerTlsCertificateSummary) SetName(v string) *LoadBalancerTlsCertificateSummary { - s.Name = &v - return s -} - -// Describes the metric data point. -type MetricDatapoint struct { - _ struct{} `type:"structure"` - - // The average. - Average *float64 `locationName:"average" type:"double"` - - // The maximum. - Maximum *float64 `locationName:"maximum" type:"double"` - - // The minimum. - Minimum *float64 `locationName:"minimum" type:"double"` - - // The sample count. - SampleCount *float64 `locationName:"sampleCount" type:"double"` - - // The sum. - Sum *float64 `locationName:"sum" type:"double"` - - // The timestamp (e.g., 1479816991.349). - Timestamp *time.Time `locationName:"timestamp" type:"timestamp"` - - // The unit. - Unit *string `locationName:"unit" type:"string" enum:"MetricUnit"` -} - -// String returns the string representation -func (s MetricDatapoint) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MetricDatapoint) GoString() string { - return s.String() -} - -// SetAverage sets the Average field's value. -func (s *MetricDatapoint) SetAverage(v float64) *MetricDatapoint { - s.Average = &v - return s -} - -// SetMaximum sets the Maximum field's value. -func (s *MetricDatapoint) SetMaximum(v float64) *MetricDatapoint { - s.Maximum = &v - return s -} - -// SetMinimum sets the Minimum field's value. -func (s *MetricDatapoint) SetMinimum(v float64) *MetricDatapoint { - s.Minimum = &v - return s -} - -// SetSampleCount sets the SampleCount field's value. -func (s *MetricDatapoint) SetSampleCount(v float64) *MetricDatapoint { - s.SampleCount = &v - return s -} - -// SetSum sets the Sum field's value. -func (s *MetricDatapoint) SetSum(v float64) *MetricDatapoint { - s.Sum = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *MetricDatapoint) SetTimestamp(v time.Time) *MetricDatapoint { - s.Timestamp = &v - return s -} - -// SetUnit sets the Unit field's value. -func (s *MetricDatapoint) SetUnit(v string) *MetricDatapoint { - s.Unit = &v - return s -} - -// Describes the monthly data transfer in and out of your virtual private server -// (or instance). -type MonthlyTransfer struct { - _ struct{} `type:"structure"` - - // The amount allocated per month (in GB). - GbPerMonthAllocated *int64 `locationName:"gbPerMonthAllocated" type:"integer"` -} - -// String returns the string representation -func (s MonthlyTransfer) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MonthlyTransfer) GoString() string { - return s.String() -} - -// SetGbPerMonthAllocated sets the GbPerMonthAllocated field's value. -func (s *MonthlyTransfer) SetGbPerMonthAllocated(v int64) *MonthlyTransfer { - s.GbPerMonthAllocated = &v - return s -} - -type OpenInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance for which you want to open the public ports. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // An array of key-value pairs containing information about the port mappings. - // - // PortInfo is a required field - PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` -} - -// String returns the string representation -func (s OpenInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OpenInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *OpenInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OpenInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfo == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfo")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *OpenInstancePublicPortsInput) SetInstanceName(v string) *OpenInstancePublicPortsInput { - s.InstanceName = &v - return s -} - -// SetPortInfo sets the PortInfo field's value. -func (s *OpenInstancePublicPortsInput) SetPortInfo(v *PortInfo) *OpenInstancePublicPortsInput { - s.PortInfo = v - return s -} - -type OpenInstancePublicPortsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s OpenInstancePublicPortsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OpenInstancePublicPortsOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *OpenInstancePublicPortsOutput) SetOperation(v *Operation) *OpenInstancePublicPortsOutput { - s.Operation = v - return s -} - -// Describes the API operation. -type Operation struct { - _ struct{} `type:"structure"` - - // The timestamp when the operation was initialized (e.g., 1479816991.349). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The error code. - ErrorCode *string `locationName:"errorCode" type:"string"` - - // The error details. - ErrorDetails *string `locationName:"errorDetails" type:"string"` - - // The ID of the operation. - Id *string `locationName:"id" type:"string"` - - // A Boolean value indicating whether the operation is terminal. - IsTerminal *bool `locationName:"isTerminal" type:"boolean"` - - // The region and Availability Zone. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // Details about the operation (e.g., Debian-1GB-Ohio-1). - OperationDetails *string `locationName:"operationDetails" type:"string"` - - // The type of operation. - OperationType *string `locationName:"operationType" type:"string" enum:"OperationType"` - - // The resource name. - ResourceName *string `locationName:"resourceName" type:"string"` - - // The resource type. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The status of the operation. - Status *string `locationName:"status" type:"string" enum:"OperationStatus"` - - // The timestamp when the status was changed (e.g., 1479816991.349). - StatusChangedAt *time.Time `locationName:"statusChangedAt" type:"timestamp"` -} - -// String returns the string representation -func (s Operation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Operation) GoString() string { - return s.String() -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Operation) SetCreatedAt(v time.Time) *Operation { - s.CreatedAt = &v - return s -} - -// SetErrorCode sets the ErrorCode field's value. -func (s *Operation) SetErrorCode(v string) *Operation { - s.ErrorCode = &v - return s -} - -// SetErrorDetails sets the ErrorDetails field's value. -func (s *Operation) SetErrorDetails(v string) *Operation { - s.ErrorDetails = &v - return s -} - -// SetId sets the Id field's value. -func (s *Operation) SetId(v string) *Operation { - s.Id = &v - return s -} - -// SetIsTerminal sets the IsTerminal field's value. -func (s *Operation) SetIsTerminal(v bool) *Operation { - s.IsTerminal = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *Operation) SetLocation(v *ResourceLocation) *Operation { - s.Location = v - return s -} - -// SetOperationDetails sets the OperationDetails field's value. -func (s *Operation) SetOperationDetails(v string) *Operation { - s.OperationDetails = &v - return s -} - -// SetOperationType sets the OperationType field's value. -func (s *Operation) SetOperationType(v string) *Operation { - s.OperationType = &v - return s -} - -// SetResourceName sets the ResourceName field's value. -func (s *Operation) SetResourceName(v string) *Operation { - s.ResourceName = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Operation) SetResourceType(v string) *Operation { - s.ResourceType = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *Operation) SetStatus(v string) *Operation { - s.Status = &v - return s -} - -// SetStatusChangedAt sets the StatusChangedAt field's value. -func (s *Operation) SetStatusChangedAt(v time.Time) *Operation { - s.StatusChangedAt = &v - return s -} - -// The password data for the Windows Server-based instance, including the ciphertext -// and the key pair name. -type PasswordData struct { - _ struct{} `type:"structure"` - - // The encrypted password. Ciphertext will be an empty string if access to your - // new instance is not ready yet. When you create an instance, it can take up - // to 15 minutes for the instance to be ready. - // - // If you use the default key pair (LightsailDefaultKeyPair), the decrypted - // password will be available in the password field. - // - // If you are using a custom key pair, you need to use your own means of decryption. - // - // If you change the Administrator password on the instance, Lightsail will - // continue to return the original ciphertext value. When accessing the instance - // using RDP, you need to manually enter the Administrator password after changing - // it from the default. - Ciphertext *string `locationName:"ciphertext" type:"string"` - - // The name of the key pair that you used when creating your instance. If no - // key pair name was specified when creating the instance, Lightsail uses the - // default key pair (LightsailDefaultKeyPair). - // - // If you are using a custom key pair, you need to use your own means of decrypting - // your password using the ciphertext. Lightsail creates the ciphertext by encrypting - // your password with the public key part of this key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` -} - -// String returns the string representation -func (s PasswordData) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PasswordData) GoString() string { - return s.String() -} - -// SetCiphertext sets the Ciphertext field's value. -func (s *PasswordData) SetCiphertext(v string) *PasswordData { - s.Ciphertext = &v - return s -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *PasswordData) SetKeyPairName(v string) *PasswordData { - s.KeyPairName = &v - return s -} - -type PeerVpcInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PeerVpcInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PeerVpcInput) GoString() string { - return s.String() -} - -type PeerVpcOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s PeerVpcOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PeerVpcOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *PeerVpcOutput) SetOperation(v *Operation) *PeerVpcOutput { - s.Operation = v - return s -} - -// Describes information about the ports on your virtual private server (or -// instance). -type PortInfo struct { - _ struct{} `type:"structure"` - - // The first port in the range. - FromPort *int64 `locationName:"fromPort" type:"integer"` - - // The protocol. - Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - - // The last port in the range. - ToPort *int64 `locationName:"toPort" type:"integer"` -} - -// String returns the string representation -func (s PortInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PortInfo) GoString() string { - return s.String() -} - -// SetFromPort sets the FromPort field's value. -func (s *PortInfo) SetFromPort(v int64) *PortInfo { - s.FromPort = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *PortInfo) SetProtocol(v string) *PortInfo { - s.Protocol = &v - return s -} - -// SetToPort sets the ToPort field's value. -func (s *PortInfo) SetToPort(v int64) *PortInfo { - s.ToPort = &v - return s -} - -type PutInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The Lightsail instance name of the public port(s) you are setting. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // Specifies information about the public port(s). - // - // PortInfos is a required field - PortInfos []*PortInfo `locationName:"portInfos" type:"list" required:"true"` -} - -// String returns the string representation -func (s PutInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfos == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfos")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *PutInstancePublicPortsInput) SetInstanceName(v string) *PutInstancePublicPortsInput { - s.InstanceName = &v - return s -} - -// SetPortInfos sets the PortInfos field's value. -func (s *PutInstancePublicPortsInput) SetPortInfos(v []*PortInfo) *PutInstancePublicPortsInput { - s.PortInfos = v - return s -} - -type PutInstancePublicPortsOutput struct { - _ struct{} `type:"structure"` - - // Describes metadata about the operation you just executed. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s PutInstancePublicPortsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutInstancePublicPortsOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *PutInstancePublicPortsOutput) SetOperation(v *Operation) *PutInstancePublicPortsOutput { - s.Operation = v - return s -} - -type RebootInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to reboot. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s RebootInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RebootInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RebootInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RebootInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *RebootInstanceInput) SetInstanceName(v string) *RebootInstanceInput { - s.InstanceName = &v - return s -} - -type RebootInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s RebootInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RebootInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *RebootInstanceOutput) SetOperations(v []*Operation) *RebootInstanceOutput { - s.Operations = v - return s -} - -// Describes the AWS Region. -type Region struct { - _ struct{} `type:"structure"` - - // The Availability Zones. Follows the format us-east-2a (case-sensitive). - AvailabilityZones []*AvailabilityZone `locationName:"availabilityZones" type:"list"` - - // The continent code (e.g., NA, meaning North America). - ContinentCode *string `locationName:"continentCode" type:"string"` - - // The description of the AWS Region (e.g., This region is recommended to serve - // users in the eastern United States and eastern Canada). - Description *string `locationName:"description" type:"string"` - - // The display name (e.g., Ohio). - DisplayName *string `locationName:"displayName" type:"string"` - - // The region name (e.g., us-east-2). - Name *string `locationName:"name" type:"string" enum:"RegionName"` -} - -// String returns the string representation -func (s Region) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Region) GoString() string { - return s.String() -} - -// SetAvailabilityZones sets the AvailabilityZones field's value. -func (s *Region) SetAvailabilityZones(v []*AvailabilityZone) *Region { - s.AvailabilityZones = v - return s -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *Region) SetContinentCode(v string) *Region { - s.ContinentCode = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *Region) SetDescription(v string) *Region { - s.Description = &v - return s -} - -// SetDisplayName sets the DisplayName field's value. -func (s *Region) SetDisplayName(v string) *Region { - s.DisplayName = &v - return s -} - -// SetName sets the Name field's value. -func (s *Region) SetName(v string) *Region { - s.Name = &v - return s -} - -type ReleaseStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP to delete. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s ReleaseStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReleaseStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ReleaseStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReleaseStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *ReleaseStaticIpInput) SetStaticIpName(v string) *ReleaseStaticIpInput { - s.StaticIpName = &v - return s -} - -type ReleaseStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s ReleaseStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReleaseStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *ReleaseStaticIpOutput) SetOperations(v []*Operation) *ReleaseStaticIpOutput { - s.Operations = v - return s -} - -// Describes the resource location. -type ResourceLocation struct { - _ struct{} `type:"structure"` - - // The Availability Zone. Follows the format us-east-2a (case-sensitive). - AvailabilityZone *string `locationName:"availabilityZone" type:"string"` - - // The AWS Region name. - RegionName *string `locationName:"regionName" type:"string" enum:"RegionName"` -} - -// String returns the string representation -func (s ResourceLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceLocation) GoString() string { - return s.String() -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *ResourceLocation) SetAvailabilityZone(v string) *ResourceLocation { - s.AvailabilityZone = &v - return s -} - -// SetRegionName sets the RegionName field's value. -func (s *ResourceLocation) SetRegionName(v string) *ResourceLocation { - s.RegionName = &v - return s -} - -type StartInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance (a virtual private server) to start. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s StartInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StartInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StartInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StartInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *StartInstanceInput) SetInstanceName(v string) *StartInstanceInput { - s.InstanceName = &v - return s -} - -type StartInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s StartInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StartInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *StartInstanceOutput) SetOperations(v []*Operation) *StartInstanceOutput { - s.Operations = v - return s -} - -// Describes the static IP. -type StaticIp struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the static IP (e.g., arn:aws:lightsail:us-east-2:123456789101:StaticIp/9cbb4a9e-f8e3-4dfe-b57e-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The instance where the static IP is attached (e.g., Amazon_Linux-1GB-Ohio-1). - AttachedTo *string `locationName:"attachedTo" type:"string"` - - // The timestamp when the static IP was created (e.g., 1479735304.222). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The static IP address. - IpAddress *string `locationName:"ipAddress" type:"string"` - - // A Boolean value indicating whether the static IP is attached. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // The region and Availability Zone where the static IP was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the static IP (e.g., StaticIP-Ohio-EXAMPLE). - Name *string `locationName:"name" type:"string"` - - // The resource type (usually StaticIp). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s StaticIp) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StaticIp) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *StaticIp) SetArn(v string) *StaticIp { - s.Arn = &v - return s -} - -// SetAttachedTo sets the AttachedTo field's value. -func (s *StaticIp) SetAttachedTo(v string) *StaticIp { - s.AttachedTo = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *StaticIp) SetCreatedAt(v time.Time) *StaticIp { - s.CreatedAt = &v - return s -} - -// SetIpAddress sets the IpAddress field's value. -func (s *StaticIp) SetIpAddress(v string) *StaticIp { - s.IpAddress = &v - return s -} - -// SetIsAttached sets the IsAttached field's value. -func (s *StaticIp) SetIsAttached(v bool) *StaticIp { - s.IsAttached = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *StaticIp) SetLocation(v *ResourceLocation) *StaticIp { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *StaticIp) SetName(v string) *StaticIp { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *StaticIp) SetResourceType(v string) *StaticIp { - s.ResourceType = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *StaticIp) SetSupportCode(v string) *StaticIp { - s.SupportCode = &v - return s -} - -type StopInstanceInput struct { - _ struct{} `type:"structure"` - - // When set to True, forces a Lightsail instance that is stuck in a stopping - // state to stop. - // - // Only use the force parameter if your instance is stuck in the stopping state. - // In any other state, your instance should stop normally without adding this - // parameter to your API request. - Force *bool `locationName:"force" type:"boolean"` - - // The name of the instance (a virtual private server) to stop. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s StopInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StopInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StopInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StopInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetForce sets the Force field's value. -func (s *StopInstanceInput) SetForce(v bool) *StopInstanceInput { - s.Force = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *StopInstanceInput) SetInstanceName(v string) *StopInstanceInput { - s.InstanceName = &v - return s -} - -type StopInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s StopInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StopInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *StopInstanceOutput) SetOperations(v []*Operation) *StopInstanceOutput { - s.Operations = v - return s -} - -type UnpeerVpcInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s UnpeerVpcInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UnpeerVpcInput) GoString() string { - return s.String() -} - -type UnpeerVpcOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s UnpeerVpcOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UnpeerVpcOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *UnpeerVpcOutput) SetOperation(v *Operation) *UnpeerVpcOutput { - s.Operation = v - return s -} - -type UpdateDomainEntryInput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the domain entry. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - - // The name of the domain recordset to update. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s UpdateDomainEntryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateDomainEntryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainEntry sets the DomainEntry field's value. -func (s *UpdateDomainEntryInput) SetDomainEntry(v *DomainEntry) *UpdateDomainEntryInput { - s.DomainEntry = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *UpdateDomainEntryInput) SetDomainName(v string) *UpdateDomainEntryInput { - s.DomainName = &v - return s -} - -type UpdateDomainEntryOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s UpdateDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateDomainEntryOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *UpdateDomainEntryOutput) SetOperations(v []*Operation) *UpdateDomainEntryOutput { - s.Operations = v - return s -} - -type UpdateLoadBalancerAttributeInput struct { - _ struct{} `type:"structure"` - - // The name of the attribute you want to update. Valid values are below. - // - // AttributeName is a required field - AttributeName *string `locationName:"attributeName" type:"string" required:"true" enum:"LoadBalancerAttributeName"` - - // The value that you want to specify for the attribute name. - // - // AttributeValue is a required field - AttributeValue *string `locationName:"attributeValue" min:"1" type:"string" required:"true"` - - // The name of the load balancer that you want to modify (e.g., my-load-balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s UpdateLoadBalancerAttributeInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateLoadBalancerAttributeInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateLoadBalancerAttributeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateLoadBalancerAttributeInput"} - if s.AttributeName == nil { - invalidParams.Add(request.NewErrParamRequired("AttributeName")) - } - if s.AttributeValue == nil { - invalidParams.Add(request.NewErrParamRequired("AttributeValue")) - } - if s.AttributeValue != nil && len(*s.AttributeValue) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AttributeValue", 1)) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAttributeName sets the AttributeName field's value. -func (s *UpdateLoadBalancerAttributeInput) SetAttributeName(v string) *UpdateLoadBalancerAttributeInput { - s.AttributeName = &v - return s -} - -// SetAttributeValue sets the AttributeValue field's value. -func (s *UpdateLoadBalancerAttributeInput) SetAttributeValue(v string) *UpdateLoadBalancerAttributeInput { - s.AttributeValue = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *UpdateLoadBalancerAttributeInput) SetLoadBalancerName(v string) *UpdateLoadBalancerAttributeInput { - s.LoadBalancerName = &v - return s -} - -type UpdateLoadBalancerAttributeOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s UpdateLoadBalancerAttributeOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateLoadBalancerAttributeOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *UpdateLoadBalancerAttributeOutput) SetOperations(v []*Operation) *UpdateLoadBalancerAttributeOutput { - s.Operations = v - return s -} - -const ( - // AccessDirectionInbound is a AccessDirection enum value - AccessDirectionInbound = "inbound" - - // AccessDirectionOutbound is a AccessDirection enum value - AccessDirectionOutbound = "outbound" -) - -const ( - // BlueprintTypeOs is a BlueprintType enum value - BlueprintTypeOs = "os" - - // BlueprintTypeApp is a BlueprintType enum value - BlueprintTypeApp = "app" -) - -const ( - // DiskSnapshotStatePending is a DiskSnapshotState enum value - DiskSnapshotStatePending = "pending" - - // DiskSnapshotStateCompleted is a DiskSnapshotState enum value - DiskSnapshotStateCompleted = "completed" - - // DiskSnapshotStateError is a DiskSnapshotState enum value - DiskSnapshotStateError = "error" - - // DiskSnapshotStateUnknown is a DiskSnapshotState enum value - DiskSnapshotStateUnknown = "unknown" -) - -const ( - // DiskStatePending is a DiskState enum value - DiskStatePending = "pending" - - // DiskStateError is a DiskState enum value - DiskStateError = "error" - - // DiskStateAvailable is a DiskState enum value - DiskStateAvailable = "available" - - // DiskStateInUse is a DiskState enum value - DiskStateInUse = "in-use" - - // DiskStateUnknown is a DiskState enum value - DiskStateUnknown = "unknown" -) - -const ( - // InstanceAccessProtocolSsh is a InstanceAccessProtocol enum value - InstanceAccessProtocolSsh = "ssh" - - // InstanceAccessProtocolRdp is a InstanceAccessProtocol enum value - InstanceAccessProtocolRdp = "rdp" -) - -const ( - // InstanceHealthReasonLbRegistrationInProgress is a InstanceHealthReason enum value - InstanceHealthReasonLbRegistrationInProgress = "Lb.RegistrationInProgress" - - // InstanceHealthReasonLbInitialHealthChecking is a InstanceHealthReason enum value - InstanceHealthReasonLbInitialHealthChecking = "Lb.InitialHealthChecking" - - // InstanceHealthReasonLbInternalError is a InstanceHealthReason enum value - InstanceHealthReasonLbInternalError = "Lb.InternalError" - - // InstanceHealthReasonInstanceResponseCodeMismatch is a InstanceHealthReason enum value - InstanceHealthReasonInstanceResponseCodeMismatch = "Instance.ResponseCodeMismatch" - - // InstanceHealthReasonInstanceTimeout is a InstanceHealthReason enum value - InstanceHealthReasonInstanceTimeout = "Instance.Timeout" - - // InstanceHealthReasonInstanceFailedHealthChecks is a InstanceHealthReason enum value - InstanceHealthReasonInstanceFailedHealthChecks = "Instance.FailedHealthChecks" - - // InstanceHealthReasonInstanceNotRegistered is a InstanceHealthReason enum value - InstanceHealthReasonInstanceNotRegistered = "Instance.NotRegistered" - - // InstanceHealthReasonInstanceNotInUse is a InstanceHealthReason enum value - InstanceHealthReasonInstanceNotInUse = "Instance.NotInUse" - - // InstanceHealthReasonInstanceDeregistrationInProgress is a InstanceHealthReason enum value - InstanceHealthReasonInstanceDeregistrationInProgress = "Instance.DeregistrationInProgress" - - // InstanceHealthReasonInstanceInvalidState is a InstanceHealthReason enum value - InstanceHealthReasonInstanceInvalidState = "Instance.InvalidState" - - // InstanceHealthReasonInstanceIpUnusable is a InstanceHealthReason enum value - InstanceHealthReasonInstanceIpUnusable = "Instance.IpUnusable" -) - -const ( - // InstanceHealthStateInitial is a InstanceHealthState enum value - InstanceHealthStateInitial = "initial" - - // InstanceHealthStateHealthy is a InstanceHealthState enum value - InstanceHealthStateHealthy = "healthy" - - // InstanceHealthStateUnhealthy is a InstanceHealthState enum value - InstanceHealthStateUnhealthy = "unhealthy" - - // InstanceHealthStateUnused is a InstanceHealthState enum value - InstanceHealthStateUnused = "unused" - - // InstanceHealthStateDraining is a InstanceHealthState enum value - InstanceHealthStateDraining = "draining" - - // InstanceHealthStateUnavailable is a InstanceHealthState enum value - InstanceHealthStateUnavailable = "unavailable" -) - -const ( - // InstanceMetricNameCpuutilization is a InstanceMetricName enum value - InstanceMetricNameCpuutilization = "CPUUtilization" - - // InstanceMetricNameNetworkIn is a InstanceMetricName enum value - InstanceMetricNameNetworkIn = "NetworkIn" - - // InstanceMetricNameNetworkOut is a InstanceMetricName enum value - InstanceMetricNameNetworkOut = "NetworkOut" - - // InstanceMetricNameStatusCheckFailed is a InstanceMetricName enum value - InstanceMetricNameStatusCheckFailed = "StatusCheckFailed" - - // InstanceMetricNameStatusCheckFailedInstance is a InstanceMetricName enum value - InstanceMetricNameStatusCheckFailedInstance = "StatusCheckFailed_Instance" - - // InstanceMetricNameStatusCheckFailedSystem is a InstanceMetricName enum value - InstanceMetricNameStatusCheckFailedSystem = "StatusCheckFailed_System" -) - -const ( - // InstancePlatformLinuxUnix is a InstancePlatform enum value - InstancePlatformLinuxUnix = "LINUX_UNIX" - - // InstancePlatformWindows is a InstancePlatform enum value - InstancePlatformWindows = "WINDOWS" -) - -const ( - // InstanceSnapshotStatePending is a InstanceSnapshotState enum value - InstanceSnapshotStatePending = "pending" - - // InstanceSnapshotStateError is a InstanceSnapshotState enum value - InstanceSnapshotStateError = "error" - - // InstanceSnapshotStateAvailable is a InstanceSnapshotState enum value - InstanceSnapshotStateAvailable = "available" -) - -const ( - // LoadBalancerAttributeNameHealthCheckPath is a LoadBalancerAttributeName enum value - LoadBalancerAttributeNameHealthCheckPath = "HealthCheckPath" - - // LoadBalancerAttributeNameSessionStickinessEnabled is a LoadBalancerAttributeName enum value - LoadBalancerAttributeNameSessionStickinessEnabled = "SessionStickinessEnabled" - - // LoadBalancerAttributeNameSessionStickinessLbCookieDurationSeconds is a LoadBalancerAttributeName enum value - LoadBalancerAttributeNameSessionStickinessLbCookieDurationSeconds = "SessionStickiness_LB_CookieDurationSeconds" -) - -const ( - // LoadBalancerMetricNameClientTlsnegotiationErrorCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameClientTlsnegotiationErrorCount = "ClientTLSNegotiationErrorCount" - - // LoadBalancerMetricNameHealthyHostCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHealthyHostCount = "HealthyHostCount" - - // LoadBalancerMetricNameUnhealthyHostCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameUnhealthyHostCount = "UnhealthyHostCount" - - // LoadBalancerMetricNameHttpcodeLb4xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeLb4xxCount = "HTTPCode_LB_4XX_Count" - - // LoadBalancerMetricNameHttpcodeLb5xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeLb5xxCount = "HTTPCode_LB_5XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance2xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance2xxCount = "HTTPCode_Instance_2XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance3xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance3xxCount = "HTTPCode_Instance_3XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance4xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance4xxCount = "HTTPCode_Instance_4XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance5xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance5xxCount = "HTTPCode_Instance_5XX_Count" - - // LoadBalancerMetricNameInstanceResponseTime is a LoadBalancerMetricName enum value - LoadBalancerMetricNameInstanceResponseTime = "InstanceResponseTime" - - // LoadBalancerMetricNameRejectedConnectionCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameRejectedConnectionCount = "RejectedConnectionCount" - - // LoadBalancerMetricNameRequestCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameRequestCount = "RequestCount" -) - -const ( - // LoadBalancerProtocolHttpHttps is a LoadBalancerProtocol enum value - LoadBalancerProtocolHttpHttps = "HTTP_HTTPS" - - // LoadBalancerProtocolHttp is a LoadBalancerProtocol enum value - LoadBalancerProtocolHttp = "HTTP" -) - -const ( - // LoadBalancerStateActive is a LoadBalancerState enum value - LoadBalancerStateActive = "active" - - // LoadBalancerStateProvisioning is a LoadBalancerState enum value - LoadBalancerStateProvisioning = "provisioning" - - // LoadBalancerStateActiveImpaired is a LoadBalancerState enum value - LoadBalancerStateActiveImpaired = "active_impaired" - - // LoadBalancerStateFailed is a LoadBalancerState enum value - LoadBalancerStateFailed = "failed" - - // LoadBalancerStateUnknown is a LoadBalancerState enum value - LoadBalancerStateUnknown = "unknown" -) - -const ( - // LoadBalancerTlsCertificateDomainStatusPendingValidation is a LoadBalancerTlsCertificateDomainStatus enum value - LoadBalancerTlsCertificateDomainStatusPendingValidation = "PENDING_VALIDATION" - - // LoadBalancerTlsCertificateDomainStatusFailed is a LoadBalancerTlsCertificateDomainStatus enum value - LoadBalancerTlsCertificateDomainStatusFailed = "FAILED" - - // LoadBalancerTlsCertificateDomainStatusSuccess is a LoadBalancerTlsCertificateDomainStatus enum value - LoadBalancerTlsCertificateDomainStatusSuccess = "SUCCESS" -) - -const ( - // LoadBalancerTlsCertificateFailureReasonNoAvailableContacts is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonNoAvailableContacts = "NO_AVAILABLE_CONTACTS" - - // LoadBalancerTlsCertificateFailureReasonAdditionalVerificationRequired is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonAdditionalVerificationRequired = "ADDITIONAL_VERIFICATION_REQUIRED" - - // LoadBalancerTlsCertificateFailureReasonDomainNotAllowed is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonDomainNotAllowed = "DOMAIN_NOT_ALLOWED" - - // LoadBalancerTlsCertificateFailureReasonInvalidPublicDomain is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonInvalidPublicDomain = "INVALID_PUBLIC_DOMAIN" - - // LoadBalancerTlsCertificateFailureReasonOther is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonOther = "OTHER" -) - -const ( - // LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal = "PENDING_AUTO_RENEWAL" - - // LoadBalancerTlsCertificateRenewalStatusPendingValidation is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusPendingValidation = "PENDING_VALIDATION" - - // LoadBalancerTlsCertificateRenewalStatusSuccess is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusSuccess = "SUCCESS" - - // LoadBalancerTlsCertificateRenewalStatusFailed is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusFailed = "FAILED" -) - -const ( - // LoadBalancerTlsCertificateRevocationReasonUnspecified is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonUnspecified = "UNSPECIFIED" - - // LoadBalancerTlsCertificateRevocationReasonKeyCompromise is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonKeyCompromise = "KEY_COMPROMISE" - - // LoadBalancerTlsCertificateRevocationReasonCaCompromise is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonCaCompromise = "CA_COMPROMISE" - - // LoadBalancerTlsCertificateRevocationReasonAffiliationChanged is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonAffiliationChanged = "AFFILIATION_CHANGED" - - // LoadBalancerTlsCertificateRevocationReasonSuperceded is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonSuperceded = "SUPERCEDED" - - // LoadBalancerTlsCertificateRevocationReasonCessationOfOperation is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonCessationOfOperation = "CESSATION_OF_OPERATION" - - // LoadBalancerTlsCertificateRevocationReasonCertificateHold is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonCertificateHold = "CERTIFICATE_HOLD" - - // LoadBalancerTlsCertificateRevocationReasonRemoveFromCrl is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonRemoveFromCrl = "REMOVE_FROM_CRL" - - // LoadBalancerTlsCertificateRevocationReasonPrivilegeWithdrawn is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonPrivilegeWithdrawn = "PRIVILEGE_WITHDRAWN" - - // LoadBalancerTlsCertificateRevocationReasonAACompromise is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonAACompromise = "A_A_COMPROMISE" -) - -const ( - // LoadBalancerTlsCertificateStatusPendingValidation is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusPendingValidation = "PENDING_VALIDATION" - - // LoadBalancerTlsCertificateStatusIssued is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusIssued = "ISSUED" - - // LoadBalancerTlsCertificateStatusInactive is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusInactive = "INACTIVE" - - // LoadBalancerTlsCertificateStatusExpired is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusExpired = "EXPIRED" - - // LoadBalancerTlsCertificateStatusValidationTimedOut is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusValidationTimedOut = "VALIDATION_TIMED_OUT" - - // LoadBalancerTlsCertificateStatusRevoked is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusRevoked = "REVOKED" - - // LoadBalancerTlsCertificateStatusFailed is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusFailed = "FAILED" - - // LoadBalancerTlsCertificateStatusUnknown is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusUnknown = "UNKNOWN" -) - -const ( - // MetricStatisticMinimum is a MetricStatistic enum value - MetricStatisticMinimum = "Minimum" - - // MetricStatisticMaximum is a MetricStatistic enum value - MetricStatisticMaximum = "Maximum" - - // MetricStatisticSum is a MetricStatistic enum value - MetricStatisticSum = "Sum" - - // MetricStatisticAverage is a MetricStatistic enum value - MetricStatisticAverage = "Average" - - // MetricStatisticSampleCount is a MetricStatistic enum value - MetricStatisticSampleCount = "SampleCount" -) - -const ( - // MetricUnitSeconds is a MetricUnit enum value - MetricUnitSeconds = "Seconds" - - // MetricUnitMicroseconds is a MetricUnit enum value - MetricUnitMicroseconds = "Microseconds" - - // MetricUnitMilliseconds is a MetricUnit enum value - MetricUnitMilliseconds = "Milliseconds" - - // MetricUnitBytes is a MetricUnit enum value - MetricUnitBytes = "Bytes" - - // MetricUnitKilobytes is a MetricUnit enum value - MetricUnitKilobytes = "Kilobytes" - - // MetricUnitMegabytes is a MetricUnit enum value - MetricUnitMegabytes = "Megabytes" - - // MetricUnitGigabytes is a MetricUnit enum value - MetricUnitGigabytes = "Gigabytes" - - // MetricUnitTerabytes is a MetricUnit enum value - MetricUnitTerabytes = "Terabytes" - - // MetricUnitBits is a MetricUnit enum value - MetricUnitBits = "Bits" - - // MetricUnitKilobits is a MetricUnit enum value - MetricUnitKilobits = "Kilobits" - - // MetricUnitMegabits is a MetricUnit enum value - MetricUnitMegabits = "Megabits" - - // MetricUnitGigabits is a MetricUnit enum value - MetricUnitGigabits = "Gigabits" - - // MetricUnitTerabits is a MetricUnit enum value - MetricUnitTerabits = "Terabits" - - // MetricUnitPercent is a MetricUnit enum value - MetricUnitPercent = "Percent" - - // MetricUnitCount is a MetricUnit enum value - MetricUnitCount = "Count" - - // MetricUnitBytesSecond is a MetricUnit enum value - MetricUnitBytesSecond = "Bytes/Second" - - // MetricUnitKilobytesSecond is a MetricUnit enum value - MetricUnitKilobytesSecond = "Kilobytes/Second" - - // MetricUnitMegabytesSecond is a MetricUnit enum value - MetricUnitMegabytesSecond = "Megabytes/Second" - - // MetricUnitGigabytesSecond is a MetricUnit enum value - MetricUnitGigabytesSecond = "Gigabytes/Second" - - // MetricUnitTerabytesSecond is a MetricUnit enum value - MetricUnitTerabytesSecond = "Terabytes/Second" - - // MetricUnitBitsSecond is a MetricUnit enum value - MetricUnitBitsSecond = "Bits/Second" - - // MetricUnitKilobitsSecond is a MetricUnit enum value - MetricUnitKilobitsSecond = "Kilobits/Second" - - // MetricUnitMegabitsSecond is a MetricUnit enum value - MetricUnitMegabitsSecond = "Megabits/Second" - - // MetricUnitGigabitsSecond is a MetricUnit enum value - MetricUnitGigabitsSecond = "Gigabits/Second" - - // MetricUnitTerabitsSecond is a MetricUnit enum value - MetricUnitTerabitsSecond = "Terabits/Second" - - // MetricUnitCountSecond is a MetricUnit enum value - MetricUnitCountSecond = "Count/Second" - - // MetricUnitNone is a MetricUnit enum value - MetricUnitNone = "None" -) - -const ( - // NetworkProtocolTcp is a NetworkProtocol enum value - NetworkProtocolTcp = "tcp" - - // NetworkProtocolAll is a NetworkProtocol enum value - NetworkProtocolAll = "all" - - // NetworkProtocolUdp is a NetworkProtocol enum value - NetworkProtocolUdp = "udp" -) - -const ( - // OperationStatusNotStarted is a OperationStatus enum value - OperationStatusNotStarted = "NotStarted" - - // OperationStatusStarted is a OperationStatus enum value - OperationStatusStarted = "Started" - - // OperationStatusFailed is a OperationStatus enum value - OperationStatusFailed = "Failed" - - // OperationStatusCompleted is a OperationStatus enum value - OperationStatusCompleted = "Completed" - - // OperationStatusSucceeded is a OperationStatus enum value - OperationStatusSucceeded = "Succeeded" -) - -const ( - // OperationTypeDeleteInstance is a OperationType enum value - OperationTypeDeleteInstance = "DeleteInstance" - - // OperationTypeCreateInstance is a OperationType enum value - OperationTypeCreateInstance = "CreateInstance" - - // OperationTypeStopInstance is a OperationType enum value - OperationTypeStopInstance = "StopInstance" - - // OperationTypeStartInstance is a OperationType enum value - OperationTypeStartInstance = "StartInstance" - - // OperationTypeRebootInstance is a OperationType enum value - OperationTypeRebootInstance = "RebootInstance" - - // OperationTypeOpenInstancePublicPorts is a OperationType enum value - OperationTypeOpenInstancePublicPorts = "OpenInstancePublicPorts" - - // OperationTypePutInstancePublicPorts is a OperationType enum value - OperationTypePutInstancePublicPorts = "PutInstancePublicPorts" - - // OperationTypeCloseInstancePublicPorts is a OperationType enum value - OperationTypeCloseInstancePublicPorts = "CloseInstancePublicPorts" - - // OperationTypeAllocateStaticIp is a OperationType enum value - OperationTypeAllocateStaticIp = "AllocateStaticIp" - - // OperationTypeReleaseStaticIp is a OperationType enum value - OperationTypeReleaseStaticIp = "ReleaseStaticIp" - - // OperationTypeAttachStaticIp is a OperationType enum value - OperationTypeAttachStaticIp = "AttachStaticIp" - - // OperationTypeDetachStaticIp is a OperationType enum value - OperationTypeDetachStaticIp = "DetachStaticIp" - - // OperationTypeUpdateDomainEntry is a OperationType enum value - OperationTypeUpdateDomainEntry = "UpdateDomainEntry" - - // OperationTypeDeleteDomainEntry is a OperationType enum value - OperationTypeDeleteDomainEntry = "DeleteDomainEntry" - - // OperationTypeCreateDomain is a OperationType enum value - OperationTypeCreateDomain = "CreateDomain" - - // OperationTypeDeleteDomain is a OperationType enum value - OperationTypeDeleteDomain = "DeleteDomain" - - // OperationTypeCreateInstanceSnapshot is a OperationType enum value - OperationTypeCreateInstanceSnapshot = "CreateInstanceSnapshot" - - // OperationTypeDeleteInstanceSnapshot is a OperationType enum value - OperationTypeDeleteInstanceSnapshot = "DeleteInstanceSnapshot" - - // OperationTypeCreateInstancesFromSnapshot is a OperationType enum value - OperationTypeCreateInstancesFromSnapshot = "CreateInstancesFromSnapshot" - - // OperationTypeCreateLoadBalancer is a OperationType enum value - OperationTypeCreateLoadBalancer = "CreateLoadBalancer" - - // OperationTypeDeleteLoadBalancer is a OperationType enum value - OperationTypeDeleteLoadBalancer = "DeleteLoadBalancer" - - // OperationTypeAttachInstancesToLoadBalancer is a OperationType enum value - OperationTypeAttachInstancesToLoadBalancer = "AttachInstancesToLoadBalancer" - - // OperationTypeDetachInstancesFromLoadBalancer is a OperationType enum value - OperationTypeDetachInstancesFromLoadBalancer = "DetachInstancesFromLoadBalancer" - - // OperationTypeUpdateLoadBalancerAttribute is a OperationType enum value - OperationTypeUpdateLoadBalancerAttribute = "UpdateLoadBalancerAttribute" - - // OperationTypeCreateLoadBalancerTlsCertificate is a OperationType enum value - OperationTypeCreateLoadBalancerTlsCertificate = "CreateLoadBalancerTlsCertificate" - - // OperationTypeDeleteLoadBalancerTlsCertificate is a OperationType enum value - OperationTypeDeleteLoadBalancerTlsCertificate = "DeleteLoadBalancerTlsCertificate" - - // OperationTypeAttachLoadBalancerTlsCertificate is a OperationType enum value - OperationTypeAttachLoadBalancerTlsCertificate = "AttachLoadBalancerTlsCertificate" - - // OperationTypeCreateDisk is a OperationType enum value - OperationTypeCreateDisk = "CreateDisk" - - // OperationTypeDeleteDisk is a OperationType enum value - OperationTypeDeleteDisk = "DeleteDisk" - - // OperationTypeAttachDisk is a OperationType enum value - OperationTypeAttachDisk = "AttachDisk" - - // OperationTypeDetachDisk is a OperationType enum value - OperationTypeDetachDisk = "DetachDisk" - - // OperationTypeCreateDiskSnapshot is a OperationType enum value - OperationTypeCreateDiskSnapshot = "CreateDiskSnapshot" - - // OperationTypeDeleteDiskSnapshot is a OperationType enum value - OperationTypeDeleteDiskSnapshot = "DeleteDiskSnapshot" - - // OperationTypeCreateDiskFromSnapshot is a OperationType enum value - OperationTypeCreateDiskFromSnapshot = "CreateDiskFromSnapshot" -) - -const ( - // PortAccessTypePublic is a PortAccessType enum value - PortAccessTypePublic = "Public" - - // PortAccessTypePrivate is a PortAccessType enum value - PortAccessTypePrivate = "Private" -) - -const ( - // PortStateOpen is a PortState enum value - PortStateOpen = "open" - - // PortStateClosed is a PortState enum value - PortStateClosed = "closed" -) - -const ( - // RegionNameUsEast1 is a RegionName enum value - RegionNameUsEast1 = "us-east-1" - - // RegionNameUsEast2 is a RegionName enum value - RegionNameUsEast2 = "us-east-2" - - // RegionNameUsWest1 is a RegionName enum value - RegionNameUsWest1 = "us-west-1" - - // RegionNameUsWest2 is a RegionName enum value - RegionNameUsWest2 = "us-west-2" - - // RegionNameEuCentral1 is a RegionName enum value - RegionNameEuCentral1 = "eu-central-1" - - // RegionNameEuWest1 is a RegionName enum value - RegionNameEuWest1 = "eu-west-1" - - // RegionNameEuWest2 is a RegionName enum value - RegionNameEuWest2 = "eu-west-2" - - // RegionNameApSouth1 is a RegionName enum value - RegionNameApSouth1 = "ap-south-1" - - // RegionNameApSoutheast1 is a RegionName enum value - RegionNameApSoutheast1 = "ap-southeast-1" - - // RegionNameApSoutheast2 is a RegionName enum value - RegionNameApSoutheast2 = "ap-southeast-2" - - // RegionNameApNortheast1 is a RegionName enum value - RegionNameApNortheast1 = "ap-northeast-1" - - // RegionNameApNortheast2 is a RegionName enum value - RegionNameApNortheast2 = "ap-northeast-2" -) - -const ( - // ResourceTypeInstance is a ResourceType enum value - ResourceTypeInstance = "Instance" - - // ResourceTypeStaticIp is a ResourceType enum value - ResourceTypeStaticIp = "StaticIp" - - // ResourceTypeKeyPair is a ResourceType enum value - ResourceTypeKeyPair = "KeyPair" - - // ResourceTypeInstanceSnapshot is a ResourceType enum value - ResourceTypeInstanceSnapshot = "InstanceSnapshot" - - // ResourceTypeDomain is a ResourceType enum value - ResourceTypeDomain = "Domain" - - // ResourceTypePeeredVpc is a ResourceType enum value - ResourceTypePeeredVpc = "PeeredVpc" - - // ResourceTypeLoadBalancer is a ResourceType enum value - ResourceTypeLoadBalancer = "LoadBalancer" - - // ResourceTypeLoadBalancerTlsCertificate is a ResourceType enum value - ResourceTypeLoadBalancerTlsCertificate = "LoadBalancerTlsCertificate" - - // ResourceTypeDisk is a ResourceType enum value - ResourceTypeDisk = "Disk" - - // ResourceTypeDiskSnapshot is a ResourceType enum value - ResourceTypeDiskSnapshot = "DiskSnapshot" -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go deleted file mode 100644 index 9c52815..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package lightsail provides the client and types for making API -// requests to Amazon Lightsail. -// -// Amazon Lightsail is the easiest way to get started with AWS for developers -// who just need virtual private servers. Lightsail includes everything you -// need to launch your project quickly - a virtual machine, SSD-based storage, -// data transfer, DNS management, and a static IP - for a low, predictable price. -// You manage those Lightsail servers through the Lightsail console or by using -// the API or command-line interface (CLI). -// -// For more information about Lightsail concepts and tasks, see the Lightsail -// Dev Guide (https://lightsail.aws.amazon.com/ls/docs/all). -// -// To use the Lightsail API or the CLI, you will need to use AWS Identity and -// Access Management (IAM) to generate access keys. For details about how to -// set this up, see the Lightsail Dev Guide (http://lightsail.aws.amazon.com/ls/docs/how-to/article/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli). -// -// See https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28 for more information on this service. -// -// See lightsail package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/lightsail/ -// -// Using the Client -// -// To contact Amazon Lightsail with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the Amazon Lightsail client Lightsail for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/lightsail/#New -package lightsail diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go deleted file mode 100644 index bda8b8a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package lightsail - -const ( - - // ErrCodeAccessDeniedException for service response error code - // "AccessDeniedException". - // - // Lightsail throws this exception when the user cannot be authenticated or - // uses invalid credentials to access a resource. - ErrCodeAccessDeniedException = "AccessDeniedException" - - // ErrCodeAccountSetupInProgressException for service response error code - // "AccountSetupInProgressException". - // - // Lightsail throws this exception when an account is still in the setup in - // progress state. - ErrCodeAccountSetupInProgressException = "AccountSetupInProgressException" - - // ErrCodeInvalidInputException for service response error code - // "InvalidInputException". - // - // Lightsail throws this exception when user input does not conform to the validation - // rules of an input field. - // - // Domain-related APIs are only available in the N. Virginia (us-east-1) Region. - // Please set your AWS Region configuration to us-east-1 to create, view, or - // edit these resources. - ErrCodeInvalidInputException = "InvalidInputException" - - // ErrCodeNotFoundException for service response error code - // "NotFoundException". - // - // Lightsail throws this exception when it cannot find a resource. - ErrCodeNotFoundException = "NotFoundException" - - // ErrCodeOperationFailureException for service response error code - // "OperationFailureException". - // - // Lightsail throws this exception when an operation fails to execute. - ErrCodeOperationFailureException = "OperationFailureException" - - // ErrCodeServiceException for service response error code - // "ServiceException". - // - // A general service exception. - ErrCodeServiceException = "ServiceException" - - // ErrCodeUnauthenticatedException for service response error code - // "UnauthenticatedException". - // - // Lightsail throws this exception when the user has not been authenticated. - ErrCodeUnauthenticatedException = "UnauthenticatedException" -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go deleted file mode 100644 index b9f97fa..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go +++ /dev/null @@ -1,97 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package lightsail - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" -) - -// Lightsail provides the API operation methods for making requests to -// Amazon Lightsail. See this package's package overview docs -// for details on the service. -// -// Lightsail methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type Lightsail struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "lightsail" // Name of service. - EndpointsID = ServiceName // ID to lookup a service endpoint with. - ServiceID = "Lightsail" // ServiceID is a unique identifer of a specific service. -) - -// New creates a new instance of the Lightsail client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a Lightsail client from just a session. -// svc := lightsail.New(mySession) -// -// // Create a Lightsail client with additional configuration -// svc := lightsail.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *Lightsail { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Lightsail { - svc := &Lightsail{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2016-11-28", - JSONVersion: "1.1", - TargetPrefix: "Lightsail_20161128", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a Lightsail operation and runs any -// custom request initialization. -func (c *Lightsail) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/api.go deleted file mode 100644 index 97351a7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/api.go +++ /dev/null @@ -1,14969 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAssociateVPCWithHostedZone = "AssociateVPCWithHostedZone" - -// AssociateVPCWithHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the AssociateVPCWithHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssociateVPCWithHostedZone for more information on using the AssociateVPCWithHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssociateVPCWithHostedZoneRequest method. -// req, resp := client.AssociateVPCWithHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/AssociateVPCWithHostedZone -func (c *Route53) AssociateVPCWithHostedZoneRequest(input *AssociateVPCWithHostedZoneInput) (req *request.Request, output *AssociateVPCWithHostedZoneOutput) { - op := &request.Operation{ - Name: opAssociateVPCWithHostedZone, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/associatevpc", - } - - if input == nil { - input = &AssociateVPCWithHostedZoneInput{} - } - - output = &AssociateVPCWithHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssociateVPCWithHostedZone API operation for Amazon Route 53. -// -// Associates an Amazon VPC with a private hosted zone. -// -// To perform the association, the VPC and the private hosted zone must already -// exist. You can't convert a public hosted zone into a private hosted zone. -// -// If you want to associate a VPC that was created by using one AWS account -// with a private hosted zone that was created by using a different account, -// the AWS account that created the private hosted zone must first submit a -// CreateVPCAssociationAuthorization request. Then the account that created -// the VPC must submit an AssociateVPCWithHostedZone request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation AssociateVPCWithHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeNotAuthorizedException "NotAuthorizedException" -// Associating the specified VPC with the specified hosted zone has not been -// authorized. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodePublicZoneVPCAssociation "PublicZoneVPCAssociation" -// You're trying to associate a VPC with a public hosted zone. Amazon Route -// 53 doesn't support associating a VPC with a public hosted zone. -// -// * ErrCodeConflictingDomainExists "ConflictingDomainExists" -// The cause of this error depends on whether you're trying to create a public -// or a private hosted zone: -// -// * Public hosted zone: Two hosted zones that have the same name or that -// have a parent/child relationship (example.com and test.example.com) can't -// have any common name servers. You tried to create a hosted zone that has -// the same name as an existing hosted zone or that's the parent or child -// of an existing hosted zone, and you specified a delegation set that shares -// one or more name servers with the existing hosted zone. For more information, -// see CreateReusableDelegationSet. -// -// * Private hosted zone: You specified an Amazon VPC that you're already -// using for another hosted zone, and the domain that you specified for one -// of the hosted zones is a subdomain of the domain that you specified for -// the other hosted zone. For example, you can't use the same Amazon VPC -// for the hosted zones for example.com and test.example.com. -// -// * ErrCodeLimitsExceeded "LimitsExceeded" -// This operation can't be completed either because the current account has -// reached the limit on reusable delegation sets that it can create or because -// you've reached the limit on the number of Amazon VPCs that you can associate -// with a private hosted zone. To get the current limit on the number of reusable -// delegation sets, see GetAccountLimit. To get the current limit on the number -// of Amazon VPCs that you can associate with a private hosted zone, see GetHostedZoneLimit. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/AssociateVPCWithHostedZone -func (c *Route53) AssociateVPCWithHostedZone(input *AssociateVPCWithHostedZoneInput) (*AssociateVPCWithHostedZoneOutput, error) { - req, out := c.AssociateVPCWithHostedZoneRequest(input) - return out, req.Send() -} - -// AssociateVPCWithHostedZoneWithContext is the same as AssociateVPCWithHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See AssociateVPCWithHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) AssociateVPCWithHostedZoneWithContext(ctx aws.Context, input *AssociateVPCWithHostedZoneInput, opts ...request.Option) (*AssociateVPCWithHostedZoneOutput, error) { - req, out := c.AssociateVPCWithHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opChangeResourceRecordSets = "ChangeResourceRecordSets" - -// ChangeResourceRecordSetsRequest generates a "aws/request.Request" representing the -// client's request for the ChangeResourceRecordSets operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ChangeResourceRecordSets for more information on using the ChangeResourceRecordSets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ChangeResourceRecordSetsRequest method. -// req, resp := client.ChangeResourceRecordSetsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeResourceRecordSets -func (c *Route53) ChangeResourceRecordSetsRequest(input *ChangeResourceRecordSetsInput) (req *request.Request, output *ChangeResourceRecordSetsOutput) { - op := &request.Operation{ - Name: opChangeResourceRecordSets, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/rrset/", - } - - if input == nil { - input = &ChangeResourceRecordSetsInput{} - } - - output = &ChangeResourceRecordSetsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ChangeResourceRecordSets API operation for Amazon Route 53. -// -// Creates, changes, or deletes a resource record set, which contains authoritative -// DNS information for a specified domain name or subdomain name. For example, -// you can use ChangeResourceRecordSets to create a resource record set that -// routes traffic for test.example.com to a web server that has an IP address -// of 192.0.2.44. -// -// Change Batches and Transactional Changes -// -// The request body must include a document with a ChangeResourceRecordSetsRequest -// element. The request body contains a list of change items, known as a change -// batch. Change batches are considered transactional changes. When using the -// Amazon Route 53 API to change resource record sets, Amazon Route 53 either -// makes all or none of the changes in a change batch request. This ensures -// that Amazon Route 53 never partially implements the intended changes to the -// resource record sets in a hosted zone. -// -// For example, a change batch request that deletes the CNAME record for www.example.com -// and creates an alias resource record set for www.example.com. Amazon Route -// 53 deletes the first resource record set and creates the second resource -// record set in a single operation. If either the DELETE or the CREATE action -// fails, then both changes (plus any other changes in the batch) fail, and -// the original CNAME record continues to exist. -// -// Due to the nature of transactional changes, you can't delete the same resource -// record set more than once in a single change batch. If you attempt to delete -// the same change batch more than once, Amazon Route 53 returns an InvalidChangeBatch -// error. -// -// Traffic Flow -// -// To create resource record sets for complex routing configurations, use either -// the traffic flow visual editor in the Amazon Route 53 console or the API -// actions for traffic policies and traffic policy instances. Save the configuration -// as a traffic policy, then associate the traffic policy with one or more domain -// names (such as example.com) or subdomain names (such as www.example.com), -// in the same hosted zone or in multiple hosted zones. You can roll back the -// updates if the new configuration isn't performing as expected. For more information, -// see Using Traffic Flow to Route DNS Traffic (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/traffic-flow.html) -// in the Amazon Route 53 Developer Guide. -// -// Create, Delete, and Upsert -// -// Use ChangeResourceRecordsSetsRequest to perform the following actions: -// -// * CREATE: Creates a resource record set that has the specified values. -// -// * DELETE: Deletes an existing resource record set that has the specified -// values. -// -// * UPSERT: If a resource record set does not already exist, AWS creates -// it. If a resource set does exist, Amazon Route 53 updates it with the -// values in the request. -// -// Syntaxes for Creating, Updating, and Deleting Resource Record Sets -// -// The syntax for a request depends on the type of resource record set that -// you want to create, delete, or update, such as weighted, alias, or failover. -// The XML elements in your request must appear in the order listed in the syntax. -// -// For an example for each type of resource record set, see "Examples." -// -// Don't refer to the syntax in the "Parameter Syntax" section, which includes -// all of the elements for every kind of resource record set that you can create, -// delete, or update by using ChangeResourceRecordSets. -// -// Change Propagation to Amazon Route 53 DNS Servers -// -// When you submit a ChangeResourceRecordSets request, Amazon Route 53 propagates -// your changes to all of the Amazon Route 53 authoritative DNS servers. While -// your changes are propagating, GetChange returns a status of PENDING. When -// propagation is complete, GetChange returns a status of INSYNC. Changes generally -// propagate to all Amazon Route 53 name servers within 60 seconds. For more -// information, see GetChange. -// -// Limits on ChangeResourceRecordSets Requests -// -// For information about the limits on a ChangeResourceRecordSets request, see -// Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ChangeResourceRecordSets for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidChangeBatch "InvalidChangeBatch" -// This exception contains a list of messages that might contain one or more -// error messages. Each error message indicates one error in the change batch. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeResourceRecordSets -func (c *Route53) ChangeResourceRecordSets(input *ChangeResourceRecordSetsInput) (*ChangeResourceRecordSetsOutput, error) { - req, out := c.ChangeResourceRecordSetsRequest(input) - return out, req.Send() -} - -// ChangeResourceRecordSetsWithContext is the same as ChangeResourceRecordSets with the addition of -// the ability to pass a context and additional request options. -// -// See ChangeResourceRecordSets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ChangeResourceRecordSetsWithContext(ctx aws.Context, input *ChangeResourceRecordSetsInput, opts ...request.Option) (*ChangeResourceRecordSetsOutput, error) { - req, out := c.ChangeResourceRecordSetsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opChangeTagsForResource = "ChangeTagsForResource" - -// ChangeTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ChangeTagsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ChangeTagsForResource for more information on using the ChangeTagsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ChangeTagsForResourceRequest method. -// req, resp := client.ChangeTagsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeTagsForResource -func (c *Route53) ChangeTagsForResourceRequest(input *ChangeTagsForResourceInput) (req *request.Request, output *ChangeTagsForResourceOutput) { - op := &request.Operation{ - Name: opChangeTagsForResource, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/tags/{ResourceType}/{ResourceId}", - } - - if input == nil { - input = &ChangeTagsForResourceInput{} - } - - output = &ChangeTagsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// ChangeTagsForResource API operation for Amazon Route 53. -// -// Adds, edits, or deletes tags for a health check or a hosted zone. -// -// For information about using tags for cost allocation, see Using Cost Allocation -// Tags (http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) -// in the AWS Billing and Cost Management User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ChangeTagsForResource for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeThrottlingException "ThrottlingException" -// The limit on the number of requests per second was exceeded. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeTagsForResource -func (c *Route53) ChangeTagsForResource(input *ChangeTagsForResourceInput) (*ChangeTagsForResourceOutput, error) { - req, out := c.ChangeTagsForResourceRequest(input) - return out, req.Send() -} - -// ChangeTagsForResourceWithContext is the same as ChangeTagsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See ChangeTagsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ChangeTagsForResourceWithContext(ctx aws.Context, input *ChangeTagsForResourceInput, opts ...request.Option) (*ChangeTagsForResourceOutput, error) { - req, out := c.ChangeTagsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateHealthCheck = "CreateHealthCheck" - -// CreateHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the CreateHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateHealthCheck for more information on using the CreateHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateHealthCheckRequest method. -// req, resp := client.CreateHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHealthCheck -func (c *Route53) CreateHealthCheckRequest(input *CreateHealthCheckInput) (req *request.Request, output *CreateHealthCheckOutput) { - op := &request.Operation{ - Name: opCreateHealthCheck, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/healthcheck", - } - - if input == nil { - input = &CreateHealthCheckInput{} - } - - output = &CreateHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateHealthCheck API operation for Amazon Route 53. -// -// Creates a new health check. -// -// For information about adding health checks to resource record sets, see ResourceRecordSet$HealthCheckId -// in ChangeResourceRecordSets. -// -// ELB Load Balancers -// -// If you're registering EC2 instances with an Elastic Load Balancing (ELB) -// load balancer, do not create Amazon Route 53 health checks for the EC2 instances. -// When you register an EC2 instance with a load balancer, you configure settings -// for an ELB health check, which performs a similar function to an Amazon Route -// 53 health check. -// -// Private Hosted Zones -// -// You can associate health checks with failover resource record sets in a private -// hosted zone. Note the following: -// -// * Amazon Route 53 health checkers are outside the VPC. To check the health -// of an endpoint within a VPC by IP address, you must assign a public IP -// address to the instance in the VPC. -// -// * You can configure a health checker to check the health of an external -// resource that the instance relies on, such as a database server. -// -// * You can create a CloudWatch metric, associate an alarm with the metric, -// and then create a health check that is based on the state of the alarm. -// For example, you might create a CloudWatch metric that checks the status -// of the Amazon EC2 StatusCheckFailed metric, add an alarm to the metric, -// and then create a health check that is based on the state of the alarm. -// For information about creating CloudWatch metrics and alarms by using -// the CloudWatch console, see the Amazon CloudWatch User Guide (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatch.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeTooManyHealthChecks "TooManyHealthChecks" -// This health check can't be created because the current account has reached -// the limit on the number of active health checks. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// For information about how to get the current limit for an account, see GetAccountLimit. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// You have reached the maximum number of active health checks for an AWS account. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeHealthCheckAlreadyExists "HealthCheckAlreadyExists" -// The health check you're attempting to create already exists. Amazon Route -// 53 returns this error when you submit a request that has the following values: -// -// * The same value for CallerReference as an existing health check, and -// one or more values that differ from the existing health check that has -// the same caller reference. -// -// * The same value for CallerReference as a health check that you created -// and later deleted, regardless of the other settings in the request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHealthCheck -func (c *Route53) CreateHealthCheck(input *CreateHealthCheckInput) (*CreateHealthCheckOutput, error) { - req, out := c.CreateHealthCheckRequest(input) - return out, req.Send() -} - -// CreateHealthCheckWithContext is the same as CreateHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See CreateHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateHealthCheckWithContext(ctx aws.Context, input *CreateHealthCheckInput, opts ...request.Option) (*CreateHealthCheckOutput, error) { - req, out := c.CreateHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateHostedZone = "CreateHostedZone" - -// CreateHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the CreateHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateHostedZone for more information on using the CreateHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateHostedZoneRequest method. -// req, resp := client.CreateHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHostedZone -func (c *Route53) CreateHostedZoneRequest(input *CreateHostedZoneInput) (req *request.Request, output *CreateHostedZoneOutput) { - op := &request.Operation{ - Name: opCreateHostedZone, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone", - } - - if input == nil { - input = &CreateHostedZoneInput{} - } - - output = &CreateHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateHostedZone API operation for Amazon Route 53. -// -// Creates a new public hosted zone, which you use to specify how the Domain -// Name System (DNS) routes traffic on the Internet for a domain, such as example.com, -// and its subdomains. -// -// You can't convert a public hosted zones to a private hosted zone or vice -// versa. Instead, you must create a new hosted zone with the same name and -// create new resource record sets. -// -// For more information about charges for hosted zones, see Amazon Route 53 -// Pricing (http://aws.amazon.com/route53/pricing/). -// -// Note the following: -// -// * You can't create a hosted zone for a top-level domain (TLD). -// -// * Amazon Route 53 automatically creates a default SOA record and four -// NS records for the zone. For more information about SOA and NS records, -// see NS and SOA Records that Amazon Route 53 Creates for a Hosted Zone -// (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/SOA-NSrecords.html) -// in the Amazon Route 53 Developer Guide. -// -// If you want to use the same name servers for multiple hosted zones, you can -// optionally associate a reusable delegation set with the hosted zone. See -// the DelegationSetId element. -// -// * If your domain is registered with a registrar other than Amazon Route -// 53, you must update the name servers with your registrar to make Amazon -// Route 53 your DNS service. For more information, see Configuring Amazon -// Route 53 as your DNS Service (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/creating-migrating.html) -// in the Amazon Route 53 Developer Guide. -// -// When you submit a CreateHostedZone request, the initial status of the hosted -// zone is PENDING. This means that the NS and SOA records are not yet available -// on all Amazon Route 53 DNS servers. When the NS and SOA records are available, -// the status of the zone changes to INSYNC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidDomainName "InvalidDomainName" -// The specified domain name is not valid. -// -// * ErrCodeHostedZoneAlreadyExists "HostedZoneAlreadyExists" -// The hosted zone you're trying to create already exists. Amazon Route 53 returns -// this error when a hosted zone has already been created with the specified -// CallerReference. -// -// * ErrCodeTooManyHostedZones "TooManyHostedZones" -// This operation can't be completed either because the current account has -// reached the limit on the number of hosted zones or because you've reached -// the limit on the number of hosted zones that can be associated with a reusable -// delegation set. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// To get the current limit on hosted zones that can be created by an account, -// see GetAccountLimit. -// -// To get the current limit on hosted zones that can be associated with a reusable -// delegation set, see GetReusableDelegationSetLimit. -// -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeDelegationSetNotAvailable "DelegationSetNotAvailable" -// You can create a hosted zone that has the same name as an existing hosted -// zone (example.com is common), but there is a limit to the number of hosted -// zones that have the same name. If you get this error, Amazon Route 53 has -// reached that limit. If you own the domain name and Amazon Route 53 generates -// this error, contact Customer Support. -// -// * ErrCodeConflictingDomainExists "ConflictingDomainExists" -// The cause of this error depends on whether you're trying to create a public -// or a private hosted zone: -// -// * Public hosted zone: Two hosted zones that have the same name or that -// have a parent/child relationship (example.com and test.example.com) can't -// have any common name servers. You tried to create a hosted zone that has -// the same name as an existing hosted zone or that's the parent or child -// of an existing hosted zone, and you specified a delegation set that shares -// one or more name servers with the existing hosted zone. For more information, -// see CreateReusableDelegationSet. -// -// * Private hosted zone: You specified an Amazon VPC that you're already -// using for another hosted zone, and the domain that you specified for one -// of the hosted zones is a subdomain of the domain that you specified for -// the other hosted zone. For example, you can't use the same Amazon VPC -// for the hosted zones for example.com and test.example.com. -// -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHostedZone -func (c *Route53) CreateHostedZone(input *CreateHostedZoneInput) (*CreateHostedZoneOutput, error) { - req, out := c.CreateHostedZoneRequest(input) - return out, req.Send() -} - -// CreateHostedZoneWithContext is the same as CreateHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See CreateHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateHostedZoneWithContext(ctx aws.Context, input *CreateHostedZoneInput, opts ...request.Option) (*CreateHostedZoneOutput, error) { - req, out := c.CreateHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateQueryLoggingConfig = "CreateQueryLoggingConfig" - -// CreateQueryLoggingConfigRequest generates a "aws/request.Request" representing the -// client's request for the CreateQueryLoggingConfig operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateQueryLoggingConfig for more information on using the CreateQueryLoggingConfig -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateQueryLoggingConfigRequest method. -// req, resp := client.CreateQueryLoggingConfigRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateQueryLoggingConfig -func (c *Route53) CreateQueryLoggingConfigRequest(input *CreateQueryLoggingConfigInput) (req *request.Request, output *CreateQueryLoggingConfigOutput) { - op := &request.Operation{ - Name: opCreateQueryLoggingConfig, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/queryloggingconfig", - } - - if input == nil { - input = &CreateQueryLoggingConfigInput{} - } - - output = &CreateQueryLoggingConfigOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateQueryLoggingConfig API operation for Amazon Route 53. -// -// Creates a configuration for DNS query logging. After you create a query logging -// configuration, Amazon Route 53 begins to publish log data to an Amazon CloudWatch -// Logs log group. -// -// DNS query logs contain information about the queries that Amazon Route 53 -// receives for a specified public hosted zone, such as the following: -// -// * Amazon Route 53 edge location that responded to the DNS query -// -// * Domain or subdomain that was requested -// -// * DNS record type, such as A or AAAA -// -// * DNS response code, such as NoError or ServFail -// -// Log Group and Resource PolicyBefore you create a query logging configuration, -// perform the following operations. -// -// If you create a query logging configuration using the Amazon Route 53 console, -// Amazon Route 53 performs these operations automatically. -// -// Create a CloudWatch Logs log group, and make note of the ARN, which you specify -// when you create a query logging configuration. Note the following: -// -// You must create the log group in the us-east-1 region. -// -// You must use the same AWS account to create the log group and the hosted -// zone that you want to configure query logging for. -// -// When you create log groups for query logging, we recommend that you use a -// consistent prefix, for example: -// -// /aws/route53/hosted zone name -// -// In the next step, you'll create a resource policy, which controls access -// to one or more log groups and the associated AWS resources, such as Amazon -// Route 53 hosted zones. There's a limit on the number of resource policies -// that you can create, so we recommend that you use a consistent prefix so -// you can use the same resource policy for all the log groups that you create -// for query logging. -// -// Create a CloudWatch Logs resource policy, and give it the permissions that -// Amazon Route 53 needs to create log streams and to send query logs to log -// streams. For the value of Resource, specify the ARN for the log group that -// you created in the previous step. To use the same resource policy for all -// the CloudWatch Logs log groups that you created for query logging configurations, -// replace the hosted zone name with *, for example: -// -// arn:aws:logs:us-east-1:123412341234:log-group:/aws/route53/* -// -// You can't use the CloudWatch console to create or edit a resource policy. -// You must use the CloudWatch API, one of the AWS SDKs, or the AWS CLI. -// -// Log Streams and Edge LocationsWhen Amazon Route 53 finishes creating the -// configuration for DNS query logging, it does the following: -// -// Creates a log stream for an edge location the first time that the edge location -// responds to DNS queries for the specified hosted zone. That log stream is -// used to log all queries that Amazon Route 53 responds to for that edge location. -// -// Begins to send query logs to the applicable log stream. -// -// The name of each log stream is in the following format: -// -// hosted zone ID/edge location code -// -// The edge location code is a three-letter code and an arbitrarily assigned -// number, for example, DFW3. The three-letter code typically corresponds with -// the International Air Transport Association airport code for an airport near -// the edge location. (These abbreviations might change in the future.) For -// a list of edge locations, see "The Amazon Route 53 Global Network" on the -// Amazon Route 53 Product Details (http://aws.amazon.com/route53/details/) -// page. -// -// Queries That Are LoggedQuery logs contain only the queries that DNS resolvers -// forward to Amazon Route 53. If a DNS resolver has already cached the response -// to a query (such as the IP address for a load balancer for example.com), -// the resolver will continue to return the cached response. It doesn't forward -// another query to Amazon Route 53 until the TTL for the corresponding resource -// record set expires. Depending on how many DNS queries are submitted for a -// resource record set, and depending on the TTL for that resource record set, -// query logs might contain information about only one query out of every several -// thousand queries that are submitted to DNS. For more information about how -// DNS works, see Routing Internet Traffic to Your Website or Web Application -// (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/welcome-dns-service.html) -// in the Amazon Route 53 Developer Guide. -// -// Log File FormatFor a list of the values in each query log and the format -// of each value, see Logging DNS Queries (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html) -// in the Amazon Route 53 Developer Guide. -// -// PricingFor information about charges for query logs, see Amazon CloudWatch -// Pricing (http://aws.amazon.com/cloudwatch/pricing/). -// -// How to Stop LoggingIf you want Amazon Route 53 to stop sending query logs -// to CloudWatch Logs, delete the query logging configuration. For more information, -// see DeleteQueryLoggingConfig. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateQueryLoggingConfig for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeNoSuchCloudWatchLogsLogGroup "NoSuchCloudWatchLogsLogGroup" -// There is no CloudWatch Logs log group with the specified ARN. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeQueryLoggingConfigAlreadyExists "QueryLoggingConfigAlreadyExists" -// You can create only one query logging configuration for a hosted zone, and -// a query logging configuration already exists for this hosted zone. -// -// * ErrCodeInsufficientCloudWatchLogsResourcePolicy "InsufficientCloudWatchLogsResourcePolicy" -// Amazon Route 53 doesn't have the permissions required to create log streams -// and send query logs to log streams. Possible causes include the following: -// -// * There is no resource policy that specifies the log group ARN in the -// value for Resource. -// -// * The resource policy that includes the log group ARN in the value for -// Resource doesn't have the necessary permissions. -// -// * The resource policy hasn't finished propagating yet. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateQueryLoggingConfig -func (c *Route53) CreateQueryLoggingConfig(input *CreateQueryLoggingConfigInput) (*CreateQueryLoggingConfigOutput, error) { - req, out := c.CreateQueryLoggingConfigRequest(input) - return out, req.Send() -} - -// CreateQueryLoggingConfigWithContext is the same as CreateQueryLoggingConfig with the addition of -// the ability to pass a context and additional request options. -// -// See CreateQueryLoggingConfig for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateQueryLoggingConfigWithContext(ctx aws.Context, input *CreateQueryLoggingConfigInput, opts ...request.Option) (*CreateQueryLoggingConfigOutput, error) { - req, out := c.CreateQueryLoggingConfigRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateReusableDelegationSet = "CreateReusableDelegationSet" - -// CreateReusableDelegationSetRequest generates a "aws/request.Request" representing the -// client's request for the CreateReusableDelegationSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateReusableDelegationSet for more information on using the CreateReusableDelegationSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateReusableDelegationSetRequest method. -// req, resp := client.CreateReusableDelegationSetRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateReusableDelegationSet -func (c *Route53) CreateReusableDelegationSetRequest(input *CreateReusableDelegationSetInput) (req *request.Request, output *CreateReusableDelegationSetOutput) { - op := &request.Operation{ - Name: opCreateReusableDelegationSet, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/delegationset", - } - - if input == nil { - input = &CreateReusableDelegationSetInput{} - } - - output = &CreateReusableDelegationSetOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateReusableDelegationSet API operation for Amazon Route 53. -// -// Creates a delegation set (a group of four name servers) that can be reused -// by multiple hosted zones. If a hosted zoned ID is specified, CreateReusableDelegationSet -// marks the delegation set associated with that zone as reusable. -// -// You can't associate a reusable delegation set with a private hosted zone. -// -// For information about using a reusable delegation set to configure white -// label name servers, see Configuring White Label Name Servers (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/white-label-name-servers.html). -// -// The process for migrating existing hosted zones to use a reusable delegation -// set is comparable to the process for configuring white label name servers. -// You need to perform the following steps: -// -// Create a reusable delegation set. -// -// Recreate hosted zones, and reduce the TTL to 60 seconds or less. -// -// Recreate resource record sets in the new hosted zones. -// -// Change the registrar's name servers to use the name servers for the new hosted -// zones. -// -// Monitor traffic for the website or application. -// -// Change TTLs back to their original values. -// -// If you want to migrate existing hosted zones to use a reusable delegation -// set, the existing hosted zones can't use any of the name servers that are -// assigned to the reusable delegation set. If one or more hosted zones do use -// one or more name servers that are assigned to the reusable delegation set, -// you can do one of the following: -// -// * For small numbers of hosted zones—up to a few hundred—it's relatively -// easy to create reusable delegation sets until you get one that has four -// name servers that don't overlap with any of the name servers in your hosted -// zones. -// -// * For larger numbers of hosted zones, the easiest solution is to use more -// than one reusable delegation set. -// -// * For larger numbers of hosted zones, you can also migrate hosted zones -// that have overlapping name servers to hosted zones that don't have overlapping -// name servers, then migrate the hosted zones again to use the reusable -// delegation set. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateReusableDelegationSet for usage and error information. -// -// Returned Error Codes: -// * ErrCodeDelegationSetAlreadyCreated "DelegationSetAlreadyCreated" -// A delegation set with the same owner and caller reference combination has -// already been created. -// -// * ErrCodeLimitsExceeded "LimitsExceeded" -// This operation can't be completed either because the current account has -// reached the limit on reusable delegation sets that it can create or because -// you've reached the limit on the number of Amazon VPCs that you can associate -// with a private hosted zone. To get the current limit on the number of reusable -// delegation sets, see GetAccountLimit. To get the current limit on the number -// of Amazon VPCs that you can associate with a private hosted zone, see GetHostedZoneLimit. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeHostedZoneNotFound "HostedZoneNotFound" -// The specified HostedZone can't be found. -// -// * ErrCodeInvalidArgument "InvalidArgument" -// Parameter name is invalid. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeDelegationSetNotAvailable "DelegationSetNotAvailable" -// You can create a hosted zone that has the same name as an existing hosted -// zone (example.com is common), but there is a limit to the number of hosted -// zones that have the same name. If you get this error, Amazon Route 53 has -// reached that limit. If you own the domain name and Amazon Route 53 generates -// this error, contact Customer Support. -// -// * ErrCodeDelegationSetAlreadyReusable "DelegationSetAlreadyReusable" -// The specified delegation set has already been marked as reusable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateReusableDelegationSet -func (c *Route53) CreateReusableDelegationSet(input *CreateReusableDelegationSetInput) (*CreateReusableDelegationSetOutput, error) { - req, out := c.CreateReusableDelegationSetRequest(input) - return out, req.Send() -} - -// CreateReusableDelegationSetWithContext is the same as CreateReusableDelegationSet with the addition of -// the ability to pass a context and additional request options. -// -// See CreateReusableDelegationSet for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateReusableDelegationSetWithContext(ctx aws.Context, input *CreateReusableDelegationSetInput, opts ...request.Option) (*CreateReusableDelegationSetOutput, error) { - req, out := c.CreateReusableDelegationSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTrafficPolicy = "CreateTrafficPolicy" - -// CreateTrafficPolicyRequest generates a "aws/request.Request" representing the -// client's request for the CreateTrafficPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTrafficPolicy for more information on using the CreateTrafficPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateTrafficPolicyRequest method. -// req, resp := client.CreateTrafficPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicy -func (c *Route53) CreateTrafficPolicyRequest(input *CreateTrafficPolicyInput) (req *request.Request, output *CreateTrafficPolicyOutput) { - op := &request.Operation{ - Name: opCreateTrafficPolicy, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicy", - } - - if input == nil { - input = &CreateTrafficPolicyInput{} - } - - output = &CreateTrafficPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTrafficPolicy API operation for Amazon Route 53. -// -// Creates a traffic policy, which you use to create multiple DNS resource record -// sets for one domain name (such as example.com) or one subdomain name (such -// as www.example.com). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateTrafficPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTooManyTrafficPolicies "TooManyTrafficPolicies" -// This traffic policy can't be created because the current account has reached -// the limit on the number of traffic policies. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// To get the current limit for an account, see GetAccountLimit. -// -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeTrafficPolicyAlreadyExists "TrafficPolicyAlreadyExists" -// A traffic policy that has the same value for Name already exists. -// -// * ErrCodeInvalidTrafficPolicyDocument "InvalidTrafficPolicyDocument" -// The format of the traffic policy document that you specified in the Document -// element is invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicy -func (c *Route53) CreateTrafficPolicy(input *CreateTrafficPolicyInput) (*CreateTrafficPolicyOutput, error) { - req, out := c.CreateTrafficPolicyRequest(input) - return out, req.Send() -} - -// CreateTrafficPolicyWithContext is the same as CreateTrafficPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTrafficPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateTrafficPolicyWithContext(ctx aws.Context, input *CreateTrafficPolicyInput, opts ...request.Option) (*CreateTrafficPolicyOutput, error) { - req, out := c.CreateTrafficPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTrafficPolicyInstance = "CreateTrafficPolicyInstance" - -// CreateTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the CreateTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTrafficPolicyInstance for more information on using the CreateTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateTrafficPolicyInstanceRequest method. -// req, resp := client.CreateTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyInstance -func (c *Route53) CreateTrafficPolicyInstanceRequest(input *CreateTrafficPolicyInstanceInput) (req *request.Request, output *CreateTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opCreateTrafficPolicyInstance, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicyinstance", - } - - if input == nil { - input = &CreateTrafficPolicyInstanceInput{} - } - - output = &CreateTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTrafficPolicyInstance API operation for Amazon Route 53. -// -// Creates resource record sets in a specified hosted zone based on the settings -// in a specified traffic policy version. In addition, CreateTrafficPolicyInstance -// associates the resource record sets with a specified domain name (such as -// example.com) or subdomain name (such as www.example.com). Amazon Route 53 -// responds to DNS queries for the domain or subdomain name by using the resource -// record sets that CreateTrafficPolicyInstance created. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTooManyTrafficPolicyInstances "TooManyTrafficPolicyInstances" -// This traffic policy instance can't be created because the current account -// has reached the limit on the number of traffic policy instances. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// For information about how to get the current limit for an account, see GetAccountLimit. -// -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeTrafficPolicyInstanceAlreadyExists "TrafficPolicyInstanceAlreadyExists" -// There is already a traffic policy instance with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyInstance -func (c *Route53) CreateTrafficPolicyInstance(input *CreateTrafficPolicyInstanceInput) (*CreateTrafficPolicyInstanceOutput, error) { - req, out := c.CreateTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// CreateTrafficPolicyInstanceWithContext is the same as CreateTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateTrafficPolicyInstanceWithContext(ctx aws.Context, input *CreateTrafficPolicyInstanceInput, opts ...request.Option) (*CreateTrafficPolicyInstanceOutput, error) { - req, out := c.CreateTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTrafficPolicyVersion = "CreateTrafficPolicyVersion" - -// CreateTrafficPolicyVersionRequest generates a "aws/request.Request" representing the -// client's request for the CreateTrafficPolicyVersion operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTrafficPolicyVersion for more information on using the CreateTrafficPolicyVersion -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateTrafficPolicyVersionRequest method. -// req, resp := client.CreateTrafficPolicyVersionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersion -func (c *Route53) CreateTrafficPolicyVersionRequest(input *CreateTrafficPolicyVersionInput) (req *request.Request, output *CreateTrafficPolicyVersionOutput) { - op := &request.Operation{ - Name: opCreateTrafficPolicyVersion, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}", - } - - if input == nil { - input = &CreateTrafficPolicyVersionInput{} - } - - output = &CreateTrafficPolicyVersionOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTrafficPolicyVersion API operation for Amazon Route 53. -// -// Creates a new version of an existing traffic policy. When you create a new -// version of a traffic policy, you specify the ID of the traffic policy that -// you want to update and a JSON-formatted document that describes the new version. -// You use traffic policies to create multiple DNS resource record sets for -// one domain name (such as example.com) or one subdomain name (such as www.example.com). -// You can create a maximum of 1000 versions of a traffic policy. If you reach -// the limit and need to create another version, you'll need to start a new -// traffic policy. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateTrafficPolicyVersion for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTooManyTrafficPolicyVersionsForCurrentPolicy "TooManyTrafficPolicyVersionsForCurrentPolicy" -// This traffic policy version can't be created because you've reached the limit -// of 1000 on the number of versions that you can create for the current traffic -// policy. -// -// To create more traffic policy versions, you can use GetTrafficPolicy to get -// the traffic policy document for a specified traffic policy version, and then -// use CreateTrafficPolicy to create a new traffic policy using the traffic -// policy document. -// -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeInvalidTrafficPolicyDocument "InvalidTrafficPolicyDocument" -// The format of the traffic policy document that you specified in the Document -// element is invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersion -func (c *Route53) CreateTrafficPolicyVersion(input *CreateTrafficPolicyVersionInput) (*CreateTrafficPolicyVersionOutput, error) { - req, out := c.CreateTrafficPolicyVersionRequest(input) - return out, req.Send() -} - -// CreateTrafficPolicyVersionWithContext is the same as CreateTrafficPolicyVersion with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTrafficPolicyVersion for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateTrafficPolicyVersionWithContext(ctx aws.Context, input *CreateTrafficPolicyVersionInput, opts ...request.Option) (*CreateTrafficPolicyVersionOutput, error) { - req, out := c.CreateTrafficPolicyVersionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateVPCAssociationAuthorization = "CreateVPCAssociationAuthorization" - -// CreateVPCAssociationAuthorizationRequest generates a "aws/request.Request" representing the -// client's request for the CreateVPCAssociationAuthorization operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateVPCAssociationAuthorization for more information on using the CreateVPCAssociationAuthorization -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateVPCAssociationAuthorizationRequest method. -// req, resp := client.CreateVPCAssociationAuthorizationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateVPCAssociationAuthorization -func (c *Route53) CreateVPCAssociationAuthorizationRequest(input *CreateVPCAssociationAuthorizationInput) (req *request.Request, output *CreateVPCAssociationAuthorizationOutput) { - op := &request.Operation{ - Name: opCreateVPCAssociationAuthorization, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/authorizevpcassociation", - } - - if input == nil { - input = &CreateVPCAssociationAuthorizationInput{} - } - - output = &CreateVPCAssociationAuthorizationOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateVPCAssociationAuthorization API operation for Amazon Route 53. -// -// Authorizes the AWS account that created a specified VPC to submit an AssociateVPCWithHostedZone -// request to associate the VPC with a specified hosted zone that was created -// by a different account. To submit a CreateVPCAssociationAuthorization request, -// you must use the account that created the hosted zone. After you authorize -// the association, use the account that created the VPC to submit an AssociateVPCWithHostedZone -// request. -// -// If you want to associate multiple VPCs that you created by using one account -// with a hosted zone that you created by using a different account, you must -// submit one authorization request for each VPC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateVPCAssociationAuthorization for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeTooManyVPCAssociationAuthorizations "TooManyVPCAssociationAuthorizations" -// You've created the maximum number of authorizations that can be created for -// the specified hosted zone. To authorize another VPC to be associated with -// the hosted zone, submit a DeleteVPCAssociationAuthorization request to remove -// an existing authorization. To get a list of existing authorizations, submit -// a ListVPCAssociationAuthorizations request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateVPCAssociationAuthorization -func (c *Route53) CreateVPCAssociationAuthorization(input *CreateVPCAssociationAuthorizationInput) (*CreateVPCAssociationAuthorizationOutput, error) { - req, out := c.CreateVPCAssociationAuthorizationRequest(input) - return out, req.Send() -} - -// CreateVPCAssociationAuthorizationWithContext is the same as CreateVPCAssociationAuthorization with the addition of -// the ability to pass a context and additional request options. -// -// See CreateVPCAssociationAuthorization for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateVPCAssociationAuthorizationWithContext(ctx aws.Context, input *CreateVPCAssociationAuthorizationInput, opts ...request.Option) (*CreateVPCAssociationAuthorizationOutput, error) { - req, out := c.CreateVPCAssociationAuthorizationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteHealthCheck = "DeleteHealthCheck" - -// DeleteHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the DeleteHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteHealthCheck for more information on using the DeleteHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteHealthCheckRequest method. -// req, resp := client.DeleteHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHealthCheck -func (c *Route53) DeleteHealthCheckRequest(input *DeleteHealthCheckInput) (req *request.Request, output *DeleteHealthCheckOutput) { - op := &request.Operation{ - Name: opDeleteHealthCheck, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}", - } - - if input == nil { - input = &DeleteHealthCheckInput{} - } - - output = &DeleteHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteHealthCheck API operation for Amazon Route 53. -// -// Deletes a health check. -// -// Amazon Route 53 does not prevent you from deleting a health check even if -// the health check is associated with one or more resource record sets. If -// you delete a health check and you don't update the associated resource record -// sets, the future status of the health check can't be predicted and may change. -// This will affect the routing of DNS queries for your DNS failover configuration. -// For more information, see Replacing and Deleting Health Checks (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-deleting.html#health-checks-deleting.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeHealthCheckInUse "HealthCheckInUse" -// This error code is not in use. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHealthCheck -func (c *Route53) DeleteHealthCheck(input *DeleteHealthCheckInput) (*DeleteHealthCheckOutput, error) { - req, out := c.DeleteHealthCheckRequest(input) - return out, req.Send() -} - -// DeleteHealthCheckWithContext is the same as DeleteHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteHealthCheckWithContext(ctx aws.Context, input *DeleteHealthCheckInput, opts ...request.Option) (*DeleteHealthCheckOutput, error) { - req, out := c.DeleteHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteHostedZone = "DeleteHostedZone" - -// DeleteHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the DeleteHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteHostedZone for more information on using the DeleteHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteHostedZoneRequest method. -// req, resp := client.DeleteHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZone -func (c *Route53) DeleteHostedZoneRequest(input *DeleteHostedZoneInput) (req *request.Request, output *DeleteHostedZoneOutput) { - op := &request.Operation{ - Name: opDeleteHostedZone, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/hostedzone/{Id}", - } - - if input == nil { - input = &DeleteHostedZoneInput{} - } - - output = &DeleteHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteHostedZone API operation for Amazon Route 53. -// -// Deletes a hosted zone. -// -// If the name servers for the hosted zone are associated with a domain and -// if you want to make the domain unavailable on the Internet, we recommend -// that you delete the name servers from the domain to prevent future DNS queries -// from possibly being misrouted. If the domain is registered with Amazon Route -// 53, see UpdateDomainNameservers. If the domain is registered with another -// registrar, use the method provided by the registrar to delete name servers -// for the domain. -// -// Some domain registries don't allow you to remove all of the name servers -// for a domain. If the registry for your domain requires one or more name servers, -// we recommend that you delete the hosted zone only if you transfer DNS service -// to another service provider, and you replace the name servers for the domain -// with name servers from the new provider. -// -// You can delete a hosted zone only if it contains only the default SOA record -// and NS resource record sets. If the hosted zone contains other resource record -// sets, you must delete them before you can delete the hosted zone. If you -// try to delete a hosted zone that contains other resource record sets, the -// request fails, and Amazon Route 53 returns a HostedZoneNotEmpty error. For -// information about deleting records from your hosted zone, see ChangeResourceRecordSets. -// -// To verify that the hosted zone has been deleted, do one of the following: -// -// * Use the GetHostedZone action to request information about the hosted -// zone. -// -// * Use the ListHostedZones action to get a list of the hosted zones associated -// with the current AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeHostedZoneNotEmpty "HostedZoneNotEmpty" -// The hosted zone contains resource records that are not SOA or NS records. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidDomainName "InvalidDomainName" -// The specified domain name is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZone -func (c *Route53) DeleteHostedZone(input *DeleteHostedZoneInput) (*DeleteHostedZoneOutput, error) { - req, out := c.DeleteHostedZoneRequest(input) - return out, req.Send() -} - -// DeleteHostedZoneWithContext is the same as DeleteHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteHostedZoneWithContext(ctx aws.Context, input *DeleteHostedZoneInput, opts ...request.Option) (*DeleteHostedZoneOutput, error) { - req, out := c.DeleteHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteQueryLoggingConfig = "DeleteQueryLoggingConfig" - -// DeleteQueryLoggingConfigRequest generates a "aws/request.Request" representing the -// client's request for the DeleteQueryLoggingConfig operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteQueryLoggingConfig for more information on using the DeleteQueryLoggingConfig -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteQueryLoggingConfigRequest method. -// req, resp := client.DeleteQueryLoggingConfigRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteQueryLoggingConfig -func (c *Route53) DeleteQueryLoggingConfigRequest(input *DeleteQueryLoggingConfigInput) (req *request.Request, output *DeleteQueryLoggingConfigOutput) { - op := &request.Operation{ - Name: opDeleteQueryLoggingConfig, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/queryloggingconfig/{Id}", - } - - if input == nil { - input = &DeleteQueryLoggingConfigInput{} - } - - output = &DeleteQueryLoggingConfigOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteQueryLoggingConfig API operation for Amazon Route 53. -// -// Deletes a configuration for DNS query logging. If you delete a configuration, -// Amazon Route 53 stops sending query logs to CloudWatch Logs. Amazon Route -// 53 doesn't delete any logs that are already in CloudWatch Logs. -// -// For more information about DNS query logs, see CreateQueryLoggingConfig. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteQueryLoggingConfig for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeNoSuchQueryLoggingConfig "NoSuchQueryLoggingConfig" -// There is no DNS query logging configuration with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteQueryLoggingConfig -func (c *Route53) DeleteQueryLoggingConfig(input *DeleteQueryLoggingConfigInput) (*DeleteQueryLoggingConfigOutput, error) { - req, out := c.DeleteQueryLoggingConfigRequest(input) - return out, req.Send() -} - -// DeleteQueryLoggingConfigWithContext is the same as DeleteQueryLoggingConfig with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteQueryLoggingConfig for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteQueryLoggingConfigWithContext(ctx aws.Context, input *DeleteQueryLoggingConfigInput, opts ...request.Option) (*DeleteQueryLoggingConfigOutput, error) { - req, out := c.DeleteQueryLoggingConfigRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteReusableDelegationSet = "DeleteReusableDelegationSet" - -// DeleteReusableDelegationSetRequest generates a "aws/request.Request" representing the -// client's request for the DeleteReusableDelegationSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteReusableDelegationSet for more information on using the DeleteReusableDelegationSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteReusableDelegationSetRequest method. -// req, resp := client.DeleteReusableDelegationSetRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteReusableDelegationSet -func (c *Route53) DeleteReusableDelegationSetRequest(input *DeleteReusableDelegationSetInput) (req *request.Request, output *DeleteReusableDelegationSetOutput) { - op := &request.Operation{ - Name: opDeleteReusableDelegationSet, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/delegationset/{Id}", - } - - if input == nil { - input = &DeleteReusableDelegationSetInput{} - } - - output = &DeleteReusableDelegationSetOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteReusableDelegationSet API operation for Amazon Route 53. -// -// Deletes a reusable delegation set. -// -// You can delete a reusable delegation set only if it isn't associated with -// any hosted zones. -// -// To verify that the reusable delegation set is not associated with any hosted -// zones, submit a GetReusableDelegationSet request and specify the ID of the -// reusable delegation set that you want to delete. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteReusableDelegationSet for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetInUse "DelegationSetInUse" -// The specified delegation contains associated hosted zones which must be deleted -// before the reusable delegation set can be deleted. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteReusableDelegationSet -func (c *Route53) DeleteReusableDelegationSet(input *DeleteReusableDelegationSetInput) (*DeleteReusableDelegationSetOutput, error) { - req, out := c.DeleteReusableDelegationSetRequest(input) - return out, req.Send() -} - -// DeleteReusableDelegationSetWithContext is the same as DeleteReusableDelegationSet with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteReusableDelegationSet for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteReusableDelegationSetWithContext(ctx aws.Context, input *DeleteReusableDelegationSetInput, opts ...request.Option) (*DeleteReusableDelegationSetOutput, error) { - req, out := c.DeleteReusableDelegationSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteTrafficPolicy = "DeleteTrafficPolicy" - -// DeleteTrafficPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteTrafficPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteTrafficPolicy for more information on using the DeleteTrafficPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteTrafficPolicyRequest method. -// req, resp := client.DeleteTrafficPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicy -func (c *Route53) DeleteTrafficPolicyRequest(input *DeleteTrafficPolicyInput) (req *request.Request, output *DeleteTrafficPolicyOutput) { - op := &request.Operation{ - Name: opDeleteTrafficPolicy, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}/{Version}", - } - - if input == nil { - input = &DeleteTrafficPolicyInput{} - } - - output = &DeleteTrafficPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteTrafficPolicy API operation for Amazon Route 53. -// -// Deletes a traffic policy. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteTrafficPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTrafficPolicyInUse "TrafficPolicyInUse" -// One or more traffic policy instances were created by using the specified -// traffic policy. -// -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicy -func (c *Route53) DeleteTrafficPolicy(input *DeleteTrafficPolicyInput) (*DeleteTrafficPolicyOutput, error) { - req, out := c.DeleteTrafficPolicyRequest(input) - return out, req.Send() -} - -// DeleteTrafficPolicyWithContext is the same as DeleteTrafficPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteTrafficPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteTrafficPolicyWithContext(ctx aws.Context, input *DeleteTrafficPolicyInput, opts ...request.Option) (*DeleteTrafficPolicyOutput, error) { - req, out := c.DeleteTrafficPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteTrafficPolicyInstance = "DeleteTrafficPolicyInstance" - -// DeleteTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the DeleteTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteTrafficPolicyInstance for more information on using the DeleteTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteTrafficPolicyInstanceRequest method. -// req, resp := client.DeleteTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicyInstance -func (c *Route53) DeleteTrafficPolicyInstanceRequest(input *DeleteTrafficPolicyInstanceInput) (req *request.Request, output *DeleteTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opDeleteTrafficPolicyInstance, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/trafficpolicyinstance/{Id}", - } - - if input == nil { - input = &DeleteTrafficPolicyInstanceInput{} - } - - output = &DeleteTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteTrafficPolicyInstance API operation for Amazon Route 53. -// -// Deletes a traffic policy instance and all of the resource record sets that -// Amazon Route 53 created when you created the instance. -// -// In the Amazon Route 53 console, traffic policy instances are known as policy -// records. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicyInstance -func (c *Route53) DeleteTrafficPolicyInstance(input *DeleteTrafficPolicyInstanceInput) (*DeleteTrafficPolicyInstanceOutput, error) { - req, out := c.DeleteTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// DeleteTrafficPolicyInstanceWithContext is the same as DeleteTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteTrafficPolicyInstanceWithContext(ctx aws.Context, input *DeleteTrafficPolicyInstanceInput, opts ...request.Option) (*DeleteTrafficPolicyInstanceOutput, error) { - req, out := c.DeleteTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteVPCAssociationAuthorization = "DeleteVPCAssociationAuthorization" - -// DeleteVPCAssociationAuthorizationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteVPCAssociationAuthorization operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteVPCAssociationAuthorization for more information on using the DeleteVPCAssociationAuthorization -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteVPCAssociationAuthorizationRequest method. -// req, resp := client.DeleteVPCAssociationAuthorizationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteVPCAssociationAuthorization -func (c *Route53) DeleteVPCAssociationAuthorizationRequest(input *DeleteVPCAssociationAuthorizationInput) (req *request.Request, output *DeleteVPCAssociationAuthorizationOutput) { - op := &request.Operation{ - Name: opDeleteVPCAssociationAuthorization, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/deauthorizevpcassociation", - } - - if input == nil { - input = &DeleteVPCAssociationAuthorizationInput{} - } - - output = &DeleteVPCAssociationAuthorizationOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteVPCAssociationAuthorization API operation for Amazon Route 53. -// -// Removes authorization to submit an AssociateVPCWithHostedZone request to -// associate a specified VPC with a hosted zone that was created by a different -// account. You must use the account that created the hosted zone to submit -// a DeleteVPCAssociationAuthorization request. -// -// Sending this request only prevents the AWS account that created the VPC from -// associating the VPC with the Amazon Route 53 hosted zone in the future. If -// the VPC is already associated with the hosted zone, DeleteVPCAssociationAuthorization -// won't disassociate the VPC from the hosted zone. If you want to delete an -// existing association, use DisassociateVPCFromHostedZone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteVPCAssociationAuthorization for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeVPCAssociationAuthorizationNotFound "VPCAssociationAuthorizationNotFound" -// The VPC that you specified is not authorized to be associated with the hosted -// zone. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteVPCAssociationAuthorization -func (c *Route53) DeleteVPCAssociationAuthorization(input *DeleteVPCAssociationAuthorizationInput) (*DeleteVPCAssociationAuthorizationOutput, error) { - req, out := c.DeleteVPCAssociationAuthorizationRequest(input) - return out, req.Send() -} - -// DeleteVPCAssociationAuthorizationWithContext is the same as DeleteVPCAssociationAuthorization with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteVPCAssociationAuthorization for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteVPCAssociationAuthorizationWithContext(ctx aws.Context, input *DeleteVPCAssociationAuthorizationInput, opts ...request.Option) (*DeleteVPCAssociationAuthorizationOutput, error) { - req, out := c.DeleteVPCAssociationAuthorizationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDisassociateVPCFromHostedZone = "DisassociateVPCFromHostedZone" - -// DisassociateVPCFromHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the DisassociateVPCFromHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DisassociateVPCFromHostedZone for more information on using the DisassociateVPCFromHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DisassociateVPCFromHostedZoneRequest method. -// req, resp := client.DisassociateVPCFromHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DisassociateVPCFromHostedZone -func (c *Route53) DisassociateVPCFromHostedZoneRequest(input *DisassociateVPCFromHostedZoneInput) (req *request.Request, output *DisassociateVPCFromHostedZoneOutput) { - op := &request.Operation{ - Name: opDisassociateVPCFromHostedZone, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/disassociatevpc", - } - - if input == nil { - input = &DisassociateVPCFromHostedZoneInput{} - } - - output = &DisassociateVPCFromHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// DisassociateVPCFromHostedZone API operation for Amazon Route 53. -// -// Disassociates a VPC from a Amazon Route 53 private hosted zone. -// -// You can't disassociate the last VPC from a private hosted zone. -// -// You can't disassociate a VPC from a private hosted zone when only one VPC -// is associated with the hosted zone. You also can't convert a private hosted -// zone into a public hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DisassociateVPCFromHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeVPCAssociationNotFound "VPCAssociationNotFound" -// The specified VPC and hosted zone are not currently associated. -// -// * ErrCodeLastVPCAssociation "LastVPCAssociation" -// The VPC that you're trying to disassociate from the private hosted zone is -// the last VPC that is associated with the hosted zone. Amazon Route 53 doesn't -// support disassociating the last VPC from a hosted zone. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DisassociateVPCFromHostedZone -func (c *Route53) DisassociateVPCFromHostedZone(input *DisassociateVPCFromHostedZoneInput) (*DisassociateVPCFromHostedZoneOutput, error) { - req, out := c.DisassociateVPCFromHostedZoneRequest(input) - return out, req.Send() -} - -// DisassociateVPCFromHostedZoneWithContext is the same as DisassociateVPCFromHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See DisassociateVPCFromHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DisassociateVPCFromHostedZoneWithContext(ctx aws.Context, input *DisassociateVPCFromHostedZoneInput, opts ...request.Option) (*DisassociateVPCFromHostedZoneOutput, error) { - req, out := c.DisassociateVPCFromHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetAccountLimit = "GetAccountLimit" - -// GetAccountLimitRequest generates a "aws/request.Request" representing the -// client's request for the GetAccountLimit operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetAccountLimit for more information on using the GetAccountLimit -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetAccountLimitRequest method. -// req, resp := client.GetAccountLimitRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetAccountLimit -func (c *Route53) GetAccountLimitRequest(input *GetAccountLimitInput) (req *request.Request, output *GetAccountLimitOutput) { - op := &request.Operation{ - Name: opGetAccountLimit, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/accountlimit/{Type}", - } - - if input == nil { - input = &GetAccountLimitInput{} - } - - output = &GetAccountLimitOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetAccountLimit API operation for Amazon Route 53. -// -// Gets the specified limit for the current account, for example, the maximum -// number of health checks that you can create using the account. -// -// For the default limit, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. To request a higher limit, open a -// case (https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-route53). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetAccountLimit for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetAccountLimit -func (c *Route53) GetAccountLimit(input *GetAccountLimitInput) (*GetAccountLimitOutput, error) { - req, out := c.GetAccountLimitRequest(input) - return out, req.Send() -} - -// GetAccountLimitWithContext is the same as GetAccountLimit with the addition of -// the ability to pass a context and additional request options. -// -// See GetAccountLimit for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetAccountLimitWithContext(ctx aws.Context, input *GetAccountLimitInput, opts ...request.Option) (*GetAccountLimitOutput, error) { - req, out := c.GetAccountLimitRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetChange = "GetChange" - -// GetChangeRequest generates a "aws/request.Request" representing the -// client's request for the GetChange operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetChange for more information on using the GetChange -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetChangeRequest method. -// req, resp := client.GetChangeRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetChange -func (c *Route53) GetChangeRequest(input *GetChangeInput) (req *request.Request, output *GetChangeOutput) { - op := &request.Operation{ - Name: opGetChange, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/change/{Id}", - } - - if input == nil { - input = &GetChangeInput{} - } - - output = &GetChangeOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetChange API operation for Amazon Route 53. -// -// Returns the current status of a change batch request. The status is one of -// the following values: -// -// * PENDING indicates that the changes in this request have not propagated -// to all Amazon Route 53 DNS servers. This is the initial status of all -// change batch requests. -// -// * INSYNC indicates that the changes have propagated to all Amazon Route -// 53 DNS servers. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetChange for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchChange "NoSuchChange" -// A change with the specified change ID does not exist. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetChange -func (c *Route53) GetChange(input *GetChangeInput) (*GetChangeOutput, error) { - req, out := c.GetChangeRequest(input) - return out, req.Send() -} - -// GetChangeWithContext is the same as GetChange with the addition of -// the ability to pass a context and additional request options. -// -// See GetChange for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetChangeWithContext(ctx aws.Context, input *GetChangeInput, opts ...request.Option) (*GetChangeOutput, error) { - req, out := c.GetChangeRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetCheckerIpRanges = "GetCheckerIpRanges" - -// GetCheckerIpRangesRequest generates a "aws/request.Request" representing the -// client's request for the GetCheckerIpRanges operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetCheckerIpRanges for more information on using the GetCheckerIpRanges -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetCheckerIpRangesRequest method. -// req, resp := client.GetCheckerIpRangesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetCheckerIpRanges -func (c *Route53) GetCheckerIpRangesRequest(input *GetCheckerIpRangesInput) (req *request.Request, output *GetCheckerIpRangesOutput) { - op := &request.Operation{ - Name: opGetCheckerIpRanges, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/checkeripranges", - } - - if input == nil { - input = &GetCheckerIpRangesInput{} - } - - output = &GetCheckerIpRangesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetCheckerIpRanges API operation for Amazon Route 53. -// -// GetCheckerIpRanges still works, but we recommend that you download ip-ranges.json, -// which includes IP address ranges for all AWS services. For more information, -// see IP Address Ranges of Amazon Route 53 Servers (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-ip-addresses.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetCheckerIpRanges for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetCheckerIpRanges -func (c *Route53) GetCheckerIpRanges(input *GetCheckerIpRangesInput) (*GetCheckerIpRangesOutput, error) { - req, out := c.GetCheckerIpRangesRequest(input) - return out, req.Send() -} - -// GetCheckerIpRangesWithContext is the same as GetCheckerIpRanges with the addition of -// the ability to pass a context and additional request options. -// -// See GetCheckerIpRanges for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetCheckerIpRangesWithContext(ctx aws.Context, input *GetCheckerIpRangesInput, opts ...request.Option) (*GetCheckerIpRangesOutput, error) { - req, out := c.GetCheckerIpRangesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetGeoLocation = "GetGeoLocation" - -// GetGeoLocationRequest generates a "aws/request.Request" representing the -// client's request for the GetGeoLocation operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetGeoLocation for more information on using the GetGeoLocation -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetGeoLocationRequest method. -// req, resp := client.GetGeoLocationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetGeoLocation -func (c *Route53) GetGeoLocationRequest(input *GetGeoLocationInput) (req *request.Request, output *GetGeoLocationOutput) { - op := &request.Operation{ - Name: opGetGeoLocation, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/geolocation", - } - - if input == nil { - input = &GetGeoLocationInput{} - } - - output = &GetGeoLocationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetGeoLocation API operation for Amazon Route 53. -// -// Gets information about whether a specified geographic location is supported -// for Amazon Route 53 geolocation resource record sets. -// -// Use the following syntax to determine whether a continent is supported for -// geolocation: -// -// GET /2013-04-01/geolocation?ContinentCode=two-letter abbreviation for a continent -// -// Use the following syntax to determine whether a country is supported for -// geolocation: -// -// GET /2013-04-01/geolocation?CountryCode=two-character country code -// -// Use the following syntax to determine whether a subdivision of a country -// is supported for geolocation: -// -// GET /2013-04-01/geolocation?CountryCode=two-character country code&SubdivisionCode=subdivision -// code -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetGeoLocation for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchGeoLocation "NoSuchGeoLocation" -// Amazon Route 53 doesn't support the specified geolocation. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetGeoLocation -func (c *Route53) GetGeoLocation(input *GetGeoLocationInput) (*GetGeoLocationOutput, error) { - req, out := c.GetGeoLocationRequest(input) - return out, req.Send() -} - -// GetGeoLocationWithContext is the same as GetGeoLocation with the addition of -// the ability to pass a context and additional request options. -// -// See GetGeoLocation for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetGeoLocationWithContext(ctx aws.Context, input *GetGeoLocationInput, opts ...request.Option) (*GetGeoLocationOutput, error) { - req, out := c.GetGeoLocationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheck = "GetHealthCheck" - -// GetHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheck for more information on using the GetHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckRequest method. -// req, resp := client.GetHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheck -func (c *Route53) GetHealthCheckRequest(input *GetHealthCheckInput) (req *request.Request, output *GetHealthCheckOutput) { - op := &request.Operation{ - Name: opGetHealthCheck, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}", - } - - if input == nil { - input = &GetHealthCheckInput{} - } - - output = &GetHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheck API operation for Amazon Route 53. -// -// Gets information about a specified health check. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeIncompatibleVersion "IncompatibleVersion" -// The resource you're trying to access is unsupported on this Amazon Route -// 53 endpoint. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheck -func (c *Route53) GetHealthCheck(input *GetHealthCheckInput) (*GetHealthCheckOutput, error) { - req, out := c.GetHealthCheckRequest(input) - return out, req.Send() -} - -// GetHealthCheckWithContext is the same as GetHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckWithContext(ctx aws.Context, input *GetHealthCheckInput, opts ...request.Option) (*GetHealthCheckOutput, error) { - req, out := c.GetHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheckCount = "GetHealthCheckCount" - -// GetHealthCheckCountRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheckCount operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheckCount for more information on using the GetHealthCheckCount -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckCountRequest method. -// req, resp := client.GetHealthCheckCountRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCount -func (c *Route53) GetHealthCheckCountRequest(input *GetHealthCheckCountInput) (req *request.Request, output *GetHealthCheckCountOutput) { - op := &request.Operation{ - Name: opGetHealthCheckCount, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheckcount", - } - - if input == nil { - input = &GetHealthCheckCountInput{} - } - - output = &GetHealthCheckCountOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheckCount API operation for Amazon Route 53. -// -// Retrieves the number of health checks that are associated with the current -// AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheckCount for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCount -func (c *Route53) GetHealthCheckCount(input *GetHealthCheckCountInput) (*GetHealthCheckCountOutput, error) { - req, out := c.GetHealthCheckCountRequest(input) - return out, req.Send() -} - -// GetHealthCheckCountWithContext is the same as GetHealthCheckCount with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheckCount for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckCountWithContext(ctx aws.Context, input *GetHealthCheckCountInput, opts ...request.Option) (*GetHealthCheckCountOutput, error) { - req, out := c.GetHealthCheckCountRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheckLastFailureReason = "GetHealthCheckLastFailureReason" - -// GetHealthCheckLastFailureReasonRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheckLastFailureReason operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheckLastFailureReason for more information on using the GetHealthCheckLastFailureReason -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckLastFailureReasonRequest method. -// req, resp := client.GetHealthCheckLastFailureReasonRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckLastFailureReason -func (c *Route53) GetHealthCheckLastFailureReasonRequest(input *GetHealthCheckLastFailureReasonInput) (req *request.Request, output *GetHealthCheckLastFailureReasonOutput) { - op := &request.Operation{ - Name: opGetHealthCheckLastFailureReason, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}/lastfailurereason", - } - - if input == nil { - input = &GetHealthCheckLastFailureReasonInput{} - } - - output = &GetHealthCheckLastFailureReasonOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheckLastFailureReason API operation for Amazon Route 53. -// -// Gets the reason that a specified health check failed most recently. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheckLastFailureReason for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckLastFailureReason -func (c *Route53) GetHealthCheckLastFailureReason(input *GetHealthCheckLastFailureReasonInput) (*GetHealthCheckLastFailureReasonOutput, error) { - req, out := c.GetHealthCheckLastFailureReasonRequest(input) - return out, req.Send() -} - -// GetHealthCheckLastFailureReasonWithContext is the same as GetHealthCheckLastFailureReason with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheckLastFailureReason for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckLastFailureReasonWithContext(ctx aws.Context, input *GetHealthCheckLastFailureReasonInput, opts ...request.Option) (*GetHealthCheckLastFailureReasonOutput, error) { - req, out := c.GetHealthCheckLastFailureReasonRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheckStatus = "GetHealthCheckStatus" - -// GetHealthCheckStatusRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheckStatus operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheckStatus for more information on using the GetHealthCheckStatus -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckStatusRequest method. -// req, resp := client.GetHealthCheckStatusRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckStatus -func (c *Route53) GetHealthCheckStatusRequest(input *GetHealthCheckStatusInput) (req *request.Request, output *GetHealthCheckStatusOutput) { - op := &request.Operation{ - Name: opGetHealthCheckStatus, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}/status", - } - - if input == nil { - input = &GetHealthCheckStatusInput{} - } - - output = &GetHealthCheckStatusOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheckStatus API operation for Amazon Route 53. -// -// Gets status of a specified health check. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheckStatus for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckStatus -func (c *Route53) GetHealthCheckStatus(input *GetHealthCheckStatusInput) (*GetHealthCheckStatusOutput, error) { - req, out := c.GetHealthCheckStatusRequest(input) - return out, req.Send() -} - -// GetHealthCheckStatusWithContext is the same as GetHealthCheckStatus with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheckStatus for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckStatusWithContext(ctx aws.Context, input *GetHealthCheckStatusInput, opts ...request.Option) (*GetHealthCheckStatusOutput, error) { - req, out := c.GetHealthCheckStatusRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHostedZone = "GetHostedZone" - -// GetHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the GetHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHostedZone for more information on using the GetHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHostedZoneRequest method. -// req, resp := client.GetHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZone -func (c *Route53) GetHostedZoneRequest(input *GetHostedZoneInput) (req *request.Request, output *GetHostedZoneOutput) { - op := &request.Operation{ - Name: opGetHostedZone, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone/{Id}", - } - - if input == nil { - input = &GetHostedZoneInput{} - } - - output = &GetHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHostedZone API operation for Amazon Route 53. -// -// Gets information about a specified hosted zone including the four name servers -// assigned to the hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZone -func (c *Route53) GetHostedZone(input *GetHostedZoneInput) (*GetHostedZoneOutput, error) { - req, out := c.GetHostedZoneRequest(input) - return out, req.Send() -} - -// GetHostedZoneWithContext is the same as GetHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See GetHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHostedZoneWithContext(ctx aws.Context, input *GetHostedZoneInput, opts ...request.Option) (*GetHostedZoneOutput, error) { - req, out := c.GetHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHostedZoneCount = "GetHostedZoneCount" - -// GetHostedZoneCountRequest generates a "aws/request.Request" representing the -// client's request for the GetHostedZoneCount operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHostedZoneCount for more information on using the GetHostedZoneCount -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHostedZoneCountRequest method. -// req, resp := client.GetHostedZoneCountRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCount -func (c *Route53) GetHostedZoneCountRequest(input *GetHostedZoneCountInput) (req *request.Request, output *GetHostedZoneCountOutput) { - op := &request.Operation{ - Name: opGetHostedZoneCount, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzonecount", - } - - if input == nil { - input = &GetHostedZoneCountInput{} - } - - output = &GetHostedZoneCountOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHostedZoneCount API operation for Amazon Route 53. -// -// Retrieves the number of hosted zones that are associated with the current -// AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHostedZoneCount for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCount -func (c *Route53) GetHostedZoneCount(input *GetHostedZoneCountInput) (*GetHostedZoneCountOutput, error) { - req, out := c.GetHostedZoneCountRequest(input) - return out, req.Send() -} - -// GetHostedZoneCountWithContext is the same as GetHostedZoneCount with the addition of -// the ability to pass a context and additional request options. -// -// See GetHostedZoneCount for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHostedZoneCountWithContext(ctx aws.Context, input *GetHostedZoneCountInput, opts ...request.Option) (*GetHostedZoneCountOutput, error) { - req, out := c.GetHostedZoneCountRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHostedZoneLimit = "GetHostedZoneLimit" - -// GetHostedZoneLimitRequest generates a "aws/request.Request" representing the -// client's request for the GetHostedZoneLimit operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHostedZoneLimit for more information on using the GetHostedZoneLimit -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHostedZoneLimitRequest method. -// req, resp := client.GetHostedZoneLimitRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneLimit -func (c *Route53) GetHostedZoneLimitRequest(input *GetHostedZoneLimitInput) (req *request.Request, output *GetHostedZoneLimitOutput) { - op := &request.Operation{ - Name: opGetHostedZoneLimit, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzonelimit/{Id}/{Type}", - } - - if input == nil { - input = &GetHostedZoneLimitInput{} - } - - output = &GetHostedZoneLimitOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHostedZoneLimit API operation for Amazon Route 53. -// -// Gets the specified limit for a specified hosted zone, for example, the maximum -// number of records that you can create in the hosted zone. -// -// For the default limit, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. To request a higher limit, open a -// case (https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-route53). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHostedZoneLimit for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeHostedZoneNotPrivate "HostedZoneNotPrivate" -// The specified hosted zone is a public hosted zone, not a private hosted zone. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneLimit -func (c *Route53) GetHostedZoneLimit(input *GetHostedZoneLimitInput) (*GetHostedZoneLimitOutput, error) { - req, out := c.GetHostedZoneLimitRequest(input) - return out, req.Send() -} - -// GetHostedZoneLimitWithContext is the same as GetHostedZoneLimit with the addition of -// the ability to pass a context and additional request options. -// -// See GetHostedZoneLimit for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHostedZoneLimitWithContext(ctx aws.Context, input *GetHostedZoneLimitInput, opts ...request.Option) (*GetHostedZoneLimitOutput, error) { - req, out := c.GetHostedZoneLimitRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetQueryLoggingConfig = "GetQueryLoggingConfig" - -// GetQueryLoggingConfigRequest generates a "aws/request.Request" representing the -// client's request for the GetQueryLoggingConfig operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetQueryLoggingConfig for more information on using the GetQueryLoggingConfig -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetQueryLoggingConfigRequest method. -// req, resp := client.GetQueryLoggingConfigRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetQueryLoggingConfig -func (c *Route53) GetQueryLoggingConfigRequest(input *GetQueryLoggingConfigInput) (req *request.Request, output *GetQueryLoggingConfigOutput) { - op := &request.Operation{ - Name: opGetQueryLoggingConfig, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/queryloggingconfig/{Id}", - } - - if input == nil { - input = &GetQueryLoggingConfigInput{} - } - - output = &GetQueryLoggingConfigOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetQueryLoggingConfig API operation for Amazon Route 53. -// -// Gets information about a specified configuration for DNS query logging. -// -// For more information about DNS query logs, see CreateQueryLoggingConfig and -// Logging DNS Queries (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetQueryLoggingConfig for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchQueryLoggingConfig "NoSuchQueryLoggingConfig" -// There is no DNS query logging configuration with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetQueryLoggingConfig -func (c *Route53) GetQueryLoggingConfig(input *GetQueryLoggingConfigInput) (*GetQueryLoggingConfigOutput, error) { - req, out := c.GetQueryLoggingConfigRequest(input) - return out, req.Send() -} - -// GetQueryLoggingConfigWithContext is the same as GetQueryLoggingConfig with the addition of -// the ability to pass a context and additional request options. -// -// See GetQueryLoggingConfig for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetQueryLoggingConfigWithContext(ctx aws.Context, input *GetQueryLoggingConfigInput, opts ...request.Option) (*GetQueryLoggingConfigOutput, error) { - req, out := c.GetQueryLoggingConfigRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetReusableDelegationSet = "GetReusableDelegationSet" - -// GetReusableDelegationSetRequest generates a "aws/request.Request" representing the -// client's request for the GetReusableDelegationSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetReusableDelegationSet for more information on using the GetReusableDelegationSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetReusableDelegationSetRequest method. -// req, resp := client.GetReusableDelegationSetRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSet -func (c *Route53) GetReusableDelegationSetRequest(input *GetReusableDelegationSetInput) (req *request.Request, output *GetReusableDelegationSetOutput) { - op := &request.Operation{ - Name: opGetReusableDelegationSet, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/delegationset/{Id}", - } - - if input == nil { - input = &GetReusableDelegationSetInput{} - } - - output = &GetReusableDelegationSetOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetReusableDelegationSet API operation for Amazon Route 53. -// -// Retrieves information about a specified reusable delegation set, including -// the four name servers that are assigned to the delegation set. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetReusableDelegationSet for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSet -func (c *Route53) GetReusableDelegationSet(input *GetReusableDelegationSetInput) (*GetReusableDelegationSetOutput, error) { - req, out := c.GetReusableDelegationSetRequest(input) - return out, req.Send() -} - -// GetReusableDelegationSetWithContext is the same as GetReusableDelegationSet with the addition of -// the ability to pass a context and additional request options. -// -// See GetReusableDelegationSet for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetReusableDelegationSetWithContext(ctx aws.Context, input *GetReusableDelegationSetInput, opts ...request.Option) (*GetReusableDelegationSetOutput, error) { - req, out := c.GetReusableDelegationSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetReusableDelegationSetLimit = "GetReusableDelegationSetLimit" - -// GetReusableDelegationSetLimitRequest generates a "aws/request.Request" representing the -// client's request for the GetReusableDelegationSetLimit operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetReusableDelegationSetLimit for more information on using the GetReusableDelegationSetLimit -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetReusableDelegationSetLimitRequest method. -// req, resp := client.GetReusableDelegationSetLimitRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSetLimit -func (c *Route53) GetReusableDelegationSetLimitRequest(input *GetReusableDelegationSetLimitInput) (req *request.Request, output *GetReusableDelegationSetLimitOutput) { - op := &request.Operation{ - Name: opGetReusableDelegationSetLimit, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/reusabledelegationsetlimit/{Id}/{Type}", - } - - if input == nil { - input = &GetReusableDelegationSetLimitInput{} - } - - output = &GetReusableDelegationSetLimitOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetReusableDelegationSetLimit API operation for Amazon Route 53. -// -// Gets the maximum number of hosted zones that you can associate with the specified -// reusable delegation set. -// -// For the default limit, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. To request a higher limit, open a -// case (https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-route53). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetReusableDelegationSetLimit for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSetLimit -func (c *Route53) GetReusableDelegationSetLimit(input *GetReusableDelegationSetLimitInput) (*GetReusableDelegationSetLimitOutput, error) { - req, out := c.GetReusableDelegationSetLimitRequest(input) - return out, req.Send() -} - -// GetReusableDelegationSetLimitWithContext is the same as GetReusableDelegationSetLimit with the addition of -// the ability to pass a context and additional request options. -// -// See GetReusableDelegationSetLimit for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetReusableDelegationSetLimitWithContext(ctx aws.Context, input *GetReusableDelegationSetLimitInput, opts ...request.Option) (*GetReusableDelegationSetLimitOutput, error) { - req, out := c.GetReusableDelegationSetLimitRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetTrafficPolicy = "GetTrafficPolicy" - -// GetTrafficPolicyRequest generates a "aws/request.Request" representing the -// client's request for the GetTrafficPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetTrafficPolicy for more information on using the GetTrafficPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetTrafficPolicyRequest method. -// req, resp := client.GetTrafficPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicy -func (c *Route53) GetTrafficPolicyRequest(input *GetTrafficPolicyInput) (req *request.Request, output *GetTrafficPolicyOutput) { - op := &request.Operation{ - Name: opGetTrafficPolicy, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}/{Version}", - } - - if input == nil { - input = &GetTrafficPolicyInput{} - } - - output = &GetTrafficPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetTrafficPolicy API operation for Amazon Route 53. -// -// Gets information about a specific traffic policy version. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetTrafficPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicy -func (c *Route53) GetTrafficPolicy(input *GetTrafficPolicyInput) (*GetTrafficPolicyOutput, error) { - req, out := c.GetTrafficPolicyRequest(input) - return out, req.Send() -} - -// GetTrafficPolicyWithContext is the same as GetTrafficPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See GetTrafficPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetTrafficPolicyWithContext(ctx aws.Context, input *GetTrafficPolicyInput, opts ...request.Option) (*GetTrafficPolicyOutput, error) { - req, out := c.GetTrafficPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetTrafficPolicyInstance = "GetTrafficPolicyInstance" - -// GetTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the GetTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetTrafficPolicyInstance for more information on using the GetTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetTrafficPolicyInstanceRequest method. -// req, resp := client.GetTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstance -func (c *Route53) GetTrafficPolicyInstanceRequest(input *GetTrafficPolicyInstanceInput) (req *request.Request, output *GetTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opGetTrafficPolicyInstance, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstance/{Id}", - } - - if input == nil { - input = &GetTrafficPolicyInstanceInput{} - } - - output = &GetTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetTrafficPolicyInstance API operation for Amazon Route 53. -// -// Gets information about a specified traffic policy instance. -// -// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance -// request, there's a brief delay while Amazon Route 53 creates the resource -// record sets that are specified in the traffic policy definition. For more -// information, see the State response element. -// -// In the Amazon Route 53 console, traffic policy instances are known as policy -// records. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstance -func (c *Route53) GetTrafficPolicyInstance(input *GetTrafficPolicyInstanceInput) (*GetTrafficPolicyInstanceOutput, error) { - req, out := c.GetTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// GetTrafficPolicyInstanceWithContext is the same as GetTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See GetTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetTrafficPolicyInstanceWithContext(ctx aws.Context, input *GetTrafficPolicyInstanceInput, opts ...request.Option) (*GetTrafficPolicyInstanceOutput, error) { - req, out := c.GetTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetTrafficPolicyInstanceCount = "GetTrafficPolicyInstanceCount" - -// GetTrafficPolicyInstanceCountRequest generates a "aws/request.Request" representing the -// client's request for the GetTrafficPolicyInstanceCount operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetTrafficPolicyInstanceCount for more information on using the GetTrafficPolicyInstanceCount -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetTrafficPolicyInstanceCountRequest method. -// req, resp := client.GetTrafficPolicyInstanceCountRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstanceCount -func (c *Route53) GetTrafficPolicyInstanceCountRequest(input *GetTrafficPolicyInstanceCountInput) (req *request.Request, output *GetTrafficPolicyInstanceCountOutput) { - op := &request.Operation{ - Name: opGetTrafficPolicyInstanceCount, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstancecount", - } - - if input == nil { - input = &GetTrafficPolicyInstanceCountInput{} - } - - output = &GetTrafficPolicyInstanceCountOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetTrafficPolicyInstanceCount API operation for Amazon Route 53. -// -// Gets the number of traffic policy instances that are associated with the -// current AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetTrafficPolicyInstanceCount for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstanceCount -func (c *Route53) GetTrafficPolicyInstanceCount(input *GetTrafficPolicyInstanceCountInput) (*GetTrafficPolicyInstanceCountOutput, error) { - req, out := c.GetTrafficPolicyInstanceCountRequest(input) - return out, req.Send() -} - -// GetTrafficPolicyInstanceCountWithContext is the same as GetTrafficPolicyInstanceCount with the addition of -// the ability to pass a context and additional request options. -// -// See GetTrafficPolicyInstanceCount for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetTrafficPolicyInstanceCountWithContext(ctx aws.Context, input *GetTrafficPolicyInstanceCountInput, opts ...request.Option) (*GetTrafficPolicyInstanceCountOutput, error) { - req, out := c.GetTrafficPolicyInstanceCountRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListGeoLocations = "ListGeoLocations" - -// ListGeoLocationsRequest generates a "aws/request.Request" representing the -// client's request for the ListGeoLocations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListGeoLocations for more information on using the ListGeoLocations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListGeoLocationsRequest method. -// req, resp := client.ListGeoLocationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListGeoLocations -func (c *Route53) ListGeoLocationsRequest(input *ListGeoLocationsInput) (req *request.Request, output *ListGeoLocationsOutput) { - op := &request.Operation{ - Name: opListGeoLocations, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/geolocations", - } - - if input == nil { - input = &ListGeoLocationsInput{} - } - - output = &ListGeoLocationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListGeoLocations API operation for Amazon Route 53. -// -// Retrieves a list of supported geo locations. -// -// Countries are listed first, and continents are listed last. If Amazon Route -// 53 supports subdivisions for a country (for example, states or provinces), -// the subdivisions for that country are listed in alphabetical order immediately -// after the corresponding country. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListGeoLocations for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListGeoLocations -func (c *Route53) ListGeoLocations(input *ListGeoLocationsInput) (*ListGeoLocationsOutput, error) { - req, out := c.ListGeoLocationsRequest(input) - return out, req.Send() -} - -// ListGeoLocationsWithContext is the same as ListGeoLocations with the addition of -// the ability to pass a context and additional request options. -// -// See ListGeoLocations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListGeoLocationsWithContext(ctx aws.Context, input *ListGeoLocationsInput, opts ...request.Option) (*ListGeoLocationsOutput, error) { - req, out := c.ListGeoLocationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListHealthChecks = "ListHealthChecks" - -// ListHealthChecksRequest generates a "aws/request.Request" representing the -// client's request for the ListHealthChecks operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListHealthChecks for more information on using the ListHealthChecks -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListHealthChecksRequest method. -// req, resp := client.ListHealthChecksRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHealthChecks -func (c *Route53) ListHealthChecksRequest(input *ListHealthChecksInput) (req *request.Request, output *ListHealthChecksOutput) { - op := &request.Operation{ - Name: opListHealthChecks, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck", - Paginator: &request.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"NextMarker"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListHealthChecksInput{} - } - - output = &ListHealthChecksOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListHealthChecks API operation for Amazon Route 53. -// -// Retrieve a list of the health checks that are associated with the current -// AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListHealthChecks for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeIncompatibleVersion "IncompatibleVersion" -// The resource you're trying to access is unsupported on this Amazon Route -// 53 endpoint. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHealthChecks -func (c *Route53) ListHealthChecks(input *ListHealthChecksInput) (*ListHealthChecksOutput, error) { - req, out := c.ListHealthChecksRequest(input) - return out, req.Send() -} - -// ListHealthChecksWithContext is the same as ListHealthChecks with the addition of -// the ability to pass a context and additional request options. -// -// See ListHealthChecks for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHealthChecksWithContext(ctx aws.Context, input *ListHealthChecksInput, opts ...request.Option) (*ListHealthChecksOutput, error) { - req, out := c.ListHealthChecksRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListHealthChecksPages iterates over the pages of a ListHealthChecks operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListHealthChecks method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListHealthChecks operation. -// pageNum := 0 -// err := client.ListHealthChecksPages(params, -// func(page *ListHealthChecksOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *Route53) ListHealthChecksPages(input *ListHealthChecksInput, fn func(*ListHealthChecksOutput, bool) bool) error { - return c.ListHealthChecksPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListHealthChecksPagesWithContext same as ListHealthChecksPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHealthChecksPagesWithContext(ctx aws.Context, input *ListHealthChecksInput, fn func(*ListHealthChecksOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListHealthChecksInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListHealthChecksRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListHealthChecksOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListHostedZones = "ListHostedZones" - -// ListHostedZonesRequest generates a "aws/request.Request" representing the -// client's request for the ListHostedZones operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListHostedZones for more information on using the ListHostedZones -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListHostedZonesRequest method. -// req, resp := client.ListHostedZonesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZones -func (c *Route53) ListHostedZonesRequest(input *ListHostedZonesInput) (req *request.Request, output *ListHostedZonesOutput) { - op := &request.Operation{ - Name: opListHostedZones, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone", - Paginator: &request.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"NextMarker"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListHostedZonesInput{} - } - - output = &ListHostedZonesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListHostedZones API operation for Amazon Route 53. -// -// Retrieves a list of the public and private hosted zones that are associated -// with the current AWS account. The response includes a HostedZones child element -// for each hosted zone. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of hosted zones, you can use the maxitems parameter to list them in -// groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListHostedZones for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZones -func (c *Route53) ListHostedZones(input *ListHostedZonesInput) (*ListHostedZonesOutput, error) { - req, out := c.ListHostedZonesRequest(input) - return out, req.Send() -} - -// ListHostedZonesWithContext is the same as ListHostedZones with the addition of -// the ability to pass a context and additional request options. -// -// See ListHostedZones for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHostedZonesWithContext(ctx aws.Context, input *ListHostedZonesInput, opts ...request.Option) (*ListHostedZonesOutput, error) { - req, out := c.ListHostedZonesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListHostedZonesPages iterates over the pages of a ListHostedZones operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListHostedZones method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListHostedZones operation. -// pageNum := 0 -// err := client.ListHostedZonesPages(params, -// func(page *ListHostedZonesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *Route53) ListHostedZonesPages(input *ListHostedZonesInput, fn func(*ListHostedZonesOutput, bool) bool) error { - return c.ListHostedZonesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListHostedZonesPagesWithContext same as ListHostedZonesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHostedZonesPagesWithContext(ctx aws.Context, input *ListHostedZonesInput, fn func(*ListHostedZonesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListHostedZonesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListHostedZonesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListHostedZonesOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListHostedZonesByName = "ListHostedZonesByName" - -// ListHostedZonesByNameRequest generates a "aws/request.Request" representing the -// client's request for the ListHostedZonesByName operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListHostedZonesByName for more information on using the ListHostedZonesByName -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListHostedZonesByNameRequest method. -// req, resp := client.ListHostedZonesByNameRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByName -func (c *Route53) ListHostedZonesByNameRequest(input *ListHostedZonesByNameInput) (req *request.Request, output *ListHostedZonesByNameOutput) { - op := &request.Operation{ - Name: opListHostedZonesByName, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzonesbyname", - } - - if input == nil { - input = &ListHostedZonesByNameInput{} - } - - output = &ListHostedZonesByNameOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListHostedZonesByName API operation for Amazon Route 53. -// -// Retrieves a list of your hosted zones in lexicographic order. The response -// includes a HostedZones child element for each hosted zone created by the -// current AWS account. -// -// ListHostedZonesByName sorts hosted zones by name with the labels reversed. -// For example: -// -// com.example.www. -// -// Note the trailing dot, which can change the sort order in some circumstances. -// -// If the domain name includes escape characters or Punycode, ListHostedZonesByName -// alphabetizes the domain name using the escaped or Punycoded value, which -// is the format that Amazon Route 53 saves in its database. For example, to -// create a hosted zone for exämple.com, you specify ex\344mple.com for the -// domain name. ListHostedZonesByName alphabetizes it as: -// -// com.ex\344mple. -// -// The labels are reversed and alphabetized using the escaped value. For more -// information about valid domain name formats, including internationalized -// domain names, see DNS Domain Name Format (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html) -// in the Amazon Route 53 Developer Guide. -// -// Amazon Route 53 returns up to 100 items in each response. If you have a lot -// of hosted zones, use the MaxItems parameter to list them in groups of up -// to 100. The response includes values that help navigate from one group of -// MaxItems hosted zones to the next: -// -// * The DNSName and HostedZoneId elements in the response contain the values, -// if any, specified for the dnsname and hostedzoneid parameters in the request -// that produced the current response. -// -// * The MaxItems element in the response contains the value, if any, that -// you specified for the maxitems parameter in the request that produced -// the current response. -// -// * If the value of IsTruncated in the response is true, there are more -// hosted zones associated with the current AWS account. -// -// If IsTruncated is false, this response includes the last hosted zone that -// is associated with the current account. The NextDNSName element and NextHostedZoneId -// elements are omitted from the response. -// -// * The NextDNSName and NextHostedZoneId elements in the response contain -// the domain name and the hosted zone ID of the next hosted zone that is -// associated with the current AWS account. If you want to list more hosted -// zones, make another call to ListHostedZonesByName, and specify the value -// of NextDNSName and NextHostedZoneId in the dnsname and hostedzoneid parameters, -// respectively. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListHostedZonesByName for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidDomainName "InvalidDomainName" -// The specified domain name is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByName -func (c *Route53) ListHostedZonesByName(input *ListHostedZonesByNameInput) (*ListHostedZonesByNameOutput, error) { - req, out := c.ListHostedZonesByNameRequest(input) - return out, req.Send() -} - -// ListHostedZonesByNameWithContext is the same as ListHostedZonesByName with the addition of -// the ability to pass a context and additional request options. -// -// See ListHostedZonesByName for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHostedZonesByNameWithContext(ctx aws.Context, input *ListHostedZonesByNameInput, opts ...request.Option) (*ListHostedZonesByNameOutput, error) { - req, out := c.ListHostedZonesByNameRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListQueryLoggingConfigs = "ListQueryLoggingConfigs" - -// ListQueryLoggingConfigsRequest generates a "aws/request.Request" representing the -// client's request for the ListQueryLoggingConfigs operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListQueryLoggingConfigs for more information on using the ListQueryLoggingConfigs -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListQueryLoggingConfigsRequest method. -// req, resp := client.ListQueryLoggingConfigsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListQueryLoggingConfigs -func (c *Route53) ListQueryLoggingConfigsRequest(input *ListQueryLoggingConfigsInput) (req *request.Request, output *ListQueryLoggingConfigsOutput) { - op := &request.Operation{ - Name: opListQueryLoggingConfigs, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/queryloggingconfig", - } - - if input == nil { - input = &ListQueryLoggingConfigsInput{} - } - - output = &ListQueryLoggingConfigsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListQueryLoggingConfigs API operation for Amazon Route 53. -// -// Lists the configurations for DNS query logging that are associated with the -// current AWS account or the configuration that is associated with a specified -// hosted zone. -// -// For more information about DNS query logs, see CreateQueryLoggingConfig. -// Additional information, including the format of DNS query logs, appears in -// Logging DNS Queries (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListQueryLoggingConfigs for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidPaginationToken "InvalidPaginationToken" -// The value that you specified to get the second or subsequent page of results -// is invalid. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListQueryLoggingConfigs -func (c *Route53) ListQueryLoggingConfigs(input *ListQueryLoggingConfigsInput) (*ListQueryLoggingConfigsOutput, error) { - req, out := c.ListQueryLoggingConfigsRequest(input) - return out, req.Send() -} - -// ListQueryLoggingConfigsWithContext is the same as ListQueryLoggingConfigs with the addition of -// the ability to pass a context and additional request options. -// -// See ListQueryLoggingConfigs for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListQueryLoggingConfigsWithContext(ctx aws.Context, input *ListQueryLoggingConfigsInput, opts ...request.Option) (*ListQueryLoggingConfigsOutput, error) { - req, out := c.ListQueryLoggingConfigsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListResourceRecordSets = "ListResourceRecordSets" - -// ListResourceRecordSetsRequest generates a "aws/request.Request" representing the -// client's request for the ListResourceRecordSets operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListResourceRecordSets for more information on using the ListResourceRecordSets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListResourceRecordSetsRequest method. -// req, resp := client.ListResourceRecordSetsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListResourceRecordSets -func (c *Route53) ListResourceRecordSetsRequest(input *ListResourceRecordSetsInput) (req *request.Request, output *ListResourceRecordSetsOutput) { - op := &request.Operation{ - Name: opListResourceRecordSets, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone/{Id}/rrset", - Paginator: &request.Paginator{ - InputTokens: []string{"StartRecordName", "StartRecordType", "StartRecordIdentifier"}, - OutputTokens: []string{"NextRecordName", "NextRecordType", "NextRecordIdentifier"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListResourceRecordSetsInput{} - } - - output = &ListResourceRecordSetsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListResourceRecordSets API operation for Amazon Route 53. -// -// Lists the resource record sets in a specified hosted zone. -// -// ListResourceRecordSets returns up to 100 resource record sets at a time in -// ASCII order, beginning at a position specified by the name and type elements. -// The action sorts results first by DNS name with the labels reversed, for -// example: -// -// com.example.www. -// -// Note the trailing dot, which can change the sort order in some circumstances. -// -// When multiple records have the same DNS name, the action sorts results by -// the record type. -// -// You can use the name and type elements to adjust the beginning position of -// the list of resource record sets returned: -// -// If you do not specify Name or TypeThe results begin with the first resource -// record set that the hosted zone contains. -// -// If you specify Name but not TypeThe results begin with the first resource -// record set in the list whose name is greater than or equal to Name. -// -// If you specify Type but not NameAmazon Route 53 returns the InvalidInput -// error. -// -// If you specify both Name and TypeThe results begin with the first resource -// record set in the list whose name is greater than or equal to Name, and whose -// type is greater than or equal to Type. -// -// This action returns the most current version of the records. This includes -// records that are PENDING, and that are not yet available on all Amazon Route -// 53 DNS servers. -// -// To ensure that you get an accurate listing of the resource record sets for -// a hosted zone at a point in time, do not submit a ChangeResourceRecordSets -// request while you're paging through the results of a ListResourceRecordSets -// request. If you do, some pages may display results without the latest changes -// while other pages display results with the latest changes. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListResourceRecordSets for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListResourceRecordSets -func (c *Route53) ListResourceRecordSets(input *ListResourceRecordSetsInput) (*ListResourceRecordSetsOutput, error) { - req, out := c.ListResourceRecordSetsRequest(input) - return out, req.Send() -} - -// ListResourceRecordSetsWithContext is the same as ListResourceRecordSets with the addition of -// the ability to pass a context and additional request options. -// -// See ListResourceRecordSets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListResourceRecordSetsWithContext(ctx aws.Context, input *ListResourceRecordSetsInput, opts ...request.Option) (*ListResourceRecordSetsOutput, error) { - req, out := c.ListResourceRecordSetsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListResourceRecordSetsPages iterates over the pages of a ListResourceRecordSets operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListResourceRecordSets method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListResourceRecordSets operation. -// pageNum := 0 -// err := client.ListResourceRecordSetsPages(params, -// func(page *ListResourceRecordSetsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *Route53) ListResourceRecordSetsPages(input *ListResourceRecordSetsInput, fn func(*ListResourceRecordSetsOutput, bool) bool) error { - return c.ListResourceRecordSetsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListResourceRecordSetsPagesWithContext same as ListResourceRecordSetsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListResourceRecordSetsPagesWithContext(ctx aws.Context, input *ListResourceRecordSetsInput, fn func(*ListResourceRecordSetsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListResourceRecordSetsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListResourceRecordSetsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListResourceRecordSetsOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListReusableDelegationSets = "ListReusableDelegationSets" - -// ListReusableDelegationSetsRequest generates a "aws/request.Request" representing the -// client's request for the ListReusableDelegationSets operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListReusableDelegationSets for more information on using the ListReusableDelegationSets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListReusableDelegationSetsRequest method. -// req, resp := client.ListReusableDelegationSetsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListReusableDelegationSets -func (c *Route53) ListReusableDelegationSetsRequest(input *ListReusableDelegationSetsInput) (req *request.Request, output *ListReusableDelegationSetsOutput) { - op := &request.Operation{ - Name: opListReusableDelegationSets, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/delegationset", - } - - if input == nil { - input = &ListReusableDelegationSetsInput{} - } - - output = &ListReusableDelegationSetsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListReusableDelegationSets API operation for Amazon Route 53. -// -// Retrieves a list of the reusable delegation sets that are associated with -// the current AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListReusableDelegationSets for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListReusableDelegationSets -func (c *Route53) ListReusableDelegationSets(input *ListReusableDelegationSetsInput) (*ListReusableDelegationSetsOutput, error) { - req, out := c.ListReusableDelegationSetsRequest(input) - return out, req.Send() -} - -// ListReusableDelegationSetsWithContext is the same as ListReusableDelegationSets with the addition of -// the ability to pass a context and additional request options. -// -// See ListReusableDelegationSets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListReusableDelegationSetsWithContext(ctx aws.Context, input *ListReusableDelegationSetsInput, opts ...request.Option) (*ListReusableDelegationSetsOutput, error) { - req, out := c.ListReusableDelegationSetsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTagsForResource = "ListTagsForResource" - -// ListTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTagsForResource for more information on using the ListTagsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTagsForResourceRequest method. -// req, resp := client.ListTagsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResource -func (c *Route53) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { - op := &request.Operation{ - Name: opListTagsForResource, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/tags/{ResourceType}/{ResourceId}", - } - - if input == nil { - input = &ListTagsForResourceInput{} - } - - output = &ListTagsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTagsForResource API operation for Amazon Route 53. -// -// Lists tags for one health check or hosted zone. -// -// For information about using tags for cost allocation, see Using Cost Allocation -// Tags (http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) -// in the AWS Billing and Cost Management User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTagsForResource for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeThrottlingException "ThrottlingException" -// The limit on the number of requests per second was exceeded. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResource -func (c *Route53) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) - return out, req.Send() -} - -// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See ListTagsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTagsForResources = "ListTagsForResources" - -// ListTagsForResourcesRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResources operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTagsForResources for more information on using the ListTagsForResources -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTagsForResourcesRequest method. -// req, resp := client.ListTagsForResourcesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResources -func (c *Route53) ListTagsForResourcesRequest(input *ListTagsForResourcesInput) (req *request.Request, output *ListTagsForResourcesOutput) { - op := &request.Operation{ - Name: opListTagsForResources, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/tags/{ResourceType}", - } - - if input == nil { - input = &ListTagsForResourcesInput{} - } - - output = &ListTagsForResourcesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTagsForResources API operation for Amazon Route 53. -// -// Lists tags for up to 10 health checks or hosted zones. -// -// For information about using tags for cost allocation, see Using Cost Allocation -// Tags (http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) -// in the AWS Billing and Cost Management User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTagsForResources for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeThrottlingException "ThrottlingException" -// The limit on the number of requests per second was exceeded. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResources -func (c *Route53) ListTagsForResources(input *ListTagsForResourcesInput) (*ListTagsForResourcesOutput, error) { - req, out := c.ListTagsForResourcesRequest(input) - return out, req.Send() -} - -// ListTagsForResourcesWithContext is the same as ListTagsForResources with the addition of -// the ability to pass a context and additional request options. -// -// See ListTagsForResources for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTagsForResourcesWithContext(ctx aws.Context, input *ListTagsForResourcesInput, opts ...request.Option) (*ListTagsForResourcesOutput, error) { - req, out := c.ListTagsForResourcesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicies = "ListTrafficPolicies" - -// ListTrafficPoliciesRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicies operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicies for more information on using the ListTrafficPolicies -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPoliciesRequest method. -// req, resp := client.ListTrafficPoliciesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicies -func (c *Route53) ListTrafficPoliciesRequest(input *ListTrafficPoliciesInput) (req *request.Request, output *ListTrafficPoliciesOutput) { - op := &request.Operation{ - Name: opListTrafficPolicies, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicies", - } - - if input == nil { - input = &ListTrafficPoliciesInput{} - } - - output = &ListTrafficPoliciesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicies API operation for Amazon Route 53. -// -// Gets information about the latest version for every traffic policy that is -// associated with the current AWS account. Policies are listed in the order -// in which they were created. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicies for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicies -func (c *Route53) ListTrafficPolicies(input *ListTrafficPoliciesInput) (*ListTrafficPoliciesOutput, error) { - req, out := c.ListTrafficPoliciesRequest(input) - return out, req.Send() -} - -// ListTrafficPoliciesWithContext is the same as ListTrafficPolicies with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicies for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPoliciesWithContext(ctx aws.Context, input *ListTrafficPoliciesInput, opts ...request.Option) (*ListTrafficPoliciesOutput, error) { - req, out := c.ListTrafficPoliciesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyInstances = "ListTrafficPolicyInstances" - -// ListTrafficPolicyInstancesRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyInstances operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyInstances for more information on using the ListTrafficPolicyInstances -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyInstancesRequest method. -// req, resp := client.ListTrafficPolicyInstancesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstances -func (c *Route53) ListTrafficPolicyInstancesRequest(input *ListTrafficPolicyInstancesInput) (req *request.Request, output *ListTrafficPolicyInstancesOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyInstances, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstances", - } - - if input == nil { - input = &ListTrafficPolicyInstancesInput{} - } - - output = &ListTrafficPolicyInstancesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyInstances API operation for Amazon Route 53. -// -// Gets information about the traffic policy instances that you created by using -// the current AWS account. -// -// After you submit an UpdateTrafficPolicyInstance request, there's a brief -// delay while Amazon Route 53 creates the resource record sets that are specified -// in the traffic policy definition. For more information, see the State response -// element. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policy instances, you can use the MaxItems parameter to -// list them in groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyInstances for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstances -func (c *Route53) ListTrafficPolicyInstances(input *ListTrafficPolicyInstancesInput) (*ListTrafficPolicyInstancesOutput, error) { - req, out := c.ListTrafficPolicyInstancesRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyInstancesWithContext is the same as ListTrafficPolicyInstances with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyInstances for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyInstancesWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesInput, opts ...request.Option) (*ListTrafficPolicyInstancesOutput, error) { - req, out := c.ListTrafficPolicyInstancesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyInstancesByHostedZone = "ListTrafficPolicyInstancesByHostedZone" - -// ListTrafficPolicyInstancesByHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyInstancesByHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyInstancesByHostedZone for more information on using the ListTrafficPolicyInstancesByHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyInstancesByHostedZoneRequest method. -// req, resp := client.ListTrafficPolicyInstancesByHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByHostedZone -func (c *Route53) ListTrafficPolicyInstancesByHostedZoneRequest(input *ListTrafficPolicyInstancesByHostedZoneInput) (req *request.Request, output *ListTrafficPolicyInstancesByHostedZoneOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyInstancesByHostedZone, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstances/hostedzone", - } - - if input == nil { - input = &ListTrafficPolicyInstancesByHostedZoneInput{} - } - - output = &ListTrafficPolicyInstancesByHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyInstancesByHostedZone API operation for Amazon Route 53. -// -// Gets information about the traffic policy instances that you created in a -// specified hosted zone. -// -// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance -// request, there's a brief delay while Amazon Route 53 creates the resource -// record sets that are specified in the traffic policy definition. For more -// information, see the State response element. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policy instances, you can use the MaxItems parameter to -// list them in groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyInstancesByHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByHostedZone -func (c *Route53) ListTrafficPolicyInstancesByHostedZone(input *ListTrafficPolicyInstancesByHostedZoneInput) (*ListTrafficPolicyInstancesByHostedZoneOutput, error) { - req, out := c.ListTrafficPolicyInstancesByHostedZoneRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyInstancesByHostedZoneWithContext is the same as ListTrafficPolicyInstancesByHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyInstancesByHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyInstancesByHostedZoneWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesByHostedZoneInput, opts ...request.Option) (*ListTrafficPolicyInstancesByHostedZoneOutput, error) { - req, out := c.ListTrafficPolicyInstancesByHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyInstancesByPolicy = "ListTrafficPolicyInstancesByPolicy" - -// ListTrafficPolicyInstancesByPolicyRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyInstancesByPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyInstancesByPolicy for more information on using the ListTrafficPolicyInstancesByPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyInstancesByPolicyRequest method. -// req, resp := client.ListTrafficPolicyInstancesByPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByPolicy -func (c *Route53) ListTrafficPolicyInstancesByPolicyRequest(input *ListTrafficPolicyInstancesByPolicyInput) (req *request.Request, output *ListTrafficPolicyInstancesByPolicyOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyInstancesByPolicy, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstances/trafficpolicy", - } - - if input == nil { - input = &ListTrafficPolicyInstancesByPolicyInput{} - } - - output = &ListTrafficPolicyInstancesByPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyInstancesByPolicy API operation for Amazon Route 53. -// -// Gets information about the traffic policy instances that you created by using -// a specify traffic policy version. -// -// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance -// request, there's a brief delay while Amazon Route 53 creates the resource -// record sets that are specified in the traffic policy definition. For more -// information, see the State response element. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policy instances, you can use the MaxItems parameter to -// list them in groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyInstancesByPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByPolicy -func (c *Route53) ListTrafficPolicyInstancesByPolicy(input *ListTrafficPolicyInstancesByPolicyInput) (*ListTrafficPolicyInstancesByPolicyOutput, error) { - req, out := c.ListTrafficPolicyInstancesByPolicyRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyInstancesByPolicyWithContext is the same as ListTrafficPolicyInstancesByPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyInstancesByPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyInstancesByPolicyWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesByPolicyInput, opts ...request.Option) (*ListTrafficPolicyInstancesByPolicyOutput, error) { - req, out := c.ListTrafficPolicyInstancesByPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyVersions = "ListTrafficPolicyVersions" - -// ListTrafficPolicyVersionsRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyVersions operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyVersions for more information on using the ListTrafficPolicyVersions -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyVersionsRequest method. -// req, resp := client.ListTrafficPolicyVersionsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyVersions -func (c *Route53) ListTrafficPolicyVersionsRequest(input *ListTrafficPolicyVersionsInput) (req *request.Request, output *ListTrafficPolicyVersionsOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyVersions, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicies/{Id}/versions", - } - - if input == nil { - input = &ListTrafficPolicyVersionsInput{} - } - - output = &ListTrafficPolicyVersionsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyVersions API operation for Amazon Route 53. -// -// Gets information about all of the versions for a specified traffic policy. -// -// Traffic policy versions are listed in numerical order by VersionNumber. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyVersions for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyVersions -func (c *Route53) ListTrafficPolicyVersions(input *ListTrafficPolicyVersionsInput) (*ListTrafficPolicyVersionsOutput, error) { - req, out := c.ListTrafficPolicyVersionsRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyVersionsWithContext is the same as ListTrafficPolicyVersions with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyVersions for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyVersionsWithContext(ctx aws.Context, input *ListTrafficPolicyVersionsInput, opts ...request.Option) (*ListTrafficPolicyVersionsOutput, error) { - req, out := c.ListTrafficPolicyVersionsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListVPCAssociationAuthorizations = "ListVPCAssociationAuthorizations" - -// ListVPCAssociationAuthorizationsRequest generates a "aws/request.Request" representing the -// client's request for the ListVPCAssociationAuthorizations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListVPCAssociationAuthorizations for more information on using the ListVPCAssociationAuthorizations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListVPCAssociationAuthorizationsRequest method. -// req, resp := client.ListVPCAssociationAuthorizationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations -func (c *Route53) ListVPCAssociationAuthorizationsRequest(input *ListVPCAssociationAuthorizationsInput) (req *request.Request, output *ListVPCAssociationAuthorizationsOutput) { - op := &request.Operation{ - Name: opListVPCAssociationAuthorizations, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone/{Id}/authorizevpcassociation", - } - - if input == nil { - input = &ListVPCAssociationAuthorizationsInput{} - } - - output = &ListVPCAssociationAuthorizationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListVPCAssociationAuthorizations API operation for Amazon Route 53. -// -// Gets a list of the VPCs that were created by other accounts and that can -// be associated with a specified hosted zone because you've submitted one or -// more CreateVPCAssociationAuthorization requests. -// -// The response includes a VPCs element with a VPC child element for each VPC -// that can be associated with the hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListVPCAssociationAuthorizations for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidPaginationToken "InvalidPaginationToken" -// The value that you specified to get the second or subsequent page of results -// is invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations -func (c *Route53) ListVPCAssociationAuthorizations(input *ListVPCAssociationAuthorizationsInput) (*ListVPCAssociationAuthorizationsOutput, error) { - req, out := c.ListVPCAssociationAuthorizationsRequest(input) - return out, req.Send() -} - -// ListVPCAssociationAuthorizationsWithContext is the same as ListVPCAssociationAuthorizations with the addition of -// the ability to pass a context and additional request options. -// -// See ListVPCAssociationAuthorizations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListVPCAssociationAuthorizationsWithContext(ctx aws.Context, input *ListVPCAssociationAuthorizationsInput, opts ...request.Option) (*ListVPCAssociationAuthorizationsOutput, error) { - req, out := c.ListVPCAssociationAuthorizationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opTestDNSAnswer = "TestDNSAnswer" - -// TestDNSAnswerRequest generates a "aws/request.Request" representing the -// client's request for the TestDNSAnswer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See TestDNSAnswer for more information on using the TestDNSAnswer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the TestDNSAnswerRequest method. -// req, resp := client.TestDNSAnswerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/TestDNSAnswer -func (c *Route53) TestDNSAnswerRequest(input *TestDNSAnswerInput) (req *request.Request, output *TestDNSAnswerOutput) { - op := &request.Operation{ - Name: opTestDNSAnswer, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/testdnsanswer", - } - - if input == nil { - input = &TestDNSAnswerInput{} - } - - output = &TestDNSAnswerOutput{} - req = c.newRequest(op, input, output) - return -} - -// TestDNSAnswer API operation for Amazon Route 53. -// -// Gets the value that Amazon Route 53 returns in response to a DNS request -// for a specified record name and type. You can optionally specify the IP address -// of a DNS resolver, an EDNS0 client subnet IP address, and a subnet mask. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation TestDNSAnswer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/TestDNSAnswer -func (c *Route53) TestDNSAnswer(input *TestDNSAnswerInput) (*TestDNSAnswerOutput, error) { - req, out := c.TestDNSAnswerRequest(input) - return out, req.Send() -} - -// TestDNSAnswerWithContext is the same as TestDNSAnswer with the addition of -// the ability to pass a context and additional request options. -// -// See TestDNSAnswer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) TestDNSAnswerWithContext(ctx aws.Context, input *TestDNSAnswerInput, opts ...request.Option) (*TestDNSAnswerOutput, error) { - req, out := c.TestDNSAnswerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateHealthCheck = "UpdateHealthCheck" - -// UpdateHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the UpdateHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateHealthCheck for more information on using the UpdateHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateHealthCheckRequest method. -// req, resp := client.UpdateHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHealthCheck -func (c *Route53) UpdateHealthCheckRequest(input *UpdateHealthCheckInput) (req *request.Request, output *UpdateHealthCheckOutput) { - op := &request.Operation{ - Name: opUpdateHealthCheck, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}", - } - - if input == nil { - input = &UpdateHealthCheckInput{} - } - - output = &UpdateHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateHealthCheck API operation for Amazon Route 53. -// -// Updates an existing health check. Note that some values can't be updated. -// -// For more information about updating health checks, see Creating, Updating, -// and Deleting Health Checks (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-deleting.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeHealthCheckVersionMismatch "HealthCheckVersionMismatch" -// The value of HealthCheckVersion in the request doesn't match the value of -// HealthCheckVersion in the health check. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHealthCheck -func (c *Route53) UpdateHealthCheck(input *UpdateHealthCheckInput) (*UpdateHealthCheckOutput, error) { - req, out := c.UpdateHealthCheckRequest(input) - return out, req.Send() -} - -// UpdateHealthCheckWithContext is the same as UpdateHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateHealthCheckWithContext(ctx aws.Context, input *UpdateHealthCheckInput, opts ...request.Option) (*UpdateHealthCheckOutput, error) { - req, out := c.UpdateHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateHostedZoneComment = "UpdateHostedZoneComment" - -// UpdateHostedZoneCommentRequest generates a "aws/request.Request" representing the -// client's request for the UpdateHostedZoneComment operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateHostedZoneComment for more information on using the UpdateHostedZoneComment -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateHostedZoneCommentRequest method. -// req, resp := client.UpdateHostedZoneCommentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneComment -func (c *Route53) UpdateHostedZoneCommentRequest(input *UpdateHostedZoneCommentInput) (req *request.Request, output *UpdateHostedZoneCommentOutput) { - op := &request.Operation{ - Name: opUpdateHostedZoneComment, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}", - } - - if input == nil { - input = &UpdateHostedZoneCommentInput{} - } - - output = &UpdateHostedZoneCommentOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateHostedZoneComment API operation for Amazon Route 53. -// -// Updates the comment for a specified hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateHostedZoneComment for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneComment -func (c *Route53) UpdateHostedZoneComment(input *UpdateHostedZoneCommentInput) (*UpdateHostedZoneCommentOutput, error) { - req, out := c.UpdateHostedZoneCommentRequest(input) - return out, req.Send() -} - -// UpdateHostedZoneCommentWithContext is the same as UpdateHostedZoneComment with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateHostedZoneComment for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateHostedZoneCommentWithContext(ctx aws.Context, input *UpdateHostedZoneCommentInput, opts ...request.Option) (*UpdateHostedZoneCommentOutput, error) { - req, out := c.UpdateHostedZoneCommentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateTrafficPolicyComment = "UpdateTrafficPolicyComment" - -// UpdateTrafficPolicyCommentRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTrafficPolicyComment operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateTrafficPolicyComment for more information on using the UpdateTrafficPolicyComment -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateTrafficPolicyCommentRequest method. -// req, resp := client.UpdateTrafficPolicyCommentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyComment -func (c *Route53) UpdateTrafficPolicyCommentRequest(input *UpdateTrafficPolicyCommentInput) (req *request.Request, output *UpdateTrafficPolicyCommentOutput) { - op := &request.Operation{ - Name: opUpdateTrafficPolicyComment, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}/{Version}", - } - - if input == nil { - input = &UpdateTrafficPolicyCommentInput{} - } - - output = &UpdateTrafficPolicyCommentOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateTrafficPolicyComment API operation for Amazon Route 53. -// -// Updates the comment for a specified traffic policy version. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateTrafficPolicyComment for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyComment -func (c *Route53) UpdateTrafficPolicyComment(input *UpdateTrafficPolicyCommentInput) (*UpdateTrafficPolicyCommentOutput, error) { - req, out := c.UpdateTrafficPolicyCommentRequest(input) - return out, req.Send() -} - -// UpdateTrafficPolicyCommentWithContext is the same as UpdateTrafficPolicyComment with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateTrafficPolicyComment for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateTrafficPolicyCommentWithContext(ctx aws.Context, input *UpdateTrafficPolicyCommentInput, opts ...request.Option) (*UpdateTrafficPolicyCommentOutput, error) { - req, out := c.UpdateTrafficPolicyCommentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateTrafficPolicyInstance = "UpdateTrafficPolicyInstance" - -// UpdateTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateTrafficPolicyInstance for more information on using the UpdateTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateTrafficPolicyInstanceRequest method. -// req, resp := client.UpdateTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyInstance -func (c *Route53) UpdateTrafficPolicyInstanceRequest(input *UpdateTrafficPolicyInstanceInput) (req *request.Request, output *UpdateTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opUpdateTrafficPolicyInstance, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicyinstance/{Id}", - } - - if input == nil { - input = &UpdateTrafficPolicyInstanceInput{} - } - - output = &UpdateTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateTrafficPolicyInstance API operation for Amazon Route 53. -// -// Updates the resource record sets in a specified hosted zone that were created -// based on the settings in a specified traffic policy version. -// -// When you update a traffic policy instance, Amazon Route 53 continues to respond -// to DNS queries for the root resource record set name (such as example.com) -// while it replaces one group of resource record sets with another. Amazon -// Route 53 performs the following operations: -// -// Amazon Route 53 creates a new group of resource record sets based on the -// specified traffic policy. This is true regardless of how significant the -// differences are between the existing resource record sets and the new resource -// record sets. -// -// When all of the new resource record sets have been created, Amazon Route -// 53 starts to respond to DNS queries for the root resource record set name -// (such as example.com) by using the new resource record sets. -// -// Amazon Route 53 deletes the old group of resource record sets that are associated -// with the root resource record set name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeConflictingTypes "ConflictingTypes" -// You tried to update a traffic policy instance by using a traffic policy version -// that has a different DNS type than the current type for the instance. You -// specified the type in the JSON document in the CreateTrafficPolicy or CreateTrafficPolicyVersionrequest. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyInstance -func (c *Route53) UpdateTrafficPolicyInstance(input *UpdateTrafficPolicyInstanceInput) (*UpdateTrafficPolicyInstanceOutput, error) { - req, out := c.UpdateTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// UpdateTrafficPolicyInstanceWithContext is the same as UpdateTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateTrafficPolicyInstanceWithContext(ctx aws.Context, input *UpdateTrafficPolicyInstanceInput, opts ...request.Option) (*UpdateTrafficPolicyInstanceOutput, error) { - req, out := c.UpdateTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// A complex type that contains the type of limit that you specified in the -// request and the current value for that limit. -type AccountLimit struct { - _ struct{} `type:"structure"` - - // The limit that you requested. Valid values include the following: - // - // * MAX_HEALTH_CHECKS_BY_OWNER: The maximum number of health checks that - // you can create using the current account. - // - // * MAX_HOSTED_ZONES_BY_OWNER: The maximum number of hosted zones that you - // can create using the current account. - // - // * MAX_REUSABLE_DELEGATION_SETS_BY_OWNER: The maximum number of reusable - // delegation sets that you can create using the current account. - // - // * MAX_TRAFFIC_POLICIES_BY_OWNER: The maximum number of traffic policies - // that you can create using the current account. - // - // * MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER: The maximum number of traffic - // policy instances that you can create using the current account. (Traffic - // policy instances are referred to as traffic flow policy records in the - // Amazon Route 53 console.) - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"AccountLimitType"` - - // The current value for the limit that is specified by AccountLimit$Type. - // - // Value is a required field - Value *int64 `min:"1" type:"long" required:"true"` -} - -// String returns the string representation -func (s AccountLimit) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AccountLimit) GoString() string { - return s.String() -} - -// SetType sets the Type field's value. -func (s *AccountLimit) SetType(v string) *AccountLimit { - s.Type = &v - return s -} - -// SetValue sets the Value field's value. -func (s *AccountLimit) SetValue(v int64) *AccountLimit { - s.Value = &v - return s -} - -// A complex type that identifies the CloudWatch alarm that you want Amazon -// Route 53 health checkers to use to determine whether this health check is -// healthy. -type AlarmIdentifier struct { - _ struct{} `type:"structure"` - - // The name of the CloudWatch alarm that you want Amazon Route 53 health checkers - // to use to determine whether this health check is healthy. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // A complex type that identifies the CloudWatch alarm that you want Amazon - // Route 53 health checkers to use to determine whether this health check is - // healthy. - // - // For the current list of CloudWatch regions, see Amazon CloudWatch (http://docs.aws.amazon.com/general/latest/gr/rande.html#cw_region) - // in the AWS Regions and Endpoints chapter of the Amazon Web Services General - // Reference. - // - // Region is a required field - Region *string `min:"1" type:"string" required:"true" enum:"CloudWatchRegion"` -} - -// String returns the string representation -func (s AlarmIdentifier) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AlarmIdentifier) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AlarmIdentifier) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AlarmIdentifier"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Region == nil { - invalidParams.Add(request.NewErrParamRequired("Region")) - } - if s.Region != nil && len(*s.Region) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Region", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *AlarmIdentifier) SetName(v string) *AlarmIdentifier { - s.Name = &v - return s -} - -// SetRegion sets the Region field's value. -func (s *AlarmIdentifier) SetRegion(v string) *AlarmIdentifier { - s.Region = &v - return s -} - -// Alias resource record sets only: Information about the CloudFront distribution, -// Elastic Beanstalk environment, ELB load balancer, Amazon S3 bucket, or Amazon -// Route 53 resource record set that you're redirecting queries to. An Elastic -// Beanstalk environment must have a regionalized subdomain. -// -// When creating resource record sets for a private hosted zone, note the following: -// -// * Resource record sets can't be created for CloudFront distributions in -// a private hosted zone. -// -// * Creating geolocation alias resource record sets or latency alias resource -// record sets in a private hosted zone is unsupported. -// -// * For information about creating failover resource record sets in a private -// hosted zone, see Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html). -type AliasTarget struct { - _ struct{} `type:"structure"` - - // Alias resource record sets only: The value that you specify depends on where - // you want to route queries: - // - // CloudFront distributionSpecify the domain name that CloudFront assigned when - // you created your distribution. - // - // Your CloudFront distribution must include an alternate domain name that matches - // the name of the resource record set. For example, if the name of the resource - // record set is acme.example.com, your CloudFront distribution must include - // acme.example.com as one of the alternate domain names. For more information, - // see Using Alternate Domain Names (CNAMEs) (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html) - // in the Amazon CloudFront Developer Guide. - // - // Elastic Beanstalk environmentSpecify the CNAME attribute for the environment. - // (The environment must have a regionalized domain name.) You can use the following - // methods to get the value of the CNAME attribute: - // - // AWS Management Console: For information about how to get the value by using - // the console, see Using Custom Domains with AWS Elastic Beanstalk (http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html) - // in the AWS Elastic Beanstalk Developer Guide. - // - // Elastic Beanstalk API: Use the DescribeEnvironments action to get the value - // of the CNAME attribute. For more information, see DescribeEnvironments (http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_DescribeEnvironments.html) - // in the AWS Elastic Beanstalk API Reference. - // - // AWS CLI: Use the describe-environments command to get the value of the CNAME - // attribute. For more information, see describe-environments (http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html) - // in the AWS Command Line Interface Reference. - // - // ELB load balancerSpecify the DNS name that is associated with the load balancer. - // Get the DNS name by using the AWS Management Console, the ELB API, or the - // AWS CLI. - // - // AWS Management Console: Go to the EC2 page, choose Load Balancers in the - // navigation pane, choose the load balancer, choose the Description tab, and - // get the value of the DNS name field. (If you're routing traffic to a Classic - // Load Balancer, get the value that begins with dualstack.) - // - // Elastic Load Balancing API: Use DescribeLoadBalancers to get the value of - // DNSName. For more information, see the applicable guide: - // - // Classic Load Balancers: DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancers.html) - // - // Application and Network Load Balancers: DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) - // - // AWS CLI: Use describe-load-balancers to get the value of DNSName. For more - // information, see the applicable guide: - // - // Classic Load Balancers: describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html) - // - // Application and Network Load Balancers: describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-load-balancers.html) - // - // Amazon S3 bucket that is configured as a static websiteSpecify the domain - // name of the Amazon S3 website endpoint in which you created the bucket, for - // example, s3-website-us-east-2.amazonaws.com. For more information about valid - // values, see the table Amazon Simple Storage Service (S3) Website Endpoints - // (http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in the - // Amazon Web Services General Reference. For more information about using S3 - // buckets for websites, see Getting Started with Amazon Route 53 (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/getting-started.html) - // in the Amazon Route 53 Developer Guide. - // - // Another Amazon Route 53 resource record setSpecify the value of the Name - // element for a resource record set in the current hosted zone. - // - // DNSName is a required field - DNSName *string `type:"string" required:"true"` - - // Applies only to alias, failover alias, geolocation alias, latency alias, - // and weighted alias resource record sets: When EvaluateTargetHealth is true, - // an alias resource record set inherits the health of the referenced AWS resource, - // such as an ELB load balancer, or the referenced resource record set. - // - // Note the following: - // - // * You can't set EvaluateTargetHealth to true when the alias target is - // a CloudFront distribution. - // - // * If the AWS resource that you specify in AliasTarget is a resource record - // set or a group of resource record sets (for example, a group of weighted - // resource record sets), but it is not another alias resource record set, - // we recommend that you associate a health check with all of the resource - // record sets in the alias target. For more information, see What Happens - // When You Omit Health Checks? (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html#dns-failover-complex-configs-hc-omitting) - // in the Amazon Route 53 Developer Guide. - // - // * If you specify an Elastic Beanstalk environment in HostedZoneId and - // DNSName, and if the environment contains an ELB load balancer, Elastic - // Load Balancing routes queries only to the healthy Amazon EC2 instances - // that are registered with the load balancer. (An environment automatically - // contains an ELB load balancer if it includes more than one EC2 instance.) - // If you set EvaluateTargetHealth to true and either no EC2 instances are - // healthy or the load balancer itself is unhealthy, Amazon Route 53 routes - // queries to other available resources that are healthy, if any. - // - // If the environment contains a single EC2 instance, there are no special requirements. - // - // * If you specify an ELB load balancer in AliasTarget, ELB routes queries - // only to the healthy EC2 instances that are registered with the load balancer. - // If no EC2 instances are healthy or if the load balancer itself is unhealthy, - // and if EvaluateTargetHealth is true for the corresponding alias resource - // record set, Amazon Route 53 routes queries to other resources. When you - // create a load balancer, you configure settings for ELB health checks; - // they're not Amazon Route 53 health checks, but they perform a similar - // function. Do not create Amazon Route 53 health checks for the EC2 instances - // that you register with an ELB load balancer. - // - // For more information, see How Health Checks Work in More Complex Amazon Route - // 53 Configurations (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html) - // in the Amazon Route 53 Developer Guide. - // - // * We recommend that you set EvaluateTargetHealth to true only when you - // have enough idle capacity to handle the failure of one or more endpoints. - // - // For more information and examples, see Amazon Route 53 Health Checks and - // DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) - // in the Amazon Route 53 Developer Guide. - // - // EvaluateTargetHealth is a required field - EvaluateTargetHealth *bool `type:"boolean" required:"true"` - - // Alias resource records sets only: The value used depends on where you want - // to route traffic: - // - // CloudFront distributionSpecify Z2FDTNDATAQYW2. - // - // Alias resource record sets for CloudFront can't be created in a private zone. - // - // Elastic Beanstalk environmentSpecify the hosted zone ID for the region in - // which you created the environment. The environment must have a regionalized - // subdomain. For a list of regions and the corresponding hosted zone IDs, see - // AWS Elastic Beanstalk (http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region) - // in the "AWS Regions and Endpoints" chapter of the Amazon Web Services General - // Reference. - // - // ELB load balancerSpecify the value of the hosted zone ID for the load balancer. - // Use the following methods to get the hosted zone ID: - // - // Elastic Load Balancing (http://docs.aws.amazon.com/general/latest/gr/rande.html#elb_region) - // table in the "AWS Regions and Endpoints" chapter of the Amazon Web Services - // General Reference: Use the value that corresponds with the region that you - // created your load balancer in. Note that there are separate columns for Application - // and Classic Load Balancers and for Network Load Balancers. - // - // AWS Management Console: Go to the Amazon EC2 page, choose Load Balancers - // in the navigation pane, select the load balancer, and get the value of the - // Hosted zone field on the Description tab. - // - // Elastic Load Balancing API: Use DescribeLoadBalancers to get the applicable - // value. For more information, see the applicable guide: - // - // Classic Load Balancers: Use DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancers.html) - // to get the value of CanonicalHostedZoneNameId. - // - // Application and Network Load Balancers: Use DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) - // to get the value of CanonicalHostedZoneId. - // - // AWS CLI: Use describe-load-balancers to get the applicable value. For more - // information, see the applicable guide: - // - // Classic Load Balancers: Use describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html) - // to get the value of CanonicalHostedZoneNameId. - // - // Application and Network Load Balancers: Use describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-load-balancers.html) - // to get the value of CanonicalHostedZoneId. - // - // An Amazon S3 bucket configured as a static websiteSpecify the hosted zone - // ID for the region that you created the bucket in. For more information about - // valid values, see the Amazon Simple Storage Service Website Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) - // table in the "AWS Regions and Endpoints" chapter of the Amazon Web Services - // General Reference. - // - // Another Amazon Route 53 resource record set in your hosted zoneSpecify the - // hosted zone ID of your hosted zone. (An alias resource record set can't reference - // a resource record set in a different hosted zone.) - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s AliasTarget) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AliasTarget) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AliasTarget) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AliasTarget"} - if s.DNSName == nil { - invalidParams.Add(request.NewErrParamRequired("DNSName")) - } - if s.EvaluateTargetHealth == nil { - invalidParams.Add(request.NewErrParamRequired("EvaluateTargetHealth")) - } - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDNSName sets the DNSName field's value. -func (s *AliasTarget) SetDNSName(v string) *AliasTarget { - s.DNSName = &v - return s -} - -// SetEvaluateTargetHealth sets the EvaluateTargetHealth field's value. -func (s *AliasTarget) SetEvaluateTargetHealth(v bool) *AliasTarget { - s.EvaluateTargetHealth = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *AliasTarget) SetHostedZoneId(v string) *AliasTarget { - s.HostedZoneId = &v - return s -} - -// A complex type that contains information about the request to associate a -// VPC with a private hosted zone. -type AssociateVPCWithHostedZoneInput struct { - _ struct{} `locationName:"AssociateVPCWithHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // Optional: A comment about the association request. - Comment *string `type:"string"` - - // The ID of the private hosted zone that you want to associate an Amazon VPC - // with. - // - // Note that you can't associate a VPC with a hosted zone that doesn't have - // an existing VPC association. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // A complex type that contains information about the VPC that you want to associate - // with a private hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s AssociateVPCWithHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssociateVPCWithHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssociateVPCWithHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssociateVPCWithHostedZoneInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *AssociateVPCWithHostedZoneInput) SetComment(v string) *AssociateVPCWithHostedZoneInput { - s.Comment = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *AssociateVPCWithHostedZoneInput) SetHostedZoneId(v string) *AssociateVPCWithHostedZoneInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *AssociateVPCWithHostedZoneInput) SetVPC(v *VPC) *AssociateVPCWithHostedZoneInput { - s.VPC = v - return s -} - -// A complex type that contains the response information for the AssociateVPCWithHostedZone -// request. -type AssociateVPCWithHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that describes the changes made to your hosted zone. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s AssociateVPCWithHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssociateVPCWithHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *AssociateVPCWithHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *AssociateVPCWithHostedZoneOutput { - s.ChangeInfo = v - return s -} - -// The information for each resource record set that you want to change. -type Change struct { - _ struct{} `type:"structure"` - - // The action to perform: - // - // * CREATE: Creates a resource record set that has the specified values. - // - // * DELETE: Deletes a existing resource record set. - // - // To delete the resource record set that is associated with a traffic policy - // instance, use DeleteTrafficPolicyInstance. Amazon Route 53 will delete - // the resource record set automatically. If you delete the resource record - // set by using ChangeResourceRecordSets, Amazon Route 53 doesn't automatically - // delete the traffic policy instance, and you'll continue to be charged - // for it even though it's no longer in use. - // - // * UPSERT: If a resource record set doesn't already exist, Amazon Route - // 53 creates it. If a resource record set does exist, Amazon Route 53 updates - // it with the values in the request. - // - // Action is a required field - Action *string `type:"string" required:"true" enum:"ChangeAction"` - - // Information about the resource record set to create, delete, or update. - // - // ResourceRecordSet is a required field - ResourceRecordSet *ResourceRecordSet `type:"structure" required:"true"` -} - -// String returns the string representation -func (s Change) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Change) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Change) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Change"} - if s.Action == nil { - invalidParams.Add(request.NewErrParamRequired("Action")) - } - if s.ResourceRecordSet == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceRecordSet")) - } - if s.ResourceRecordSet != nil { - if err := s.ResourceRecordSet.Validate(); err != nil { - invalidParams.AddNested("ResourceRecordSet", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAction sets the Action field's value. -func (s *Change) SetAction(v string) *Change { - s.Action = &v - return s -} - -// SetResourceRecordSet sets the ResourceRecordSet field's value. -func (s *Change) SetResourceRecordSet(v *ResourceRecordSet) *Change { - s.ResourceRecordSet = v - return s -} - -// The information for a change request. -type ChangeBatch struct { - _ struct{} `type:"structure"` - - // Information about the changes to make to the record sets. - // - // Changes is a required field - Changes []*Change `locationNameList:"Change" min:"1" type:"list" required:"true"` - - // Optional: Any comments you want to include about a change batch request. - Comment *string `type:"string"` -} - -// String returns the string representation -func (s ChangeBatch) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeBatch) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ChangeBatch) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ChangeBatch"} - if s.Changes == nil { - invalidParams.Add(request.NewErrParamRequired("Changes")) - } - if s.Changes != nil && len(s.Changes) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Changes", 1)) - } - if s.Changes != nil { - for i, v := range s.Changes { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Changes", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetChanges sets the Changes field's value. -func (s *ChangeBatch) SetChanges(v []*Change) *ChangeBatch { - s.Changes = v - return s -} - -// SetComment sets the Comment field's value. -func (s *ChangeBatch) SetComment(v string) *ChangeBatch { - s.Comment = &v - return s -} - -// A complex type that describes change information about changes made to your -// hosted zone. -type ChangeInfo struct { - _ struct{} `type:"structure"` - - // A complex type that describes change information about changes made to your - // hosted zone. - // - // This element contains an ID that you use when performing a GetChange action - // to get detailed information about the change. - Comment *string `type:"string"` - - // The ID of the request. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // The current state of the request. PENDING indicates that this request has - // not yet been applied to all Amazon Route 53 DNS servers. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ChangeStatus"` - - // The date and time that the change request was submitted in ISO 8601 format - // (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal Time (UTC). - // For example, the value 2017-03-27T17:48:16.751Z represents March 27, 2017 - // at 17:48:16.751 UTC. - // - // SubmittedAt is a required field - SubmittedAt *time.Time `type:"timestamp" required:"true"` -} - -// String returns the string representation -func (s ChangeInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeInfo) GoString() string { - return s.String() -} - -// SetComment sets the Comment field's value. -func (s *ChangeInfo) SetComment(v string) *ChangeInfo { - s.Comment = &v - return s -} - -// SetId sets the Id field's value. -func (s *ChangeInfo) SetId(v string) *ChangeInfo { - s.Id = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *ChangeInfo) SetStatus(v string) *ChangeInfo { - s.Status = &v - return s -} - -// SetSubmittedAt sets the SubmittedAt field's value. -func (s *ChangeInfo) SetSubmittedAt(v time.Time) *ChangeInfo { - s.SubmittedAt = &v - return s -} - -// A complex type that contains change information for the resource record set. -type ChangeResourceRecordSetsInput struct { - _ struct{} `locationName:"ChangeResourceRecordSetsRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that contains an optional comment and the Changes element. - // - // ChangeBatch is a required field - ChangeBatch *ChangeBatch `type:"structure" required:"true"` - - // The ID of the hosted zone that contains the resource record sets that you - // want to change. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s ChangeResourceRecordSetsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeResourceRecordSetsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ChangeResourceRecordSetsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ChangeResourceRecordSetsInput"} - if s.ChangeBatch == nil { - invalidParams.Add(request.NewErrParamRequired("ChangeBatch")) - } - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.ChangeBatch != nil { - if err := s.ChangeBatch.Validate(); err != nil { - invalidParams.AddNested("ChangeBatch", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetChangeBatch sets the ChangeBatch field's value. -func (s *ChangeResourceRecordSetsInput) SetChangeBatch(v *ChangeBatch) *ChangeResourceRecordSetsInput { - s.ChangeBatch = v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ChangeResourceRecordSetsInput) SetHostedZoneId(v string) *ChangeResourceRecordSetsInput { - s.HostedZoneId = &v - return s -} - -// A complex type containing the response for the request. -type ChangeResourceRecordSetsOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about changes made to your hosted - // zone. - // - // This element contains an ID that you use when performing a GetChange action - // to get detailed information about the change. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s ChangeResourceRecordSetsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeResourceRecordSetsOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *ChangeResourceRecordSetsOutput) SetChangeInfo(v *ChangeInfo) *ChangeResourceRecordSetsOutput { - s.ChangeInfo = v - return s -} - -// A complex type that contains information about the tags that you want to -// add, edit, or delete. -type ChangeTagsForResourceInput struct { - _ struct{} `locationName:"ChangeTagsForResourceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that contains a list of the tags that you want to add to the - // specified health check or hosted zone and/or the tags that you want to edit - // Value for. - // - // You can add a maximum of 10 tags to a health check or a hosted zone. - AddTags []*Tag `locationNameList:"Tag" min:"1" type:"list"` - - // A complex type that contains a list of the tags that you want to delete from - // the specified health check or hosted zone. You can specify up to 10 keys. - RemoveTagKeys []*string `locationNameList:"Key" min:"1" type:"list"` - - // The ID of the resource for which you want to add, change, or delete tags. - // - // ResourceId is a required field - ResourceId *string `location:"uri" locationName:"ResourceId" type:"string" required:"true"` - - // The type of the resource. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - // - // ResourceType is a required field - ResourceType *string `location:"uri" locationName:"ResourceType" type:"string" required:"true" enum:"TagResourceType"` -} - -// String returns the string representation -func (s ChangeTagsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeTagsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ChangeTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ChangeTagsForResourceInput"} - if s.AddTags != nil && len(s.AddTags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AddTags", 1)) - } - if s.RemoveTagKeys != nil && len(s.RemoveTagKeys) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RemoveTagKeys", 1)) - } - if s.ResourceId == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceId")) - } - if s.ResourceType == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAddTags sets the AddTags field's value. -func (s *ChangeTagsForResourceInput) SetAddTags(v []*Tag) *ChangeTagsForResourceInput { - s.AddTags = v - return s -} - -// SetRemoveTagKeys sets the RemoveTagKeys field's value. -func (s *ChangeTagsForResourceInput) SetRemoveTagKeys(v []*string) *ChangeTagsForResourceInput { - s.RemoveTagKeys = v - return s -} - -// SetResourceId sets the ResourceId field's value. -func (s *ChangeTagsForResourceInput) SetResourceId(v string) *ChangeTagsForResourceInput { - s.ResourceId = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ChangeTagsForResourceInput) SetResourceType(v string) *ChangeTagsForResourceInput { - s.ResourceType = &v - return s -} - -// Empty response for the request. -type ChangeTagsForResourceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s ChangeTagsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeTagsForResourceOutput) GoString() string { - return s.String() -} - -// A complex type that contains information about the CloudWatch alarm that -// Amazon Route 53 is monitoring for this health check. -type CloudWatchAlarmConfiguration struct { - _ struct{} `type:"structure"` - - // For the metric that the CloudWatch alarm is associated with, the arithmetic - // operation that is used for the comparison. - // - // ComparisonOperator is a required field - ComparisonOperator *string `type:"string" required:"true" enum:"ComparisonOperator"` - - // For the metric that the CloudWatch alarm is associated with, a complex type - // that contains information about the dimensions for the metric. For information, - // see Amazon CloudWatch Namespaces, Dimensions, and Metrics Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html) - // in the Amazon CloudWatch User Guide. - Dimensions []*Dimension `locationNameList:"Dimension" type:"list"` - - // For the metric that the CloudWatch alarm is associated with, the number of - // periods that the metric is compared to the threshold. - // - // EvaluationPeriods is a required field - EvaluationPeriods *int64 `min:"1" type:"integer" required:"true"` - - // The name of the CloudWatch metric that the alarm is associated with. - // - // MetricName is a required field - MetricName *string `min:"1" type:"string" required:"true"` - - // The namespace of the metric that the alarm is associated with. For more information, - // see Amazon CloudWatch Namespaces, Dimensions, and Metrics Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html) - // in the Amazon CloudWatch User Guide. - // - // Namespace is a required field - Namespace *string `min:"1" type:"string" required:"true"` - - // For the metric that the CloudWatch alarm is associated with, the duration - // of one evaluation period in seconds. - // - // Period is a required field - Period *int64 `min:"60" type:"integer" required:"true"` - - // For the metric that the CloudWatch alarm is associated with, the statistic - // that is applied to the metric. - // - // Statistic is a required field - Statistic *string `type:"string" required:"true" enum:"Statistic"` - - // For the metric that the CloudWatch alarm is associated with, the value the - // metric is compared with. - // - // Threshold is a required field - Threshold *float64 `type:"double" required:"true"` -} - -// String returns the string representation -func (s CloudWatchAlarmConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloudWatchAlarmConfiguration) GoString() string { - return s.String() -} - -// SetComparisonOperator sets the ComparisonOperator field's value. -func (s *CloudWatchAlarmConfiguration) SetComparisonOperator(v string) *CloudWatchAlarmConfiguration { - s.ComparisonOperator = &v - return s -} - -// SetDimensions sets the Dimensions field's value. -func (s *CloudWatchAlarmConfiguration) SetDimensions(v []*Dimension) *CloudWatchAlarmConfiguration { - s.Dimensions = v - return s -} - -// SetEvaluationPeriods sets the EvaluationPeriods field's value. -func (s *CloudWatchAlarmConfiguration) SetEvaluationPeriods(v int64) *CloudWatchAlarmConfiguration { - s.EvaluationPeriods = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *CloudWatchAlarmConfiguration) SetMetricName(v string) *CloudWatchAlarmConfiguration { - s.MetricName = &v - return s -} - -// SetNamespace sets the Namespace field's value. -func (s *CloudWatchAlarmConfiguration) SetNamespace(v string) *CloudWatchAlarmConfiguration { - s.Namespace = &v - return s -} - -// SetPeriod sets the Period field's value. -func (s *CloudWatchAlarmConfiguration) SetPeriod(v int64) *CloudWatchAlarmConfiguration { - s.Period = &v - return s -} - -// SetStatistic sets the Statistic field's value. -func (s *CloudWatchAlarmConfiguration) SetStatistic(v string) *CloudWatchAlarmConfiguration { - s.Statistic = &v - return s -} - -// SetThreshold sets the Threshold field's value. -func (s *CloudWatchAlarmConfiguration) SetThreshold(v float64) *CloudWatchAlarmConfiguration { - s.Threshold = &v - return s -} - -// A complex type that contains the health check request information. -type CreateHealthCheckInput struct { - _ struct{} `locationName:"CreateHealthCheckRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A unique string that identifies the request and that allows you to retry - // a failed CreateHealthCheck request without the risk of creating two identical - // health checks: - // - // * If you send a CreateHealthCheck request with the same CallerReference - // and settings as a previous request, and if the health check doesn't exist, - // Amazon Route 53 creates the health check. If the health check does exist, - // Amazon Route 53 returns the settings for the existing health check. - // - // * If you send a CreateHealthCheck request with the same CallerReference - // as a deleted health check, regardless of the settings, Amazon Route 53 - // returns a HealthCheckAlreadyExists error. - // - // * If you send a CreateHealthCheck request with the same CallerReference - // as an existing health check but with different settings, Amazon Route - // 53 returns a HealthCheckAlreadyExists error. - // - // * If you send a CreateHealthCheck request with a unique CallerReference - // but settings identical to an existing health check, Amazon Route 53 creates - // the health check. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // A complex type that contains the response to a CreateHealthCheck request. - // - // HealthCheckConfig is a required field - HealthCheckConfig *HealthCheckConfig `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateHealthCheckInput"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.CallerReference != nil && len(*s.CallerReference) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerReference", 1)) - } - if s.HealthCheckConfig == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckConfig")) - } - if s.HealthCheckConfig != nil { - if err := s.HealthCheckConfig.Validate(); err != nil { - invalidParams.AddNested("HealthCheckConfig", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCallerReference sets the CallerReference field's value. -func (s *CreateHealthCheckInput) SetCallerReference(v string) *CreateHealthCheckInput { - s.CallerReference = &v - return s -} - -// SetHealthCheckConfig sets the HealthCheckConfig field's value. -func (s *CreateHealthCheckInput) SetHealthCheckConfig(v *HealthCheckConfig) *CreateHealthCheckInput { - s.HealthCheckConfig = v - return s -} - -// A complex type containing the response information for the new health check. -type CreateHealthCheckOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains identifying information about the health check. - // - // HealthCheck is a required field - HealthCheck *HealthCheck `type:"structure" required:"true"` - - // The unique URL representing the new health check. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHealthCheckOutput) GoString() string { - return s.String() -} - -// SetHealthCheck sets the HealthCheck field's value. -func (s *CreateHealthCheckOutput) SetHealthCheck(v *HealthCheck) *CreateHealthCheckOutput { - s.HealthCheck = v - return s -} - -// SetLocation sets the Location field's value. -func (s *CreateHealthCheckOutput) SetLocation(v string) *CreateHealthCheckOutput { - s.Location = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type CreateHostedZoneInput struct { - _ struct{} `locationName:"CreateHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A unique string that identifies the request and that allows failed CreateHostedZone - // requests to be retried without the risk of executing the operation twice. - // You must use a unique CallerReference string every time you submit a CreateHostedZone - // request. CallerReference can be any unique string, for example, a date/time - // stamp. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // If you want to associate a reusable delegation set with this hosted zone, - // the ID that Amazon Route 53 assigned to the reusable delegation set when - // you created it. For more information about reusable delegation sets, see - // CreateReusableDelegationSet. - DelegationSetId *string `type:"string"` - - // (Optional) A complex type that contains the following optional values: - // - // * For public and private hosted zones, an optional comment - // - // * For private hosted zones, an optional PrivateZone element - // - // If you don't specify a comment or the PrivateZone element, omit HostedZoneConfig - // and the other elements. - HostedZoneConfig *HostedZoneConfig `type:"structure"` - - // The name of the domain. For resource record types that include a domain name, - // specify a fully qualified domain name, for example, www.example.com. The - // trailing dot is optional; Amazon Route 53 assumes that the domain name is - // fully qualified. This means that Amazon Route 53 treats www.example.com (without - // a trailing dot) and www.example.com. (with a trailing dot) as identical. - // - // If you're creating a public hosted zone, this is the name you have registered - // with your DNS registrar. If your domain name is registered with a registrar - // other than Amazon Route 53, change the name servers for your domain to the - // set of NameServers that CreateHostedZone returns in DelegationSet. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // (Private hosted zones only) A complex type that contains information about - // the Amazon VPC that you're associating with this hosted zone. - // - // You can specify only one Amazon VPC when you create a private hosted zone. - // To associate additional Amazon VPCs with the hosted zone, use AssociateVPCWithHostedZone - // after you create a hosted zone. - VPC *VPC `type:"structure"` -} - -// String returns the string representation -func (s CreateHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateHostedZoneInput"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.CallerReference != nil && len(*s.CallerReference) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerReference", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCallerReference sets the CallerReference field's value. -func (s *CreateHostedZoneInput) SetCallerReference(v string) *CreateHostedZoneInput { - s.CallerReference = &v - return s -} - -// SetDelegationSetId sets the DelegationSetId field's value. -func (s *CreateHostedZoneInput) SetDelegationSetId(v string) *CreateHostedZoneInput { - s.DelegationSetId = &v - return s -} - -// SetHostedZoneConfig sets the HostedZoneConfig field's value. -func (s *CreateHostedZoneInput) SetHostedZoneConfig(v *HostedZoneConfig) *CreateHostedZoneInput { - s.HostedZoneConfig = v - return s -} - -// SetName sets the Name field's value. -func (s *CreateHostedZoneInput) SetName(v string) *CreateHostedZoneInput { - s.Name = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateHostedZoneInput) SetVPC(v *VPC) *CreateHostedZoneInput { - s.VPC = v - return s -} - -// A complex type containing the response information for the hosted zone. -type CreateHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the CreateHostedZone request. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` - - // A complex type that describes the name servers for this hosted zone. - // - // DelegationSet is a required field - DelegationSet *DelegationSet `type:"structure" required:"true"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZone is a required field - HostedZone *HostedZone `type:"structure" required:"true"` - - // The unique URL representing the new hosted zone. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains information about an Amazon VPC that you associated - // with this hosted zone. - VPC *VPC `type:"structure"` -} - -// String returns the string representation -func (s CreateHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *CreateHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *CreateHostedZoneOutput { - s.ChangeInfo = v - return s -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *CreateHostedZoneOutput) SetDelegationSet(v *DelegationSet) *CreateHostedZoneOutput { - s.DelegationSet = v - return s -} - -// SetHostedZone sets the HostedZone field's value. -func (s *CreateHostedZoneOutput) SetHostedZone(v *HostedZone) *CreateHostedZoneOutput { - s.HostedZone = v - return s -} - -// SetLocation sets the Location field's value. -func (s *CreateHostedZoneOutput) SetLocation(v string) *CreateHostedZoneOutput { - s.Location = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateHostedZoneOutput) SetVPC(v *VPC) *CreateHostedZoneOutput { - s.VPC = v - return s -} - -type CreateQueryLoggingConfigInput struct { - _ struct{} `locationName:"CreateQueryLoggingConfigRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The Amazon Resource Name (ARN) for the log group that you want to Amazon - // Route 53 to send query logs to. This is the format of the ARN: - // - // arn:aws:logs:region:account-id:log-group:log_group_name - // - // To get the ARN for a log group, you can use the CloudWatch console, the DescribeLogGroups - // (http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogGroups.html) - // API action, the describe-log-groups (http://docs.aws.amazon.com/cli/latest/reference/logs/describe-log-groups.html) - // command, or the applicable command in one of the AWS SDKs. - // - // CloudWatchLogsLogGroupArn is a required field - CloudWatchLogsLogGroupArn *string `type:"string" required:"true"` - - // The ID of the hosted zone that you want to log queries for. You can log queries - // only for public hosted zones. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateQueryLoggingConfigInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateQueryLoggingConfigInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateQueryLoggingConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateQueryLoggingConfigInput"} - if s.CloudWatchLogsLogGroupArn == nil { - invalidParams.Add(request.NewErrParamRequired("CloudWatchLogsLogGroupArn")) - } - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCloudWatchLogsLogGroupArn sets the CloudWatchLogsLogGroupArn field's value. -func (s *CreateQueryLoggingConfigInput) SetCloudWatchLogsLogGroupArn(v string) *CreateQueryLoggingConfigInput { - s.CloudWatchLogsLogGroupArn = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateQueryLoggingConfigInput) SetHostedZoneId(v string) *CreateQueryLoggingConfigInput { - s.HostedZoneId = &v - return s -} - -type CreateQueryLoggingConfigOutput struct { - _ struct{} `type:"structure"` - - // The unique URL representing the new query logging configuration. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains the ID for a query logging configuration, the - // ID of the hosted zone that you want to log queries for, and the ARN for the - // log group that you want Amazon Route 53 to send query logs to. - // - // QueryLoggingConfig is a required field - QueryLoggingConfig *QueryLoggingConfig `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateQueryLoggingConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateQueryLoggingConfigOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateQueryLoggingConfigOutput) SetLocation(v string) *CreateQueryLoggingConfigOutput { - s.Location = &v - return s -} - -// SetQueryLoggingConfig sets the QueryLoggingConfig field's value. -func (s *CreateQueryLoggingConfigOutput) SetQueryLoggingConfig(v *QueryLoggingConfig) *CreateQueryLoggingConfigOutput { - s.QueryLoggingConfig = v - return s -} - -type CreateReusableDelegationSetInput struct { - _ struct{} `locationName:"CreateReusableDelegationSetRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A unique string that identifies the request, and that allows you to retry - // failed CreateReusableDelegationSet requests without the risk of executing - // the operation twice. You must use a unique CallerReference string every time - // you submit a CreateReusableDelegationSet request. CallerReference can be - // any unique string, for example a date/time stamp. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // If you want to mark the delegation set for an existing hosted zone as reusable, - // the ID for that hosted zone. - HostedZoneId *string `type:"string"` -} - -// String returns the string representation -func (s CreateReusableDelegationSetInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateReusableDelegationSetInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateReusableDelegationSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateReusableDelegationSetInput"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.CallerReference != nil && len(*s.CallerReference) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerReference", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCallerReference sets the CallerReference field's value. -func (s *CreateReusableDelegationSetInput) SetCallerReference(v string) *CreateReusableDelegationSetInput { - s.CallerReference = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateReusableDelegationSetInput) SetHostedZoneId(v string) *CreateReusableDelegationSetInput { - s.HostedZoneId = &v - return s -} - -type CreateReusableDelegationSetOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains name server information. - // - // DelegationSet is a required field - DelegationSet *DelegationSet `type:"structure" required:"true"` - - // The unique URL representing the new reusable delegation set. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateReusableDelegationSetOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateReusableDelegationSetOutput) GoString() string { - return s.String() -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *CreateReusableDelegationSetOutput) SetDelegationSet(v *DelegationSet) *CreateReusableDelegationSetOutput { - s.DelegationSet = v - return s -} - -// SetLocation sets the Location field's value. -func (s *CreateReusableDelegationSetOutput) SetLocation(v string) *CreateReusableDelegationSetOutput { - s.Location = &v - return s -} - -// A complex type that contains information about the traffic policy that you -// want to create. -type CreateTrafficPolicyInput struct { - _ struct{} `locationName:"CreateTrafficPolicyRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // (Optional) Any comments that you want to include about the traffic policy. - Comment *string `type:"string"` - - // The definition of this traffic policy in JSON format. For more information, - // see Traffic Policy Document Format (http://docs.aws.amazon.com/Route53/latest/APIReference/api-policies-traffic-policy-document-format.html). - // - // Document is a required field - Document *string `type:"string" required:"true"` - - // The name of the traffic policy. - // - // Name is a required field - Name *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTrafficPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTrafficPolicyInput"} - if s.Document == nil { - invalidParams.Add(request.NewErrParamRequired("Document")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *CreateTrafficPolicyInput) SetComment(v string) *CreateTrafficPolicyInput { - s.Comment = &v - return s -} - -// SetDocument sets the Document field's value. -func (s *CreateTrafficPolicyInput) SetDocument(v string) *CreateTrafficPolicyInput { - s.Document = &v - return s -} - -// SetName sets the Name field's value. -func (s *CreateTrafficPolicyInput) SetName(v string) *CreateTrafficPolicyInput { - s.Name = &v - return s -} - -// A complex type that contains information about the resource record sets that -// you want to create based on a specified traffic policy. -type CreateTrafficPolicyInstanceInput struct { - _ struct{} `locationName:"CreateTrafficPolicyInstanceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The ID of the hosted zone in which you want Amazon Route 53 to create resource - // record sets by using the configuration in a traffic policy. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The domain name (such as example.com) or subdomain name (such as www.example.com) - // for which Amazon Route 53 responds to DNS queries by using the resource record - // sets that Amazon Route 53 creates for this traffic policy instance. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // (Optional) The TTL that you want Amazon Route 53 to assign to all of the - // resource record sets that it creates in the specified hosted zone. - // - // TTL is a required field - TTL *int64 `type:"long" required:"true"` - - // The ID of the traffic policy that you want to use to create resource record - // sets in the specified hosted zone. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `min:"1" type:"string" required:"true"` - - // The version of the traffic policy that you want to use to create resource - // record sets in the specified hosted zone. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTrafficPolicyInstanceInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.TTL == nil { - invalidParams.Add(request.NewErrParamRequired("TTL")) - } - if s.TrafficPolicyId == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyId")) - } - if s.TrafficPolicyId != nil && len(*s.TrafficPolicyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyId", 1)) - } - if s.TrafficPolicyVersion == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyVersion")) - } - if s.TrafficPolicyVersion != nil && *s.TrafficPolicyVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("TrafficPolicyVersion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateTrafficPolicyInstanceInput) SetHostedZoneId(v string) *CreateTrafficPolicyInstanceInput { - s.HostedZoneId = &v - return s -} - -// SetName sets the Name field's value. -func (s *CreateTrafficPolicyInstanceInput) SetName(v string) *CreateTrafficPolicyInstanceInput { - s.Name = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *CreateTrafficPolicyInstanceInput) SetTTL(v int64) *CreateTrafficPolicyInstanceInput { - s.TTL = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *CreateTrafficPolicyInstanceInput) SetTrafficPolicyId(v string) *CreateTrafficPolicyInstanceInput { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *CreateTrafficPolicyInstanceInput) SetTrafficPolicyVersion(v int64) *CreateTrafficPolicyInstanceInput { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains the response information for the CreateTrafficPolicyInstance -// request. -type CreateTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` - - // A unique URL that represents a new traffic policy instance. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains settings for the new traffic policy instance. - // - // TrafficPolicyInstance is a required field - TrafficPolicyInstance *TrafficPolicyInstance `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateTrafficPolicyInstanceOutput) SetLocation(v string) *CreateTrafficPolicyInstanceOutput { - s.Location = &v - return s -} - -// SetTrafficPolicyInstance sets the TrafficPolicyInstance field's value. -func (s *CreateTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficPolicyInstance) *CreateTrafficPolicyInstanceOutput { - s.TrafficPolicyInstance = v - return s -} - -// A complex type that contains the response information for the CreateTrafficPolicy -// request. -type CreateTrafficPolicyOutput struct { - _ struct{} `type:"structure"` - - // A unique URL that represents a new traffic policy. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains settings for the new traffic policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateTrafficPolicyOutput) SetLocation(v string) *CreateTrafficPolicyOutput { - s.Location = &v - return s -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *CreateTrafficPolicyOutput) SetTrafficPolicy(v *TrafficPolicy) *CreateTrafficPolicyOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about the traffic policy that you -// want to create a new version for. -type CreateTrafficPolicyVersionInput struct { - _ struct{} `locationName:"CreateTrafficPolicyVersionRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The comment that you specified in the CreateTrafficPolicyVersion request, - // if any. - Comment *string `type:"string"` - - // The definition of this version of the traffic policy, in JSON format. You - // specified the JSON in the CreateTrafficPolicyVersion request. For more information - // about the JSON format, see CreateTrafficPolicy. - // - // Document is a required field - Document *string `type:"string" required:"true"` - - // The ID of the traffic policy for which you want to create a new version. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyVersionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyVersionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTrafficPolicyVersionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTrafficPolicyVersionInput"} - if s.Document == nil { - invalidParams.Add(request.NewErrParamRequired("Document")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *CreateTrafficPolicyVersionInput) SetComment(v string) *CreateTrafficPolicyVersionInput { - s.Comment = &v - return s -} - -// SetDocument sets the Document field's value. -func (s *CreateTrafficPolicyVersionInput) SetDocument(v string) *CreateTrafficPolicyVersionInput { - s.Document = &v - return s -} - -// SetId sets the Id field's value. -func (s *CreateTrafficPolicyVersionInput) SetId(v string) *CreateTrafficPolicyVersionInput { - s.Id = &v - return s -} - -// A complex type that contains the response information for the CreateTrafficPolicyVersion -// request. -type CreateTrafficPolicyVersionOutput struct { - _ struct{} `type:"structure"` - - // A unique URL that represents a new traffic policy version. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains settings for the new version of the traffic - // policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyVersionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyVersionOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateTrafficPolicyVersionOutput) SetLocation(v string) *CreateTrafficPolicyVersionOutput { - s.Location = &v - return s -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *CreateTrafficPolicyVersionOutput) SetTrafficPolicy(v *TrafficPolicy) *CreateTrafficPolicyVersionOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about the request to authorize associating -// a VPC with your private hosted zone. Authorization is only required when -// a private hosted zone and a VPC were created by using different accounts. -type CreateVPCAssociationAuthorizationInput struct { - _ struct{} `locationName:"CreateVPCAssociationAuthorizationRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The ID of the private hosted zone that you want to authorize associating - // a VPC with. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // A complex type that contains the VPC ID and region for the VPC that you want - // to authorize associating with your hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateVPCAssociationAuthorizationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateVPCAssociationAuthorizationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateVPCAssociationAuthorizationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateVPCAssociationAuthorizationInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateVPCAssociationAuthorizationInput) SetHostedZoneId(v string) *CreateVPCAssociationAuthorizationInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateVPCAssociationAuthorizationInput) SetVPC(v *VPC) *CreateVPCAssociationAuthorizationInput { - s.VPC = v - return s -} - -// A complex type that contains the response information from a CreateVPCAssociationAuthorization -// request. -type CreateVPCAssociationAuthorizationOutput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you authorized associating a VPC with. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The VPC that you authorized associating with a hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateVPCAssociationAuthorizationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateVPCAssociationAuthorizationOutput) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateVPCAssociationAuthorizationOutput) SetHostedZoneId(v string) *CreateVPCAssociationAuthorizationOutput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateVPCAssociationAuthorizationOutput) SetVPC(v *VPC) *CreateVPCAssociationAuthorizationOutput { - s.VPC = v - return s -} - -// A complex type that lists the name servers in a delegation set, as well as -// the CallerReference and the ID for the delegation set. -type DelegationSet struct { - _ struct{} `type:"structure"` - - // The value that you specified for CallerReference when you created the reusable - // delegation set. - CallerReference *string `min:"1" type:"string"` - - // The ID that Amazon Route 53 assigns to a reusable delegation set. - Id *string `type:"string"` - - // A complex type that contains a list of the authoritative name servers for - // a hosted zone or for a reusable delegation set. - // - // NameServers is a required field - NameServers []*string `locationNameList:"NameServer" min:"1" type:"list" required:"true"` -} - -// String returns the string representation -func (s DelegationSet) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DelegationSet) GoString() string { - return s.String() -} - -// SetCallerReference sets the CallerReference field's value. -func (s *DelegationSet) SetCallerReference(v string) *DelegationSet { - s.CallerReference = &v - return s -} - -// SetId sets the Id field's value. -func (s *DelegationSet) SetId(v string) *DelegationSet { - s.Id = &v - return s -} - -// SetNameServers sets the NameServers field's value. -func (s *DelegationSet) SetNameServers(v []*string) *DelegationSet { - s.NameServers = v - return s -} - -// This action deletes a health check. -type DeleteHealthCheckInput struct { - _ struct{} `type:"structure"` - - // The ID of the health check that you want to delete. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteHealthCheckInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *DeleteHealthCheckInput) SetHealthCheckId(v string) *DeleteHealthCheckInput { - s.HealthCheckId = &v - return s -} - -// An empty element. -type DeleteHealthCheckOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHealthCheckOutput) GoString() string { - return s.String() -} - -// A request to delete a hosted zone. -type DeleteHostedZoneInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteHostedZoneInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteHostedZoneInput) SetId(v string) *DeleteHostedZoneInput { - s.Id = &v - return s -} - -// A complex type that contains the response to a DeleteHostedZone request. -type DeleteHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains the ID, the status, and the date and time of - // a request to delete a hosted zone. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DeleteHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *DeleteHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *DeleteHostedZoneOutput { - s.ChangeInfo = v - return s -} - -type DeleteQueryLoggingConfigInput struct { - _ struct{} `type:"structure"` - - // The ID of the configuration that you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteQueryLoggingConfigInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteQueryLoggingConfigInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteQueryLoggingConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteQueryLoggingConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteQueryLoggingConfigInput) SetId(v string) *DeleteQueryLoggingConfigInput { - s.Id = &v - return s -} - -type DeleteQueryLoggingConfigOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteQueryLoggingConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteQueryLoggingConfigOutput) GoString() string { - return s.String() -} - -// A request to delete a reusable delegation set. -type DeleteReusableDelegationSetInput struct { - _ struct{} `type:"structure"` - - // The ID of the reusable delegation set that you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteReusableDelegationSetInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteReusableDelegationSetInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteReusableDelegationSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteReusableDelegationSetInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteReusableDelegationSetInput) SetId(v string) *DeleteReusableDelegationSetInput { - s.Id = &v - return s -} - -// An empty element. -type DeleteReusableDelegationSetOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteReusableDelegationSetOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteReusableDelegationSetOutput) GoString() string { - return s.String() -} - -// A request to delete a specified traffic policy version. -type DeleteTrafficPolicyInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy that you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The version number of the traffic policy that you want to delete. - // - // Version is a required field - Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteTrafficPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteTrafficPolicyInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.Version == nil { - invalidParams.Add(request.NewErrParamRequired("Version")) - } - if s.Version != nil && *s.Version < 1 { - invalidParams.Add(request.NewErrParamMinValue("Version", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteTrafficPolicyInput) SetId(v string) *DeleteTrafficPolicyInput { - s.Id = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *DeleteTrafficPolicyInput) SetVersion(v int64) *DeleteTrafficPolicyInput { - s.Version = &v - return s -} - -// A request to delete a specified traffic policy instance. -type DeleteTrafficPolicyInstanceInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy instance that you want to delete. - // - // When you delete a traffic policy instance, Amazon Route 53 also deletes all - // of the resource record sets that were created when you created the traffic - // policy instance. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteTrafficPolicyInstanceInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteTrafficPolicyInstanceInput) SetId(v string) *DeleteTrafficPolicyInstanceInput { - s.Id = &v - return s -} - -// An empty element. -type DeleteTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// An empty element. -type DeleteTrafficPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyOutput) GoString() string { - return s.String() -} - -// A complex type that contains information about the request to remove authorization -// to associate a VPC that was created by one AWS account with a hosted zone -// that was created with a different AWS account. -type DeleteVPCAssociationAuthorizationInput struct { - _ struct{} `locationName:"DeleteVPCAssociationAuthorizationRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // When removing authorization to associate a VPC that was created by one AWS - // account with a hosted zone that was created with a different AWS account, - // the ID of the hosted zone. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // When removing authorization to associate a VPC that was created by one AWS - // account with a hosted zone that was created with a different AWS account, - // a complex type that includes the ID and region of the VPC. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DeleteVPCAssociationAuthorizationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteVPCAssociationAuthorizationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteVPCAssociationAuthorizationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteVPCAssociationAuthorizationInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *DeleteVPCAssociationAuthorizationInput) SetHostedZoneId(v string) *DeleteVPCAssociationAuthorizationInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *DeleteVPCAssociationAuthorizationInput) SetVPC(v *VPC) *DeleteVPCAssociationAuthorizationInput { - s.VPC = v - return s -} - -// Empty response for the request. -type DeleteVPCAssociationAuthorizationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteVPCAssociationAuthorizationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteVPCAssociationAuthorizationOutput) GoString() string { - return s.String() -} - -// For the metric that the CloudWatch alarm is associated with, a complex type -// that contains information about one dimension. -type Dimension struct { - _ struct{} `type:"structure"` - - // For the metric that the CloudWatch alarm is associated with, the name of - // one dimension. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // For the metric that the CloudWatch alarm is associated with, the value of - // one dimension. - // - // Value is a required field - Value *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s Dimension) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Dimension) GoString() string { - return s.String() -} - -// SetName sets the Name field's value. -func (s *Dimension) SetName(v string) *Dimension { - s.Name = &v - return s -} - -// SetValue sets the Value field's value. -func (s *Dimension) SetValue(v string) *Dimension { - s.Value = &v - return s -} - -// A complex type that contains information about the VPC that you want to disassociate -// from a specified private hosted zone. -type DisassociateVPCFromHostedZoneInput struct { - _ struct{} `locationName:"DisassociateVPCFromHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // Optional: A comment about the disassociation request. - Comment *string `type:"string"` - - // The ID of the private hosted zone that you want to disassociate a VPC from. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // A complex type that contains information about the VPC that you're disassociating - // from the specified hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DisassociateVPCFromHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DisassociateVPCFromHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DisassociateVPCFromHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DisassociateVPCFromHostedZoneInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *DisassociateVPCFromHostedZoneInput) SetComment(v string) *DisassociateVPCFromHostedZoneInput { - s.Comment = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *DisassociateVPCFromHostedZoneInput) SetHostedZoneId(v string) *DisassociateVPCFromHostedZoneInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *DisassociateVPCFromHostedZoneInput) SetVPC(v *VPC) *DisassociateVPCFromHostedZoneInput { - s.VPC = v - return s -} - -// A complex type that contains the response information for the disassociate -// request. -type DisassociateVPCFromHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that describes the changes made to the specified private hosted - // zone. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DisassociateVPCFromHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DisassociateVPCFromHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *DisassociateVPCFromHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *DisassociateVPCFromHostedZoneOutput { - s.ChangeInfo = v - return s -} - -// A complex type that contains information about a geo location. -type GeoLocation struct { - _ struct{} `type:"structure"` - - // The two-letter code for the continent. - // - // Valid values: AF | AN | AS | EU | OC | NA | SA - // - // Constraint: Specifying ContinentCode with either CountryCode or SubdivisionCode - // returns an InvalidInput error. - ContinentCode *string `min:"2" type:"string"` - - // The two-letter code for the country. - CountryCode *string `min:"1" type:"string"` - - // The code for the subdivision, for example, a state in the United States or - // a province in Canada. - SubdivisionCode *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GeoLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GeoLocation) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GeoLocation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GeoLocation"} - if s.ContinentCode != nil && len(*s.ContinentCode) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ContinentCode", 2)) - } - if s.CountryCode != nil && len(*s.CountryCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CountryCode", 1)) - } - if s.SubdivisionCode != nil && len(*s.SubdivisionCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SubdivisionCode", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *GeoLocation) SetContinentCode(v string) *GeoLocation { - s.ContinentCode = &v - return s -} - -// SetCountryCode sets the CountryCode field's value. -func (s *GeoLocation) SetCountryCode(v string) *GeoLocation { - s.CountryCode = &v - return s -} - -// SetSubdivisionCode sets the SubdivisionCode field's value. -func (s *GeoLocation) SetSubdivisionCode(v string) *GeoLocation { - s.SubdivisionCode = &v - return s -} - -// A complex type that contains the codes and full continent, country, and subdivision -// names for the specified geolocation code. -type GeoLocationDetails struct { - _ struct{} `type:"structure"` - - // The two-letter code for the continent. - ContinentCode *string `min:"2" type:"string"` - - // The full name of the continent. - ContinentName *string `min:"1" type:"string"` - - // The two-letter code for the country. - CountryCode *string `min:"1" type:"string"` - - // The name of the country. - CountryName *string `min:"1" type:"string"` - - // The code for the subdivision, for example, a state in the United States or - // a province in Canada. - SubdivisionCode *string `min:"1" type:"string"` - - // The full name of the subdivision, for example, a state in the United States - // or a province in Canada. - SubdivisionName *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GeoLocationDetails) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GeoLocationDetails) GoString() string { - return s.String() -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *GeoLocationDetails) SetContinentCode(v string) *GeoLocationDetails { - s.ContinentCode = &v - return s -} - -// SetContinentName sets the ContinentName field's value. -func (s *GeoLocationDetails) SetContinentName(v string) *GeoLocationDetails { - s.ContinentName = &v - return s -} - -// SetCountryCode sets the CountryCode field's value. -func (s *GeoLocationDetails) SetCountryCode(v string) *GeoLocationDetails { - s.CountryCode = &v - return s -} - -// SetCountryName sets the CountryName field's value. -func (s *GeoLocationDetails) SetCountryName(v string) *GeoLocationDetails { - s.CountryName = &v - return s -} - -// SetSubdivisionCode sets the SubdivisionCode field's value. -func (s *GeoLocationDetails) SetSubdivisionCode(v string) *GeoLocationDetails { - s.SubdivisionCode = &v - return s -} - -// SetSubdivisionName sets the SubdivisionName field's value. -func (s *GeoLocationDetails) SetSubdivisionName(v string) *GeoLocationDetails { - s.SubdivisionName = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type GetAccountLimitInput struct { - _ struct{} `type:"structure"` - - // The limit that you want to get. Valid values include the following: - // - // * MAX_HEALTH_CHECKS_BY_OWNER: The maximum number of health checks that - // you can create using the current account. - // - // * MAX_HOSTED_ZONES_BY_OWNER: The maximum number of hosted zones that you - // can create using the current account. - // - // * MAX_REUSABLE_DELEGATION_SETS_BY_OWNER: The maximum number of reusable - // delegation sets that you can create using the current account. - // - // * MAX_TRAFFIC_POLICIES_BY_OWNER: The maximum number of traffic policies - // that you can create using the current account. - // - // * MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER: The maximum number of traffic - // policy instances that you can create using the current account. (Traffic - // policy instances are referred to as traffic flow policy records in the - // Amazon Route 53 console.) - // - // Type is a required field - Type *string `location:"uri" locationName:"Type" type:"string" required:"true" enum:"AccountLimitType"` -} - -// String returns the string representation -func (s GetAccountLimitInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetAccountLimitInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetAccountLimitInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetAccountLimitInput"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetType sets the Type field's value. -func (s *GetAccountLimitInput) SetType(v string) *GetAccountLimitInput { - s.Type = &v - return s -} - -// A complex type that contains the requested limit. -type GetAccountLimitOutput struct { - _ struct{} `type:"structure"` - - // The current number of entities that you have created of the specified type. - // For example, if you specified MAX_HEALTH_CHECKS_BY_OWNER for the value of - // Type in the request, the value of Count is the current number of health checks - // that you have created using the current account. - // - // Count is a required field - Count *int64 `type:"long" required:"true"` - - // The current setting for the specified limit. For example, if you specified - // MAX_HEALTH_CHECKS_BY_OWNER for the value of Type in the request, the value - // of Limit is the maximum number of health checks that you can create using - // the current account. - // - // Limit is a required field - Limit *AccountLimit `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetAccountLimitOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetAccountLimitOutput) GoString() string { - return s.String() -} - -// SetCount sets the Count field's value. -func (s *GetAccountLimitOutput) SetCount(v int64) *GetAccountLimitOutput { - s.Count = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetAccountLimitOutput) SetLimit(v *AccountLimit) *GetAccountLimitOutput { - s.Limit = v - return s -} - -// The input for a GetChange request. -type GetChangeInput struct { - _ struct{} `type:"structure"` - - // The ID of the change batch request. The value that you specify here is the - // value that ChangeResourceRecordSets returned in the Id element when you submitted - // the request. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetChangeInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetChangeInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetChangeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetChangeInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetChangeInput) SetId(v string) *GetChangeInput { - s.Id = &v - return s -} - -// A complex type that contains the ChangeInfo element. -type GetChangeOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the specified change batch. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetChangeOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetChangeOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *GetChangeOutput) SetChangeInfo(v *ChangeInfo) *GetChangeOutput { - s.ChangeInfo = v - return s -} - -type GetCheckerIpRangesInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetCheckerIpRangesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCheckerIpRangesInput) GoString() string { - return s.String() -} - -type GetCheckerIpRangesOutput struct { - _ struct{} `type:"structure"` - - // CheckerIpRanges is a required field - CheckerIpRanges []*string `type:"list" required:"true"` -} - -// String returns the string representation -func (s GetCheckerIpRangesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCheckerIpRangesOutput) GoString() string { - return s.String() -} - -// SetCheckerIpRanges sets the CheckerIpRanges field's value. -func (s *GetCheckerIpRangesOutput) SetCheckerIpRanges(v []*string) *GetCheckerIpRangesOutput { - s.CheckerIpRanges = v - return s -} - -// A request for information about whether a specified geographic location is -// supported for Amazon Route 53 geolocation resource record sets. -type GetGeoLocationInput struct { - _ struct{} `type:"structure"` - - // Amazon Route 53 supports the following continent codes: - // - // * AF: Africa - // - // * AN: Antarctica - // - // * AS: Asia - // - // * EU: Europe - // - // * OC: Oceania - // - // * NA: North America - // - // * SA: South America - ContinentCode *string `location:"querystring" locationName:"continentcode" min:"2" type:"string"` - - // Amazon Route 53 uses the two-letter country codes that are specified in ISO - // standard 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). - CountryCode *string `location:"querystring" locationName:"countrycode" min:"1" type:"string"` - - // Amazon Route 53 uses the one- to three-letter subdivision codes that are - // specified in ISO standard 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). - // Amazon Route 53 doesn't support subdivision codes for all countries. If you - // specify SubdivisionCode, you must also specify CountryCode. - SubdivisionCode *string `location:"querystring" locationName:"subdivisioncode" min:"1" type:"string"` -} - -// String returns the string representation -func (s GetGeoLocationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetGeoLocationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetGeoLocationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetGeoLocationInput"} - if s.ContinentCode != nil && len(*s.ContinentCode) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ContinentCode", 2)) - } - if s.CountryCode != nil && len(*s.CountryCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CountryCode", 1)) - } - if s.SubdivisionCode != nil && len(*s.SubdivisionCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SubdivisionCode", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *GetGeoLocationInput) SetContinentCode(v string) *GetGeoLocationInput { - s.ContinentCode = &v - return s -} - -// SetCountryCode sets the CountryCode field's value. -func (s *GetGeoLocationInput) SetCountryCode(v string) *GetGeoLocationInput { - s.CountryCode = &v - return s -} - -// SetSubdivisionCode sets the SubdivisionCode field's value. -func (s *GetGeoLocationInput) SetSubdivisionCode(v string) *GetGeoLocationInput { - s.SubdivisionCode = &v - return s -} - -// A complex type that contains the response information for the specified geolocation -// code. -type GetGeoLocationOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains the codes and full continent, country, and subdivision - // names for the specified geolocation code. - // - // GeoLocationDetails is a required field - GeoLocationDetails *GeoLocationDetails `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetGeoLocationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetGeoLocationOutput) GoString() string { - return s.String() -} - -// SetGeoLocationDetails sets the GeoLocationDetails field's value. -func (s *GetGeoLocationOutput) SetGeoLocationDetails(v *GeoLocationDetails) *GetGeoLocationOutput { - s.GeoLocationDetails = v - return s -} - -// A request for the number of health checks that are associated with the current -// AWS account. -type GetHealthCheckCountInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetHealthCheckCountInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckCountInput) GoString() string { - return s.String() -} - -// A complex type that contains the response to a GetHealthCheckCount request. -type GetHealthCheckCountOutput struct { - _ struct{} `type:"structure"` - - // The number of health checks associated with the current AWS account. - // - // HealthCheckCount is a required field - HealthCheckCount *int64 `type:"long" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckCountOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckCountOutput) GoString() string { - return s.String() -} - -// SetHealthCheckCount sets the HealthCheckCount field's value. -func (s *GetHealthCheckCountOutput) SetHealthCheckCount(v int64) *GetHealthCheckCountOutput { - s.HealthCheckCount = &v - return s -} - -// A request to get information about a specified health check. -type GetHealthCheckInput struct { - _ struct{} `type:"structure"` - - // The identifier that Amazon Route 53 assigned to the health check when you - // created it. When you add or update a resource record set, you use this value - // to specify which health check to use. The value can be up to 64 characters - // long. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHealthCheckInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *GetHealthCheckInput) SetHealthCheckId(v string) *GetHealthCheckInput { - s.HealthCheckId = &v - return s -} - -// A request for the reason that a health check failed most recently. -type GetHealthCheckLastFailureReasonInput struct { - _ struct{} `type:"structure"` - - // The ID for the health check for which you want the last failure reason. When - // you created the health check, CreateHealthCheck returned the ID in the response, - // in the HealthCheckId element. - // - // If you want to get the last failure reason for a calculated health check, - // you must use the Amazon Route 53 console or the CloudWatch console. You can't - // use GetHealthCheckLastFailureReason for a calculated health check. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckLastFailureReasonInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckLastFailureReasonInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHealthCheckLastFailureReasonInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHealthCheckLastFailureReasonInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *GetHealthCheckLastFailureReasonInput) SetHealthCheckId(v string) *GetHealthCheckLastFailureReasonInput { - s.HealthCheckId = &v - return s -} - -// A complex type that contains the response to a GetHealthCheckLastFailureReason -// request. -type GetHealthCheckLastFailureReasonOutput struct { - _ struct{} `type:"structure"` - - // A list that contains one Observation element for each Amazon Route 53 health - // checker that is reporting a last failure reason. - // - // HealthCheckObservations is a required field - HealthCheckObservations []*HealthCheckObservation `locationNameList:"HealthCheckObservation" type:"list" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckLastFailureReasonOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckLastFailureReasonOutput) GoString() string { - return s.String() -} - -// SetHealthCheckObservations sets the HealthCheckObservations field's value. -func (s *GetHealthCheckLastFailureReasonOutput) SetHealthCheckObservations(v []*HealthCheckObservation) *GetHealthCheckLastFailureReasonOutput { - s.HealthCheckObservations = v - return s -} - -// A complex type that contains the response to a GetHealthCheck request. -type GetHealthCheckOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about one health check that is associated - // with the current AWS account. - // - // HealthCheck is a required field - HealthCheck *HealthCheck `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckOutput) GoString() string { - return s.String() -} - -// SetHealthCheck sets the HealthCheck field's value. -func (s *GetHealthCheckOutput) SetHealthCheck(v *HealthCheck) *GetHealthCheckOutput { - s.HealthCheck = v - return s -} - -// A request to get the status for a health check. -type GetHealthCheckStatusInput struct { - _ struct{} `type:"structure"` - - // The ID for the health check that you want the current status for. When you - // created the health check, CreateHealthCheck returned the ID in the response, - // in the HealthCheckId element. - // - // If you want to check the status of a calculated health check, you must use - // the Amazon Route 53 console or the CloudWatch console. You can't use GetHealthCheckStatus - // to get the status of a calculated health check. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckStatusInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckStatusInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHealthCheckStatusInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHealthCheckStatusInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *GetHealthCheckStatusInput) SetHealthCheckId(v string) *GetHealthCheckStatusInput { - s.HealthCheckId = &v - return s -} - -// A complex type that contains the response to a GetHealthCheck request. -type GetHealthCheckStatusOutput struct { - _ struct{} `type:"structure"` - - // A list that contains one HealthCheckObservation element for each Amazon Route - // 53 health checker that is reporting a status about the health check endpoint. - // - // HealthCheckObservations is a required field - HealthCheckObservations []*HealthCheckObservation `locationNameList:"HealthCheckObservation" type:"list" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckStatusOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckStatusOutput) GoString() string { - return s.String() -} - -// SetHealthCheckObservations sets the HealthCheckObservations field's value. -func (s *GetHealthCheckStatusOutput) SetHealthCheckObservations(v []*HealthCheckObservation) *GetHealthCheckStatusOutput { - s.HealthCheckObservations = v - return s -} - -// A request to retrieve a count of all the hosted zones that are associated -// with the current AWS account. -type GetHostedZoneCountInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetHostedZoneCountInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneCountInput) GoString() string { - return s.String() -} - -// A complex type that contains the response to a GetHostedZoneCount request. -type GetHostedZoneCountOutput struct { - _ struct{} `type:"structure"` - - // The total number of public and private hosted zones that are associated with - // the current AWS account. - // - // HostedZoneCount is a required field - HostedZoneCount *int64 `type:"long" required:"true"` -} - -// String returns the string representation -func (s GetHostedZoneCountOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneCountOutput) GoString() string { - return s.String() -} - -// SetHostedZoneCount sets the HostedZoneCount field's value. -func (s *GetHostedZoneCountOutput) SetHostedZoneCount(v int64) *GetHostedZoneCountOutput { - s.HostedZoneCount = &v - return s -} - -// A request to get information about a specified hosted zone. -type GetHostedZoneInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you want to get information about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHostedZoneInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetHostedZoneInput) SetId(v string) *GetHostedZoneInput { - s.Id = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type GetHostedZoneLimitInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you want to get a limit for. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // The limit that you want to get. Valid values include the following: - // - // * MAX_RRSETS_BY_ZONE: The maximum number of records that you can create - // in the specified hosted zone. - // - // * MAX_VPCS_ASSOCIATED_BY_ZONE: The maximum number of Amazon VPCs that - // you can associate with the specified private hosted zone. - // - // Type is a required field - Type *string `location:"uri" locationName:"Type" type:"string" required:"true" enum:"HostedZoneLimitType"` -} - -// String returns the string representation -func (s GetHostedZoneLimitInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneLimitInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHostedZoneLimitInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHostedZoneLimitInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *GetHostedZoneLimitInput) SetHostedZoneId(v string) *GetHostedZoneLimitInput { - s.HostedZoneId = &v - return s -} - -// SetType sets the Type field's value. -func (s *GetHostedZoneLimitInput) SetType(v string) *GetHostedZoneLimitInput { - s.Type = &v - return s -} - -// A complex type that contains the requested limit. -type GetHostedZoneLimitOutput struct { - _ struct{} `type:"structure"` - - // The current number of entities that you have created of the specified type. - // For example, if you specified MAX_RRSETS_BY_ZONE for the value of Type in - // the request, the value of Count is the current number of records that you - // have created in the specified hosted zone. - // - // Count is a required field - Count *int64 `type:"long" required:"true"` - - // The current setting for the specified limit. For example, if you specified - // MAX_RRSETS_BY_ZONE for the value of Type in the request, the value of Limit - // is the maximum number of records that you can create in the specified hosted - // zone. - // - // Limit is a required field - Limit *HostedZoneLimit `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetHostedZoneLimitOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneLimitOutput) GoString() string { - return s.String() -} - -// SetCount sets the Count field's value. -func (s *GetHostedZoneLimitOutput) SetCount(v int64) *GetHostedZoneLimitOutput { - s.Count = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetHostedZoneLimitOutput) SetLimit(v *HostedZoneLimit) *GetHostedZoneLimitOutput { - s.Limit = v - return s -} - -// A complex type that contain the response to a GetHostedZone request. -type GetHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that lists the Amazon Route 53 name servers for the specified - // hosted zone. - DelegationSet *DelegationSet `type:"structure"` - - // A complex type that contains general information about the specified hosted - // zone. - // - // HostedZone is a required field - HostedZone *HostedZone `type:"structure" required:"true"` - - // A complex type that contains information about the VPCs that are associated - // with the specified hosted zone. - VPCs []*VPC `locationNameList:"VPC" min:"1" type:"list"` -} - -// String returns the string representation -func (s GetHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneOutput) GoString() string { - return s.String() -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *GetHostedZoneOutput) SetDelegationSet(v *DelegationSet) *GetHostedZoneOutput { - s.DelegationSet = v - return s -} - -// SetHostedZone sets the HostedZone field's value. -func (s *GetHostedZoneOutput) SetHostedZone(v *HostedZone) *GetHostedZoneOutput { - s.HostedZone = v - return s -} - -// SetVPCs sets the VPCs field's value. -func (s *GetHostedZoneOutput) SetVPCs(v []*VPC) *GetHostedZoneOutput { - s.VPCs = v - return s -} - -type GetQueryLoggingConfigInput struct { - _ struct{} `type:"structure"` - - // The ID of the configuration for DNS query logging that you want to get information - // about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetQueryLoggingConfigInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetQueryLoggingConfigInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetQueryLoggingConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetQueryLoggingConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetQueryLoggingConfigInput) SetId(v string) *GetQueryLoggingConfigInput { - s.Id = &v - return s -} - -type GetQueryLoggingConfigOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the query logging configuration - // that you specified in a GetQueryLoggingConfig request. - // - // QueryLoggingConfig is a required field - QueryLoggingConfig *QueryLoggingConfig `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetQueryLoggingConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetQueryLoggingConfigOutput) GoString() string { - return s.String() -} - -// SetQueryLoggingConfig sets the QueryLoggingConfig field's value. -func (s *GetQueryLoggingConfigOutput) SetQueryLoggingConfig(v *QueryLoggingConfig) *GetQueryLoggingConfigOutput { - s.QueryLoggingConfig = v - return s -} - -// A request to get information about a specified reusable delegation set. -type GetReusableDelegationSetInput struct { - _ struct{} `type:"structure"` - - // The ID of the reusable delegation set that you want to get a list of name - // servers for. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetReusableDelegationSetInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetReusableDelegationSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetReusableDelegationSetInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetReusableDelegationSetInput) SetId(v string) *GetReusableDelegationSetInput { - s.Id = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type GetReusableDelegationSetLimitInput struct { - _ struct{} `type:"structure"` - - // The ID of the delegation set that you want to get the limit for. - // - // DelegationSetId is a required field - DelegationSetId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // Specify MAX_ZONES_BY_REUSABLE_DELEGATION_SET to get the maximum number of - // hosted zones that you can associate with the specified reusable delegation - // set. - // - // Type is a required field - Type *string `location:"uri" locationName:"Type" type:"string" required:"true" enum:"ReusableDelegationSetLimitType"` -} - -// String returns the string representation -func (s GetReusableDelegationSetLimitInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetLimitInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetReusableDelegationSetLimitInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetReusableDelegationSetLimitInput"} - if s.DelegationSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DelegationSetId")) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDelegationSetId sets the DelegationSetId field's value. -func (s *GetReusableDelegationSetLimitInput) SetDelegationSetId(v string) *GetReusableDelegationSetLimitInput { - s.DelegationSetId = &v - return s -} - -// SetType sets the Type field's value. -func (s *GetReusableDelegationSetLimitInput) SetType(v string) *GetReusableDelegationSetLimitInput { - s.Type = &v - return s -} - -// A complex type that contains the requested limit. -type GetReusableDelegationSetLimitOutput struct { - _ struct{} `type:"structure"` - - // The current number of hosted zones that you can associate with the specified - // reusable delegation set. - // - // Count is a required field - Count *int64 `type:"long" required:"true"` - - // The current setting for the limit on hosted zones that you can associate - // with the specified reusable delegation set. - // - // Limit is a required field - Limit *ReusableDelegationSetLimit `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetReusableDelegationSetLimitOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetLimitOutput) GoString() string { - return s.String() -} - -// SetCount sets the Count field's value. -func (s *GetReusableDelegationSetLimitOutput) SetCount(v int64) *GetReusableDelegationSetLimitOutput { - s.Count = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetReusableDelegationSetLimitOutput) SetLimit(v *ReusableDelegationSetLimit) *GetReusableDelegationSetLimitOutput { - s.Limit = v - return s -} - -// A complex type that contains the response to the GetReusableDelegationSet -// request. -type GetReusableDelegationSetOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the reusable delegation set. - // - // DelegationSet is a required field - DelegationSet *DelegationSet `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetReusableDelegationSetOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetOutput) GoString() string { - return s.String() -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *GetReusableDelegationSetOutput) SetDelegationSet(v *DelegationSet) *GetReusableDelegationSetOutput { - s.DelegationSet = v - return s -} - -// Gets information about a specific traffic policy version. -type GetTrafficPolicyInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy that you want to get information about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The version number of the traffic policy that you want to get information - // about. - // - // Version is a required field - Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetTrafficPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetTrafficPolicyInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.Version == nil { - invalidParams.Add(request.NewErrParamRequired("Version")) - } - if s.Version != nil && *s.Version < 1 { - invalidParams.Add(request.NewErrParamMinValue("Version", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetTrafficPolicyInput) SetId(v string) *GetTrafficPolicyInput { - s.Id = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *GetTrafficPolicyInput) SetVersion(v int64) *GetTrafficPolicyInput { - s.Version = &v - return s -} - -// Request to get the number of traffic policy instances that are associated -// with the current AWS account. -type GetTrafficPolicyInstanceCountInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceCountInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceCountInput) GoString() string { - return s.String() -} - -// A complex type that contains information about the resource record sets that -// Amazon Route 53 created based on a specified traffic policy. -type GetTrafficPolicyInstanceCountOutput struct { - _ struct{} `type:"structure"` - - // The number of traffic policy instances that are associated with the current - // AWS account. - // - // TrafficPolicyInstanceCount is a required field - TrafficPolicyInstanceCount *int64 `type:"integer" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceCountOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceCountOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicyInstanceCount sets the TrafficPolicyInstanceCount field's value. -func (s *GetTrafficPolicyInstanceCountOutput) SetTrafficPolicyInstanceCount(v int64) *GetTrafficPolicyInstanceCountOutput { - s.TrafficPolicyInstanceCount = &v - return s -} - -// Gets information about a specified traffic policy instance. -type GetTrafficPolicyInstanceInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy instance that you want to get information about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetTrafficPolicyInstanceInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetTrafficPolicyInstanceInput) SetId(v string) *GetTrafficPolicyInstanceInput { - s.Id = &v - return s -} - -// A complex type that contains information about the resource record sets that -// Amazon Route 53 created based on a specified traffic policy. -type GetTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the traffic policy instance. - // - // TrafficPolicyInstance is a required field - TrafficPolicyInstance *TrafficPolicyInstance `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicyInstance sets the TrafficPolicyInstance field's value. -func (s *GetTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficPolicyInstance) *GetTrafficPolicyInstanceOutput { - s.TrafficPolicyInstance = v - return s -} - -// A complex type that contains the response information for the request. -type GetTrafficPolicyOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the specified traffic policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *GetTrafficPolicyOutput) SetTrafficPolicy(v *TrafficPolicy) *GetTrafficPolicyOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about one health check that is associated -// with the current AWS account. -type HealthCheck struct { - _ struct{} `type:"structure"` - - // A unique string that you specified when you created the health check. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // A complex type that contains information about the CloudWatch alarm that - // Amazon Route 53 is monitoring for this health check. - CloudWatchAlarmConfiguration *CloudWatchAlarmConfiguration `type:"structure"` - - // A complex type that contains detailed information about one health check. - // - // HealthCheckConfig is a required field - HealthCheckConfig *HealthCheckConfig `type:"structure" required:"true"` - - // The version of the health check. You can optionally pass this value in a - // call to UpdateHealthCheck to prevent overwriting another change to the health - // check. - // - // HealthCheckVersion is a required field - HealthCheckVersion *int64 `min:"1" type:"long" required:"true"` - - // The identifier that Amazon Route 53assigned to the health check when you - // created it. When you add or update a resource record set, you use this value - // to specify which health check to use. The value can be up to 64 characters - // long. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // If the health check was created by another service, the service that created - // the health check. When a health check is created by another service, you - // can't edit or delete it using Amazon Route 53. - LinkedService *LinkedService `type:"structure"` -} - -// String returns the string representation -func (s HealthCheck) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HealthCheck) GoString() string { - return s.String() -} - -// SetCallerReference sets the CallerReference field's value. -func (s *HealthCheck) SetCallerReference(v string) *HealthCheck { - s.CallerReference = &v - return s -} - -// SetCloudWatchAlarmConfiguration sets the CloudWatchAlarmConfiguration field's value. -func (s *HealthCheck) SetCloudWatchAlarmConfiguration(v *CloudWatchAlarmConfiguration) *HealthCheck { - s.CloudWatchAlarmConfiguration = v - return s -} - -// SetHealthCheckConfig sets the HealthCheckConfig field's value. -func (s *HealthCheck) SetHealthCheckConfig(v *HealthCheckConfig) *HealthCheck { - s.HealthCheckConfig = v - return s -} - -// SetHealthCheckVersion sets the HealthCheckVersion field's value. -func (s *HealthCheck) SetHealthCheckVersion(v int64) *HealthCheck { - s.HealthCheckVersion = &v - return s -} - -// SetId sets the Id field's value. -func (s *HealthCheck) SetId(v string) *HealthCheck { - s.Id = &v - return s -} - -// SetLinkedService sets the LinkedService field's value. -func (s *HealthCheck) SetLinkedService(v *LinkedService) *HealthCheck { - s.LinkedService = v - return s -} - -// A complex type that contains information about the health check. -type HealthCheckConfig struct { - _ struct{} `type:"structure"` - - // A complex type that identifies the CloudWatch alarm that you want Amazon - // Route 53 health checkers to use to determine whether this health check is - // healthy. - AlarmIdentifier *AlarmIdentifier `type:"structure"` - - // (CALCULATED Health Checks Only) A complex type that contains one ChildHealthCheck - // element for each health check that you want to associate with a CALCULATED - // health check. - ChildHealthChecks []*string `locationNameList:"ChildHealthCheck" type:"list"` - - // Specify whether you want Amazon Route 53 to send the value of FullyQualifiedDomainName - // to the endpoint in the client_hello message during TLS negotiation. This - // allows the endpoint to respond to HTTPS health check requests with the applicable - // SSL/TLS certificate. - // - // Some endpoints require that HTTPS requests include the host name in the client_hello - // message. If you don't enable SNI, the status of the health check will be - // SSL alert handshake_failure. A health check can also have that status for - // other reasons. If SNI is enabled and you're still getting the error, check - // the SSL/TLS configuration on your endpoint and confirm that your certificate - // is valid. - // - // The SSL/TLS certificate on your endpoint includes a domain name in the Common - // Name field and possibly several more in the Subject Alternative Names field. - // One of the domain names in the certificate should match the value that you - // specify for FullyQualifiedDomainName. If the endpoint responds to the client_hello - // message with a certificate that does not include the domain name that you - // specified in FullyQualifiedDomainName, a health checker will retry the handshake. - // In the second attempt, the health checker will omit FullyQualifiedDomainName - // from the client_hello message. - EnableSNI *bool `type:"boolean"` - - // The number of consecutive health checks that an endpoint must pass or fail - // for Amazon Route 53 to change the current status of the endpoint from unhealthy - // to healthy or vice versa. For more information, see How Amazon Route 53 Determines - // Whether an Endpoint Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - // in the Amazon Route 53 Developer Guide. - // - // If you don't specify a value for FailureThreshold, the default value is three - // health checks. - FailureThreshold *int64 `min:"1" type:"integer"` - - // Amazon Route 53 behavior depends on whether you specify a value for IPAddress. - // - // If you specify a value forIPAddress: - // - // Amazon Route 53 sends health check requests to the specified IPv4 or IPv6 - // address and passes the value of FullyQualifiedDomainName in the Host header - // for all health checks except TCP health checks. This is typically the fully - // qualified DNS name of the endpoint on which you want Amazon Route 53 to perform - // health checks. - // - // When Amazon Route 53 checks the health of an endpoint, here is how it constructs - // the Host header: - // - // * If you specify a value of 80 for Port and HTTP or HTTP_STR_MATCH for - // Type, Amazon Route 53 passes the value of FullyQualifiedDomainName to - // the endpoint in the Host header. - // - // * If you specify a value of 443 for Port and HTTPS or HTTPS_STR_MATCH - // for Type, Amazon Route 53 passes the value of FullyQualifiedDomainName - // to the endpoint in the Host header. - // - // * If you specify another value for Port and any value except TCP for Type, - // Amazon Route 53 passes FullyQualifiedDomainName:Port to the endpoint in - // the Host header. - // - // If you don't specify a value for FullyQualifiedDomainName, Amazon Route 53 - // substitutes the value of IPAddress in the Host header in each of the preceding - // cases. - // - // If you don't specify a value for IPAddress: - // - // Amazon Route 53 sends a DNS request to the domain that you specify for FullyQualifiedDomainName - // at the interval that you specify for RequestInterval. Using an IPv4 address - // that DNS returns, Amazon Route 53 then checks the health of the endpoint. - // - // If you don't specify a value for IPAddress, Amazon Route 53 uses only IPv4 - // to send health checks to the endpoint. If there's no resource record set - // with a type of A for the name that you specify for FullyQualifiedDomainName, - // the health check fails with a "DNS resolution failed" error. - // - // If you want to check the health of weighted, latency, or failover resource - // record sets and you choose to specify the endpoint only by FullyQualifiedDomainName, - // we recommend that you create a separate health check for each endpoint. For - // example, create a health check for each HTTP server that is serving content - // for www.example.com. For the value of FullyQualifiedDomainName, specify the - // domain name of the server (such as us-east-2-www.example.com), not the name - // of the resource record sets (www.example.com). - // - // In this configuration, if you create a health check for which the value of - // FullyQualifiedDomainName matches the name of the resource record sets and - // you then associate the health check with those resource record sets, health - // check results will be unpredictable. - // - // In addition, if the value that you specify for Type is HTTP, HTTPS, HTTP_STR_MATCH, - // or HTTPS_STR_MATCH, Amazon Route 53 passes the value of FullyQualifiedDomainName - // in the Host header, as it does when you specify a value for IPAddress. If - // the value of Type is TCP, Amazon Route 53 doesn't pass a Host header. - FullyQualifiedDomainName *string `type:"string"` - - // The number of child health checks that are associated with a CALCULATED health - // that Amazon Route 53 must consider healthy for the CALCULATED health check - // to be considered healthy. To specify the child health checks that you want - // to associate with a CALCULATED health check, use the HealthCheckConfig$ChildHealthChecks - // and HealthCheckConfig$ChildHealthChecks elements. - // - // Note the following: - // - // * If you specify a number greater than the number of child health checks, - // Amazon Route 53 always considers this health check to be unhealthy. - // - // * If you specify 0, Amazon Route 53 always considers this health check - // to be healthy. - HealthThreshold *int64 `type:"integer"` - - // The IPv4 or IPv6 IP address of the endpoint that you want Amazon Route 53 - // to perform health checks on. If you don't specify a value for IPAddress, - // Amazon Route 53 sends a DNS request to resolve the domain name that you specify - // in FullyQualifiedDomainName at the interval that you specify in RequestInterval. - // Using an IP address returned by DNS, Amazon Route 53 then checks the health - // of the endpoint. - // - // Use one of the following formats for the value of IPAddress: - // - // * IPv4 address: four values between 0 and 255, separated by periods (.), - // for example, 192.0.2.44. - // - // * IPv6 address: eight groups of four hexadecimal values, separated by - // colons (:), for example, 2001:0db8:85a3:0000:0000:abcd:0001:2345. You - // can also shorten IPv6 addresses as described in RFC 5952, for example, - // 2001:db8:85a3::abcd:1:2345. - // - // If the endpoint is an EC2 instance, we recommend that you create an Elastic - // IP address, associate it with your EC2 instance, and specify the Elastic - // IP address for IPAddress. This ensures that the IP address of your instance - // will never change. - // - // For more information, see HealthCheckConfig$FullyQualifiedDomainName. - // - // Constraints: Amazon Route 53 can't check the health of endpoints for which - // the IP address is in local, private, non-routable, or multicast ranges. For - // more information about IP addresses for which you can't create health checks, - // see the following documents: - // - // * RFC 5735, Special Use IPv4 Addresses (https://tools.ietf.org/html/rfc5735) - // - // * RFC 6598, IANA-Reserved IPv4 Prefix for Shared Address Space (https://tools.ietf.org/html/rfc6598) - // - // * RFC 5156, Special-Use IPv6 Addresses (https://tools.ietf.org/html/rfc5156) - // - // When the value of Type is CALCULATED or CLOUDWATCH_METRIC, omit IPAddress. - IPAddress *string `type:"string"` - - // When CloudWatch has insufficient data about the metric to determine the alarm - // state, the status that you want Amazon Route 53 to assign to the health check: - // - // * Healthy: Amazon Route 53 considers the health check to be healthy. - // - // * Unhealthy: Amazon Route 53 considers the health check to be unhealthy. - // - // * LastKnownStatus: Amazon Route 53 uses the status of the health check - // from the last time that CloudWatch had sufficient data to determine the - // alarm state. For new health checks that have no last known status, the - // default status for the health check is healthy. - InsufficientDataHealthStatus *string `type:"string" enum:"InsufficientDataHealthStatus"` - - // Specify whether you want Amazon Route 53 to invert the status of a health - // check, for example, to consider a health check unhealthy when it otherwise - // would be considered healthy. - Inverted *bool `type:"boolean"` - - // Specify whether you want Amazon Route 53 to measure the latency between health - // checkers in multiple AWS regions and your endpoint, and to display CloudWatch - // latency graphs on the Health Checks page in the Amazon Route 53 console. - // - // You can't change the value of MeasureLatency after you create a health check. - MeasureLatency *bool `type:"boolean"` - - // The port on the endpoint on which you want Amazon Route 53 to perform health - // checks. Specify a value for Port only when you specify a value for IPAddress. - Port *int64 `min:"1" type:"integer"` - - // A complex type that contains one Region element for each region from which - // you want Amazon Route 53 health checkers to check the specified endpoint. - // - // If you don't specify any regions, Amazon Route 53 health checkers automatically - // performs checks from all of the regions that are listed under Valid Values. - // - // If you update a health check to remove a region that has been performing - // health checks, Amazon Route 53 will briefly continue to perform checks from - // that region to ensure that some health checkers are always checking the endpoint - // (for example, if you replace three regions with four different regions). - Regions []*string `locationNameList:"Region" min:"3" type:"list"` - - // The number of seconds between the time that Amazon Route 53 gets a response - // from your endpoint and the time that it sends the next health check request. - // Each Amazon Route 53 health checker makes requests at this interval. - // - // You can't change the value of RequestInterval after you create a health check. - // - // If you don't specify a value for RequestInterval, the default value is 30 - // seconds. - RequestInterval *int64 `min:"10" type:"integer"` - - // The path, if any, that you want Amazon Route 53 to request when performing - // health checks. The path can be any value for which your endpoint will return - // an HTTP status code of 2xx or 3xx when the endpoint is healthy, for example, - // the file /docs/route53-health-check.html. - ResourcePath *string `type:"string"` - - // If the value of Type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string that - // you want Amazon Route 53 to search for in the response body from the specified - // resource. If the string appears in the response body, Amazon Route 53 considers - // the resource healthy. - // - // Amazon Route 53 considers case when searching for SearchString in the response - // body. - SearchString *string `type:"string"` - - // The type of health check that you want to create, which indicates how Amazon - // Route 53 determines whether an endpoint is healthy. - // - // You can't change the value of Type after you create a health check. - // - // You can create the following types of health checks: - // - // * HTTP: Amazon Route 53 tries to establish a TCP connection. If successful, - // Amazon Route 53 submits an HTTP request and waits for an HTTP status code - // of 200 or greater and less than 400. - // - // * HTTPS: Amazon Route 53 tries to establish a TCP connection. If successful, - // Amazon Route 53 submits an HTTPS request and waits for an HTTP status - // code of 200 or greater and less than 400. - // - // If you specify HTTPS for the value of Type, the endpoint must support TLS - // v1.0 or later. - // - // * HTTP_STR_MATCH: Amazon Route 53 tries to establish a TCP connection. - // If successful, Amazon Route 53 submits an HTTP request and searches the - // first 5,120 bytes of the response body for the string that you specify - // in SearchString. - // - // * HTTPS_STR_MATCH: Amazon Route 53 tries to establish a TCP connection. - // If successful, Amazon Route 53 submits an HTTPS request and searches the - // first 5,120 bytes of the response body for the string that you specify - // in SearchString. - // - // * TCP: Amazon Route 53 tries to establish a TCP connection. - // - // * CLOUDWATCH_METRIC: The health check is associated with a CloudWatch - // alarm. If the state of the alarm is OK, the health check is considered - // healthy. If the state is ALARM, the health check is considered unhealthy. - // If CloudWatch doesn't have sufficient data to determine whether the state - // is OK or ALARM, the health check status depends on the setting for InsufficientDataHealthStatus: - // Healthy, Unhealthy, or LastKnownStatus. - // - // * CALCULATED: For health checks that monitor the status of other health - // checks, Amazon Route 53 adds up the number of health checks that Amazon - // Route 53 health checkers consider to be healthy and compares that number - // with the value of HealthThreshold. - // - // For more information, see How Amazon Route 53 Determines Whether an Endpoint - // Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - // in the Amazon Route 53 Developer Guide. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"HealthCheckType"` -} - -// String returns the string representation -func (s HealthCheckConfig) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HealthCheckConfig) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *HealthCheckConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HealthCheckConfig"} - if s.FailureThreshold != nil && *s.FailureThreshold < 1 { - invalidParams.Add(request.NewErrParamMinValue("FailureThreshold", 1)) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } - if s.Regions != nil && len(s.Regions) < 3 { - invalidParams.Add(request.NewErrParamMinLen("Regions", 3)) - } - if s.RequestInterval != nil && *s.RequestInterval < 10 { - invalidParams.Add(request.NewErrParamMinValue("RequestInterval", 10)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.AlarmIdentifier != nil { - if err := s.AlarmIdentifier.Validate(); err != nil { - invalidParams.AddNested("AlarmIdentifier", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAlarmIdentifier sets the AlarmIdentifier field's value. -func (s *HealthCheckConfig) SetAlarmIdentifier(v *AlarmIdentifier) *HealthCheckConfig { - s.AlarmIdentifier = v - return s -} - -// SetChildHealthChecks sets the ChildHealthChecks field's value. -func (s *HealthCheckConfig) SetChildHealthChecks(v []*string) *HealthCheckConfig { - s.ChildHealthChecks = v - return s -} - -// SetEnableSNI sets the EnableSNI field's value. -func (s *HealthCheckConfig) SetEnableSNI(v bool) *HealthCheckConfig { - s.EnableSNI = &v - return s -} - -// SetFailureThreshold sets the FailureThreshold field's value. -func (s *HealthCheckConfig) SetFailureThreshold(v int64) *HealthCheckConfig { - s.FailureThreshold = &v - return s -} - -// SetFullyQualifiedDomainName sets the FullyQualifiedDomainName field's value. -func (s *HealthCheckConfig) SetFullyQualifiedDomainName(v string) *HealthCheckConfig { - s.FullyQualifiedDomainName = &v - return s -} - -// SetHealthThreshold sets the HealthThreshold field's value. -func (s *HealthCheckConfig) SetHealthThreshold(v int64) *HealthCheckConfig { - s.HealthThreshold = &v - return s -} - -// SetIPAddress sets the IPAddress field's value. -func (s *HealthCheckConfig) SetIPAddress(v string) *HealthCheckConfig { - s.IPAddress = &v - return s -} - -// SetInsufficientDataHealthStatus sets the InsufficientDataHealthStatus field's value. -func (s *HealthCheckConfig) SetInsufficientDataHealthStatus(v string) *HealthCheckConfig { - s.InsufficientDataHealthStatus = &v - return s -} - -// SetInverted sets the Inverted field's value. -func (s *HealthCheckConfig) SetInverted(v bool) *HealthCheckConfig { - s.Inverted = &v - return s -} - -// SetMeasureLatency sets the MeasureLatency field's value. -func (s *HealthCheckConfig) SetMeasureLatency(v bool) *HealthCheckConfig { - s.MeasureLatency = &v - return s -} - -// SetPort sets the Port field's value. -func (s *HealthCheckConfig) SetPort(v int64) *HealthCheckConfig { - s.Port = &v - return s -} - -// SetRegions sets the Regions field's value. -func (s *HealthCheckConfig) SetRegions(v []*string) *HealthCheckConfig { - s.Regions = v - return s -} - -// SetRequestInterval sets the RequestInterval field's value. -func (s *HealthCheckConfig) SetRequestInterval(v int64) *HealthCheckConfig { - s.RequestInterval = &v - return s -} - -// SetResourcePath sets the ResourcePath field's value. -func (s *HealthCheckConfig) SetResourcePath(v string) *HealthCheckConfig { - s.ResourcePath = &v - return s -} - -// SetSearchString sets the SearchString field's value. -func (s *HealthCheckConfig) SetSearchString(v string) *HealthCheckConfig { - s.SearchString = &v - return s -} - -// SetType sets the Type field's value. -func (s *HealthCheckConfig) SetType(v string) *HealthCheckConfig { - s.Type = &v - return s -} - -// A complex type that contains the last failure reason as reported by one Amazon -// Route 53 health checker. -type HealthCheckObservation struct { - _ struct{} `type:"structure"` - - // The IP address of the Amazon Route 53 health checker that provided the failure - // reason in StatusReport. - IPAddress *string `type:"string"` - - // The region of the Amazon Route 53 health checker that provided the status - // in StatusReport. - Region *string `min:"1" type:"string" enum:"HealthCheckRegion"` - - // A complex type that contains the last failure reason as reported by one Amazon - // Route 53 health checker and the time of the failed health check. - StatusReport *StatusReport `type:"structure"` -} - -// String returns the string representation -func (s HealthCheckObservation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HealthCheckObservation) GoString() string { - return s.String() -} - -// SetIPAddress sets the IPAddress field's value. -func (s *HealthCheckObservation) SetIPAddress(v string) *HealthCheckObservation { - s.IPAddress = &v - return s -} - -// SetRegion sets the Region field's value. -func (s *HealthCheckObservation) SetRegion(v string) *HealthCheckObservation { - s.Region = &v - return s -} - -// SetStatusReport sets the StatusReport field's value. -func (s *HealthCheckObservation) SetStatusReport(v *StatusReport) *HealthCheckObservation { - s.StatusReport = v - return s -} - -// A complex type that contains general information about the hosted zone. -type HostedZone struct { - _ struct{} `type:"structure"` - - // The value that you specified for CallerReference when you created the hosted - // zone. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // A complex type that includes the Comment and PrivateZone elements. If you - // omitted the HostedZoneConfig and Comment elements from the request, the Config - // and Comment elements don't appear in the response. - Config *HostedZoneConfig `type:"structure"` - - // The ID that Amazon Route 53 assigned to the hosted zone when you created - // it. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // If the hosted zone was created by another service, the service that created - // the hosted zone. When a hosted zone is created by another service, you can't - // edit or delete it using Amazon Route 53. - LinkedService *LinkedService `type:"structure"` - - // The name of the domain. For public hosted zones, this is the name that you - // have registered with your DNS registrar. - // - // For information about how to specify characters other than a-z, 0-9, and - // - (hyphen) and how to specify internationalized domain names, see CreateHostedZone. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The number of resource record sets in the hosted zone. - ResourceRecordSetCount *int64 `type:"long"` -} - -// String returns the string representation -func (s HostedZone) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HostedZone) GoString() string { - return s.String() -} - -// SetCallerReference sets the CallerReference field's value. -func (s *HostedZone) SetCallerReference(v string) *HostedZone { - s.CallerReference = &v - return s -} - -// SetConfig sets the Config field's value. -func (s *HostedZone) SetConfig(v *HostedZoneConfig) *HostedZone { - s.Config = v - return s -} - -// SetId sets the Id field's value. -func (s *HostedZone) SetId(v string) *HostedZone { - s.Id = &v - return s -} - -// SetLinkedService sets the LinkedService field's value. -func (s *HostedZone) SetLinkedService(v *LinkedService) *HostedZone { - s.LinkedService = v - return s -} - -// SetName sets the Name field's value. -func (s *HostedZone) SetName(v string) *HostedZone { - s.Name = &v - return s -} - -// SetResourceRecordSetCount sets the ResourceRecordSetCount field's value. -func (s *HostedZone) SetResourceRecordSetCount(v int64) *HostedZone { - s.ResourceRecordSetCount = &v - return s -} - -// A complex type that contains an optional comment about your hosted zone. -// If you don't want to specify a comment, omit both the HostedZoneConfig and -// Comment elements. -type HostedZoneConfig struct { - _ struct{} `type:"structure"` - - // Any comments that you want to include about the hosted zone. - Comment *string `type:"string"` - - // A value that indicates whether this is a private hosted zone. - PrivateZone *bool `type:"boolean"` -} - -// String returns the string representation -func (s HostedZoneConfig) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HostedZoneConfig) GoString() string { - return s.String() -} - -// SetComment sets the Comment field's value. -func (s *HostedZoneConfig) SetComment(v string) *HostedZoneConfig { - s.Comment = &v - return s -} - -// SetPrivateZone sets the PrivateZone field's value. -func (s *HostedZoneConfig) SetPrivateZone(v bool) *HostedZoneConfig { - s.PrivateZone = &v - return s -} - -// A complex type that contains the type of limit that you specified in the -// request and the current value for that limit. -type HostedZoneLimit struct { - _ struct{} `type:"structure"` - - // The limit that you requested. Valid values include the following: - // - // * MAX_RRSETS_BY_ZONE: The maximum number of records that you can create - // in the specified hosted zone. - // - // * MAX_VPCS_ASSOCIATED_BY_ZONE: The maximum number of Amazon VPCs that - // you can associate with the specified private hosted zone. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"HostedZoneLimitType"` - - // The current value for the limit that is specified by Type. - // - // Value is a required field - Value *int64 `min:"1" type:"long" required:"true"` -} - -// String returns the string representation -func (s HostedZoneLimit) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HostedZoneLimit) GoString() string { - return s.String() -} - -// SetType sets the Type field's value. -func (s *HostedZoneLimit) SetType(v string) *HostedZoneLimit { - s.Type = &v - return s -} - -// SetValue sets the Value field's value. -func (s *HostedZoneLimit) SetValue(v int64) *HostedZoneLimit { - s.Value = &v - return s -} - -// If a health check or hosted zone was created by another service, LinkedService -// is a complex type that describes the service that created the resource. When -// a resource is created by another service, you can't edit or delete it using -// Amazon Route 53. -type LinkedService struct { - _ struct{} `type:"structure"` - - // If the health check or hosted zone was created by another service, an optional - // description that can be provided by the other service. When a resource is - // created by another service, you can't edit or delete it using Amazon Route - // 53. - Description *string `type:"string"` - - // If the health check or hosted zone was created by another service, the service - // that created the resource. When a resource is created by another service, - // you can't edit or delete it using Amazon Route 53. - ServicePrincipal *string `type:"string"` -} - -// String returns the string representation -func (s LinkedService) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LinkedService) GoString() string { - return s.String() -} - -// SetDescription sets the Description field's value. -func (s *LinkedService) SetDescription(v string) *LinkedService { - s.Description = &v - return s -} - -// SetServicePrincipal sets the ServicePrincipal field's value. -func (s *LinkedService) SetServicePrincipal(v string) *LinkedService { - s.ServicePrincipal = &v - return s -} - -// A request to get a list of geographic locations that Amazon Route 53 supports -// for geolocation resource record sets. -type ListGeoLocationsInput struct { - _ struct{} `type:"structure"` - - // (Optional) The maximum number of geolocations to be included in the response - // body for this request. If more than MaxItems geolocations remain to be listed, - // then the value of the IsTruncated element in the response is true. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // The code for the continent with which you want to start listing locations - // that Amazon Route 53 supports for geolocation. If Amazon Route 53 has already - // returned a page or more of results, if IsTruncated is true, and if NextContinentCode - // from the previous response has a value, enter that value in StartContinentCode - // to return the next page of results. - // - // Include StartContinentCode only if you want to list continents. Don't include - // StartContinentCode when you're listing countries or countries with their - // subdivisions. - StartContinentCode *string `location:"querystring" locationName:"startcontinentcode" min:"2" type:"string"` - - // The code for the country with which you want to start listing locations that - // Amazon Route 53 supports for geolocation. If Amazon Route 53 has already - // returned a page or more of results, if IsTruncated is true, and if NextCountryCode - // from the previous response has a value, enter that value in StartCountryCode - // to return the next page of results. - // - // Amazon Route 53 uses the two-letter country codes that are specified in ISO - // standard 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). - StartCountryCode *string `location:"querystring" locationName:"startcountrycode" min:"1" type:"string"` - - // The code for the subdivision (for example, state or province) with which - // you want to start listing locations that Amazon Route 53 supports for geolocation. - // If Amazon Route 53 has already returned a page or more of results, if IsTruncated - // is true, and if NextSubdivisionCode from the previous response has a value, - // enter that value in StartSubdivisionCode to return the next page of results. - // - // To list subdivisions of a country, you must include both StartCountryCode - // and StartSubdivisionCode. - StartSubdivisionCode *string `location:"querystring" locationName:"startsubdivisioncode" min:"1" type:"string"` -} - -// String returns the string representation -func (s ListGeoLocationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListGeoLocationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListGeoLocationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListGeoLocationsInput"} - if s.StartContinentCode != nil && len(*s.StartContinentCode) < 2 { - invalidParams.Add(request.NewErrParamMinLen("StartContinentCode", 2)) - } - if s.StartCountryCode != nil && len(*s.StartCountryCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("StartCountryCode", 1)) - } - if s.StartSubdivisionCode != nil && len(*s.StartSubdivisionCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("StartSubdivisionCode", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListGeoLocationsInput) SetMaxItems(v string) *ListGeoLocationsInput { - s.MaxItems = &v - return s -} - -// SetStartContinentCode sets the StartContinentCode field's value. -func (s *ListGeoLocationsInput) SetStartContinentCode(v string) *ListGeoLocationsInput { - s.StartContinentCode = &v - return s -} - -// SetStartCountryCode sets the StartCountryCode field's value. -func (s *ListGeoLocationsInput) SetStartCountryCode(v string) *ListGeoLocationsInput { - s.StartCountryCode = &v - return s -} - -// SetStartSubdivisionCode sets the StartSubdivisionCode field's value. -func (s *ListGeoLocationsInput) SetStartSubdivisionCode(v string) *ListGeoLocationsInput { - s.StartSubdivisionCode = &v - return s -} - -// A complex type containing the response information for the request. -type ListGeoLocationsOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains one GeoLocationDetails element for each location - // that Amazon Route 53 supports for geolocation. - // - // GeoLocationDetailsList is a required field - GeoLocationDetailsList []*GeoLocationDetails `locationNameList:"GeoLocationDetails" type:"list" required:"true"` - - // A value that indicates whether more locations remain to be listed after the - // last location in this response. If so, the value of IsTruncated is true. - // To get more values, submit another request and include the values of NextContinentCode, - // NextCountryCode, and NextSubdivisionCode in the StartContinentCode, StartCountryCode, - // and StartSubdivisionCode, as applicable. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for MaxItems in the request. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, you can make a follow-up request to display more - // locations. Enter the value of NextContinentCode in the StartContinentCode - // parameter in another ListGeoLocations request. - NextContinentCode *string `min:"2" type:"string"` - - // If IsTruncated is true, you can make a follow-up request to display more - // locations. Enter the value of NextCountryCode in the StartCountryCode parameter - // in another ListGeoLocations request. - NextCountryCode *string `min:"1" type:"string"` - - // If IsTruncated is true, you can make a follow-up request to display more - // locations. Enter the value of NextSubdivisionCode in the StartSubdivisionCode - // parameter in another ListGeoLocations request. - NextSubdivisionCode *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s ListGeoLocationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListGeoLocationsOutput) GoString() string { - return s.String() -} - -// SetGeoLocationDetailsList sets the GeoLocationDetailsList field's value. -func (s *ListGeoLocationsOutput) SetGeoLocationDetailsList(v []*GeoLocationDetails) *ListGeoLocationsOutput { - s.GeoLocationDetailsList = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListGeoLocationsOutput) SetIsTruncated(v bool) *ListGeoLocationsOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListGeoLocationsOutput) SetMaxItems(v string) *ListGeoLocationsOutput { - s.MaxItems = &v - return s -} - -// SetNextContinentCode sets the NextContinentCode field's value. -func (s *ListGeoLocationsOutput) SetNextContinentCode(v string) *ListGeoLocationsOutput { - s.NextContinentCode = &v - return s -} - -// SetNextCountryCode sets the NextCountryCode field's value. -func (s *ListGeoLocationsOutput) SetNextCountryCode(v string) *ListGeoLocationsOutput { - s.NextCountryCode = &v - return s -} - -// SetNextSubdivisionCode sets the NextSubdivisionCode field's value. -func (s *ListGeoLocationsOutput) SetNextSubdivisionCode(v string) *ListGeoLocationsOutput { - s.NextSubdivisionCode = &v - return s -} - -// A request to retrieve a list of the health checks that are associated with -// the current AWS account. -type ListHealthChecksInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // health checks. To get another group, submit another ListHealthChecks request. - // - // For the value of marker, specify the value of NextMarker from the previous - // response, which is the ID of the first health check that Amazon Route 53 - // will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more health checks to get. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // The maximum number of health checks that you want ListHealthChecks to return - // in response to the current request. Amazon Route 53 returns a maximum of - // 100 items. If you set MaxItems to a value greater than 100, Amazon Route - // 53 returns only the first 100 health checks. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListHealthChecksInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHealthChecksInput) GoString() string { - return s.String() -} - -// SetMarker sets the Marker field's value. -func (s *ListHealthChecksInput) SetMarker(v string) *ListHealthChecksInput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHealthChecksInput) SetMaxItems(v string) *ListHealthChecksInput { - s.MaxItems = &v - return s -} - -// A complex type that contains the response to a ListHealthChecks request. -type ListHealthChecksOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains one HealthCheck element for each health check - // that is associated with the current AWS account. - // - // HealthChecks is a required field - HealthChecks []*HealthCheck `locationNameList:"HealthCheck" type:"list" required:"true"` - - // A flag that indicates whether there are more health checks to be listed. - // If the response was truncated, you can get the next group of health checks - // by submitting another ListHealthChecks request and specifying the value of - // NextMarker in the marker parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // For the second and subsequent calls to ListHealthChecks, Marker is the value - // that you specified for the marker parameter in the previous request. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListHealthChecks - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextMarker identifies the first health - // check that Amazon Route 53 returns if you submit another ListHealthChecks - // request and specify the value of NextMarker in the marker parameter. - NextMarker *string `type:"string"` -} - -// String returns the string representation -func (s ListHealthChecksOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHealthChecksOutput) GoString() string { - return s.String() -} - -// SetHealthChecks sets the HealthChecks field's value. -func (s *ListHealthChecksOutput) SetHealthChecks(v []*HealthCheck) *ListHealthChecksOutput { - s.HealthChecks = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListHealthChecksOutput) SetIsTruncated(v bool) *ListHealthChecksOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListHealthChecksOutput) SetMarker(v string) *ListHealthChecksOutput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHealthChecksOutput) SetMaxItems(v string) *ListHealthChecksOutput { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListHealthChecksOutput) SetNextMarker(v string) *ListHealthChecksOutput { - s.NextMarker = &v - return s -} - -// Retrieves a list of the public and private hosted zones that are associated -// with the current AWS account in ASCII order by domain name. -type ListHostedZonesByNameInput struct { - _ struct{} `type:"structure"` - - // (Optional) For your first request to ListHostedZonesByName, include the dnsname - // parameter only if you want to specify the name of the first hosted zone in - // the response. If you don't include the dnsname parameter, Amazon Route 53 - // returns all of the hosted zones that were created by the current AWS account, - // in ASCII order. For subsequent requests, include both dnsname and hostedzoneid - // parameters. For dnsname, specify the value of NextDNSName from the previous - // response. - DNSName *string `location:"querystring" locationName:"dnsname" type:"string"` - - // (Optional) For your first request to ListHostedZonesByName, do not include - // the hostedzoneid parameter. - // - // If you have more hosted zones than the value of maxitems, ListHostedZonesByName - // returns only the first maxitems hosted zones. To get the next group of maxitems - // hosted zones, submit another request to ListHostedZonesByName and include - // both dnsname and hostedzoneid parameters. For the value of hostedzoneid, - // specify the value of the NextHostedZoneId element from the previous response. - HostedZoneId *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // The maximum number of hosted zones to be included in the response body for - // this request. If you have more than maxitems hosted zones, then the value - // of the IsTruncated element in the response is true, and the values of NextDNSName - // and NextHostedZoneId specify the first hosted zone in the next group of maxitems - // hosted zones. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesByNameInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesByNameInput) GoString() string { - return s.String() -} - -// SetDNSName sets the DNSName field's value. -func (s *ListHostedZonesByNameInput) SetDNSName(v string) *ListHostedZonesByNameInput { - s.DNSName = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListHostedZonesByNameInput) SetHostedZoneId(v string) *ListHostedZonesByNameInput { - s.HostedZoneId = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesByNameInput) SetMaxItems(v string) *ListHostedZonesByNameInput { - s.MaxItems = &v - return s -} - -// A complex type that contains the response information for the request. -type ListHostedZonesByNameOutput struct { - _ struct{} `type:"structure"` - - // For the second and subsequent calls to ListHostedZonesByName, DNSName is - // the value that you specified for the dnsname parameter in the request that - // produced the current response. - DNSName *string `type:"string"` - - // The ID that Amazon Route 53 assigned to the hosted zone when you created - // it. - HostedZoneId *string `type:"string"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZones is a required field - HostedZones []*HostedZone `locationNameList:"HostedZone" type:"list" required:"true"` - - // A flag that indicates whether there are more hosted zones to be listed. If - // the response was truncated, you can get the next group of maxitems hosted - // zones by calling ListHostedZonesByName again and specifying the values of - // NextDNSName and NextHostedZoneId elements in the dnsname and hostedzoneid - // parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListHostedZonesByName - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextDNSName is the name of the first - // hosted zone in the next group of maxitems hosted zones. Call ListHostedZonesByName - // again and specify the value of NextDNSName and NextHostedZoneId in the dnsname - // and hostedzoneid parameters, respectively. - // - // This element is present only if IsTruncated is true. - NextDNSName *string `type:"string"` - - // If IsTruncated is true, the value of NextHostedZoneId identifies the first - // hosted zone in the next group of maxitems hosted zones. Call ListHostedZonesByName - // again and specify the value of NextDNSName and NextHostedZoneId in the dnsname - // and hostedzoneid parameters, respectively. - // - // This element is present only if IsTruncated is true. - NextHostedZoneId *string `type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesByNameOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesByNameOutput) GoString() string { - return s.String() -} - -// SetDNSName sets the DNSName field's value. -func (s *ListHostedZonesByNameOutput) SetDNSName(v string) *ListHostedZonesByNameOutput { - s.DNSName = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListHostedZonesByNameOutput) SetHostedZoneId(v string) *ListHostedZonesByNameOutput { - s.HostedZoneId = &v - return s -} - -// SetHostedZones sets the HostedZones field's value. -func (s *ListHostedZonesByNameOutput) SetHostedZones(v []*HostedZone) *ListHostedZonesByNameOutput { - s.HostedZones = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListHostedZonesByNameOutput) SetIsTruncated(v bool) *ListHostedZonesByNameOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesByNameOutput) SetMaxItems(v string) *ListHostedZonesByNameOutput { - s.MaxItems = &v - return s -} - -// SetNextDNSName sets the NextDNSName field's value. -func (s *ListHostedZonesByNameOutput) SetNextDNSName(v string) *ListHostedZonesByNameOutput { - s.NextDNSName = &v - return s -} - -// SetNextHostedZoneId sets the NextHostedZoneId field's value. -func (s *ListHostedZonesByNameOutput) SetNextHostedZoneId(v string) *ListHostedZonesByNameOutput { - s.NextHostedZoneId = &v - return s -} - -// A request to retrieve a list of the public and private hosted zones that -// are associated with the current AWS account. -type ListHostedZonesInput struct { - _ struct{} `type:"structure"` - - // If you're using reusable delegation sets and you want to list all of the - // hosted zones that are associated with a reusable delegation set, specify - // the ID of that reusable delegation set. - DelegationSetId *string `location:"querystring" locationName:"delegationsetid" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // hosted zones. To get more hosted zones, submit another ListHostedZones request. - // - // For the value of marker, specify the value of NextMarker from the previous - // response, which is the ID of the first hosted zone that Amazon Route 53 will - // return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more hosted zones to get. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // (Optional) The maximum number of hosted zones that you want Amazon Route - // 53 to return. If you have more than maxitems hosted zones, the value of IsTruncated - // in the response is true, and the value of NextMarker is the hosted zone ID - // of the first hosted zone that Amazon Route 53 will return if you submit another - // request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesInput) GoString() string { - return s.String() -} - -// SetDelegationSetId sets the DelegationSetId field's value. -func (s *ListHostedZonesInput) SetDelegationSetId(v string) *ListHostedZonesInput { - s.DelegationSetId = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListHostedZonesInput) SetMarker(v string) *ListHostedZonesInput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesInput) SetMaxItems(v string) *ListHostedZonesInput { - s.MaxItems = &v - return s -} - -type ListHostedZonesOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZones is a required field - HostedZones []*HostedZone `locationNameList:"HostedZone" type:"list" required:"true"` - - // A flag indicating whether there are more hosted zones to be listed. If the - // response was truncated, you can get more hosted zones by submitting another - // ListHostedZones request and specifying the value of NextMarker in the marker - // parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // For the second and subsequent calls to ListHostedZones, Marker is the value - // that you specified for the marker parameter in the request that produced - // the current response. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListHostedZones - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextMarker identifies the first hosted - // zone in the next group of hosted zones. Submit another ListHostedZones request, - // and specify the value of NextMarker from the response in the marker parameter. - // - // This element is present only if IsTruncated is true. - NextMarker *string `type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesOutput) GoString() string { - return s.String() -} - -// SetHostedZones sets the HostedZones field's value. -func (s *ListHostedZonesOutput) SetHostedZones(v []*HostedZone) *ListHostedZonesOutput { - s.HostedZones = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListHostedZonesOutput) SetIsTruncated(v bool) *ListHostedZonesOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListHostedZonesOutput) SetMarker(v string) *ListHostedZonesOutput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesOutput) SetMaxItems(v string) *ListHostedZonesOutput { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListHostedZonesOutput) SetNextMarker(v string) *ListHostedZonesOutput { - s.NextMarker = &v - return s -} - -type ListQueryLoggingConfigsInput struct { - _ struct{} `type:"structure"` - - // (Optional) If you want to list the query logging configuration that is associated - // with a hosted zone, specify the ID in HostedZoneId. - // - // If you don't specify a hosted zone ID, ListQueryLoggingConfigs returns all - // of the configurations that are associated with the current AWS account. - HostedZoneId *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // (Optional) The maximum number of query logging configurations that you want - // Amazon Route 53 to return in response to the current request. If the current - // AWS account has more than MaxResults configurations, use the value of ListQueryLoggingConfigsResponse$NextToken - // in the response to get the next page of results. - // - // If you don't specify a value for MaxResults, Amazon Route 53 returns up to - // 100 configurations. - MaxResults *string `location:"querystring" locationName:"maxresults" type:"string"` - - // (Optional) If the current AWS account has more than MaxResults query logging - // configurations, use NextToken to get the second and subsequent pages of results. - // - // For the first ListQueryLoggingConfigs request, omit this value. - // - // For the second and subsequent requests, get the value of NextToken from the - // previous response and specify that value for NextToken in the request. - NextToken *string `location:"querystring" locationName:"nexttoken" type:"string"` -} - -// String returns the string representation -func (s ListQueryLoggingConfigsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListQueryLoggingConfigsInput) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListQueryLoggingConfigsInput) SetHostedZoneId(v string) *ListQueryLoggingConfigsInput { - s.HostedZoneId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListQueryLoggingConfigsInput) SetMaxResults(v string) *ListQueryLoggingConfigsInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListQueryLoggingConfigsInput) SetNextToken(v string) *ListQueryLoggingConfigsInput { - s.NextToken = &v - return s -} - -type ListQueryLoggingConfigsOutput struct { - _ struct{} `type:"structure"` - - // If a response includes the last of the query logging configurations that - // are associated with the current AWS account, NextToken doesn't appear in - // the response. - // - // If a response doesn't include the last of the configurations, you can get - // more configurations by submitting another ListQueryLoggingConfigs request. - // Get the value of NextToken that Amazon Route 53 returned in the previous - // response and include it in NextToken in the next request. - NextToken *string `type:"string"` - - // An array that contains one QueryLoggingConfig element for each configuration - // for DNS query logging that is associated with the current AWS account. - // - // QueryLoggingConfigs is a required field - QueryLoggingConfigs []*QueryLoggingConfig `locationNameList:"QueryLoggingConfig" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListQueryLoggingConfigsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListQueryLoggingConfigsOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *ListQueryLoggingConfigsOutput) SetNextToken(v string) *ListQueryLoggingConfigsOutput { - s.NextToken = &v - return s -} - -// SetQueryLoggingConfigs sets the QueryLoggingConfigs field's value. -func (s *ListQueryLoggingConfigsOutput) SetQueryLoggingConfigs(v []*QueryLoggingConfig) *ListQueryLoggingConfigsOutput { - s.QueryLoggingConfigs = v - return s -} - -// A request for the resource record sets that are associated with a specified -// hosted zone. -type ListResourceRecordSetsInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that contains the resource record sets that you - // want to list. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // (Optional) The maximum number of resource records sets to include in the - // response body for this request. If the response includes more than maxitems - // resource record sets, the value of the IsTruncated element in the response - // is true, and the values of the NextRecordName and NextRecordType elements - // in the response identify the first resource record set in the next group - // of maxitems resource record sets. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // Weighted resource record sets only: If results were truncated for a given - // DNS name and type, specify the value of NextRecordIdentifier from the previous - // response to get the next resource record set that has the current DNS name - // and type. - StartRecordIdentifier *string `location:"querystring" locationName:"identifier" min:"1" type:"string"` - - // The first name in the lexicographic ordering of resource record sets that - // you want to list. - StartRecordName *string `location:"querystring" locationName:"name" type:"string"` - - // The type of resource record set to begin the record listing from. - // - // Valid values for basic resource record sets: A | AAAA | CAA | CNAME | MX - // | NAPTR | NS | PTR | SOA | SPF | SRV | TXT - // - // Values for weighted, latency, geo, and failover resource record sets: A | - // AAAA | CAA | CNAME | MX | NAPTR | PTR | SPF | SRV | TXT - // - // Values for alias resource record sets: - // - // * CloudFront distribution: A or AAAA - // - // * Elastic Beanstalk environment that has a regionalized subdomain: A - // - // * ELB load balancer: A | AAAA - // - // * Amazon S3 bucket: A - // - // * Another resource record set in this hosted zone: The type of the resource - // record set that the alias references. - // - // Constraint: Specifying type without specifying name returns an InvalidInput - // error. - StartRecordType *string `location:"querystring" locationName:"type" type:"string" enum:"RRType"` -} - -// String returns the string representation -func (s ListResourceRecordSetsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListResourceRecordSetsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListResourceRecordSetsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListResourceRecordSetsInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.StartRecordIdentifier != nil && len(*s.StartRecordIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("StartRecordIdentifier", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListResourceRecordSetsInput) SetHostedZoneId(v string) *ListResourceRecordSetsInput { - s.HostedZoneId = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListResourceRecordSetsInput) SetMaxItems(v string) *ListResourceRecordSetsInput { - s.MaxItems = &v - return s -} - -// SetStartRecordIdentifier sets the StartRecordIdentifier field's value. -func (s *ListResourceRecordSetsInput) SetStartRecordIdentifier(v string) *ListResourceRecordSetsInput { - s.StartRecordIdentifier = &v - return s -} - -// SetStartRecordName sets the StartRecordName field's value. -func (s *ListResourceRecordSetsInput) SetStartRecordName(v string) *ListResourceRecordSetsInput { - s.StartRecordName = &v - return s -} - -// SetStartRecordType sets the StartRecordType field's value. -func (s *ListResourceRecordSetsInput) SetStartRecordType(v string) *ListResourceRecordSetsInput { - s.StartRecordType = &v - return s -} - -// A complex type that contains list information for the resource record set. -type ListResourceRecordSetsOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether more resource record sets remain to be listed. - // If your results were truncated, you can make a follow-up pagination request - // by using the NextRecordName element. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The maximum number of records you requested. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // Weighted, latency, geolocation, and failover resource record sets only: If - // results were truncated for a given DNS name and type, the value of SetIdentifier - // for the next resource record set that has the current DNS name and type. - NextRecordIdentifier *string `min:"1" type:"string"` - - // If the results were truncated, the name of the next record in the list. - // - // This element is present only if IsTruncated is true. - NextRecordName *string `type:"string"` - - // If the results were truncated, the type of the next record in the list. - // - // This element is present only if IsTruncated is true. - NextRecordType *string `type:"string" enum:"RRType"` - - // Information about multiple resource record sets. - // - // ResourceRecordSets is a required field - ResourceRecordSets []*ResourceRecordSet `locationNameList:"ResourceRecordSet" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListResourceRecordSetsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListResourceRecordSetsOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListResourceRecordSetsOutput) SetIsTruncated(v bool) *ListResourceRecordSetsOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListResourceRecordSetsOutput) SetMaxItems(v string) *ListResourceRecordSetsOutput { - s.MaxItems = &v - return s -} - -// SetNextRecordIdentifier sets the NextRecordIdentifier field's value. -func (s *ListResourceRecordSetsOutput) SetNextRecordIdentifier(v string) *ListResourceRecordSetsOutput { - s.NextRecordIdentifier = &v - return s -} - -// SetNextRecordName sets the NextRecordName field's value. -func (s *ListResourceRecordSetsOutput) SetNextRecordName(v string) *ListResourceRecordSetsOutput { - s.NextRecordName = &v - return s -} - -// SetNextRecordType sets the NextRecordType field's value. -func (s *ListResourceRecordSetsOutput) SetNextRecordType(v string) *ListResourceRecordSetsOutput { - s.NextRecordType = &v - return s -} - -// SetResourceRecordSets sets the ResourceRecordSets field's value. -func (s *ListResourceRecordSetsOutput) SetResourceRecordSets(v []*ResourceRecordSet) *ListResourceRecordSetsOutput { - s.ResourceRecordSets = v - return s -} - -// A request to get a list of the reusable delegation sets that are associated -// with the current AWS account. -type ListReusableDelegationSetsInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // reusable delegation sets. To get another group, submit another ListReusableDelegationSets - // request. - // - // For the value of marker, specify the value of NextMarker from the previous - // response, which is the ID of the first reusable delegation set that Amazon - // Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more reusable delegation sets to get. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // The number of reusable delegation sets that you want Amazon Route 53 to return - // in the response to this request. If you specify a value greater than 100, - // Amazon Route 53 returns only the first 100 reusable delegation sets. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListReusableDelegationSetsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListReusableDelegationSetsInput) GoString() string { - return s.String() -} - -// SetMarker sets the Marker field's value. -func (s *ListReusableDelegationSetsInput) SetMarker(v string) *ListReusableDelegationSetsInput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListReusableDelegationSetsInput) SetMaxItems(v string) *ListReusableDelegationSetsInput { - s.MaxItems = &v - return s -} - -// A complex type that contains information about the reusable delegation sets -// that are associated with the current AWS account. -type ListReusableDelegationSetsOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains one DelegationSet element for each reusable - // delegation set that was created by the current AWS account. - // - // DelegationSets is a required field - DelegationSets []*DelegationSet `locationNameList:"DelegationSet" type:"list" required:"true"` - - // A flag that indicates whether there are more reusable delegation sets to - // be listed. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // For the second and subsequent calls to ListReusableDelegationSets, Marker - // is the value that you specified for the marker parameter in the request that - // produced the current response. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListReusableDelegationSets - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextMarker identifies the next reusable - // delegation set that Amazon Route 53 will return if you submit another ListReusableDelegationSets - // request and specify the value of NextMarker in the marker parameter. - NextMarker *string `type:"string"` -} - -// String returns the string representation -func (s ListReusableDelegationSetsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListReusableDelegationSetsOutput) GoString() string { - return s.String() -} - -// SetDelegationSets sets the DelegationSets field's value. -func (s *ListReusableDelegationSetsOutput) SetDelegationSets(v []*DelegationSet) *ListReusableDelegationSetsOutput { - s.DelegationSets = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListReusableDelegationSetsOutput) SetIsTruncated(v bool) *ListReusableDelegationSetsOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListReusableDelegationSetsOutput) SetMarker(v string) *ListReusableDelegationSetsOutput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListReusableDelegationSetsOutput) SetMaxItems(v string) *ListReusableDelegationSetsOutput { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListReusableDelegationSetsOutput) SetNextMarker(v string) *ListReusableDelegationSetsOutput { - s.NextMarker = &v - return s -} - -// A complex type containing information about a request for a list of the tags -// that are associated with an individual resource. -type ListTagsForResourceInput struct { - _ struct{} `type:"structure"` - - // The ID of the resource for which you want to retrieve tags. - // - // ResourceId is a required field - ResourceId *string `location:"uri" locationName:"ResourceId" type:"string" required:"true"` - - // The type of the resource. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - // - // ResourceType is a required field - ResourceType *string `location:"uri" locationName:"ResourceType" type:"string" required:"true" enum:"TagResourceType"` -} - -// String returns the string representation -func (s ListTagsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} - if s.ResourceId == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceId")) - } - if s.ResourceType == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceId sets the ResourceId field's value. -func (s *ListTagsForResourceInput) SetResourceId(v string) *ListTagsForResourceInput { - s.ResourceId = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ListTagsForResourceInput) SetResourceType(v string) *ListTagsForResourceInput { - s.ResourceType = &v - return s -} - -// A complex type that contains information about the health checks or hosted -// zones for which you want to list tags. -type ListTagsForResourceOutput struct { - _ struct{} `type:"structure"` - - // A ResourceTagSet containing tags associated with the specified resource. - // - // ResourceTagSet is a required field - ResourceTagSet *ResourceTagSet `type:"structure" required:"true"` -} - -// String returns the string representation -func (s ListTagsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourceOutput) GoString() string { - return s.String() -} - -// SetResourceTagSet sets the ResourceTagSet field's value. -func (s *ListTagsForResourceOutput) SetResourceTagSet(v *ResourceTagSet) *ListTagsForResourceOutput { - s.ResourceTagSet = v - return s -} - -// A complex type that contains information about the health checks or hosted -// zones for which you want to list tags. -type ListTagsForResourcesInput struct { - _ struct{} `locationName:"ListTagsForResourcesRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that contains the ResourceId element for each resource for - // which you want to get a list of tags. - // - // ResourceIds is a required field - ResourceIds []*string `locationNameList:"ResourceId" min:"1" type:"list" required:"true"` - - // The type of the resources. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - // - // ResourceType is a required field - ResourceType *string `location:"uri" locationName:"ResourceType" type:"string" required:"true" enum:"TagResourceType"` -} - -// String returns the string representation -func (s ListTagsForResourcesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourcesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourcesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourcesInput"} - if s.ResourceIds == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceIds")) - } - if s.ResourceIds != nil && len(s.ResourceIds) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceIds", 1)) - } - if s.ResourceType == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceIds sets the ResourceIds field's value. -func (s *ListTagsForResourcesInput) SetResourceIds(v []*string) *ListTagsForResourcesInput { - s.ResourceIds = v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ListTagsForResourcesInput) SetResourceType(v string) *ListTagsForResourcesInput { - s.ResourceType = &v - return s -} - -// A complex type containing tags for the specified resources. -type ListTagsForResourcesOutput struct { - _ struct{} `type:"structure"` - - // A list of ResourceTagSets containing tags associated with the specified resources. - // - // ResourceTagSets is a required field - ResourceTagSets []*ResourceTagSet `locationNameList:"ResourceTagSet" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTagsForResourcesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourcesOutput) GoString() string { - return s.String() -} - -// SetResourceTagSets sets the ResourceTagSets field's value. -func (s *ListTagsForResourcesOutput) SetResourceTagSets(v []*ResourceTagSet) *ListTagsForResourcesOutput { - s.ResourceTagSets = v - return s -} - -// A complex type that contains the information about the request to list the -// traffic policies that are associated with the current AWS account. -type ListTrafficPoliciesInput struct { - _ struct{} `type:"structure"` - - // (Optional) The maximum number of traffic policies that you want Amazon Route - // 53 to return in response to this request. If you have more than MaxItems - // traffic policies, the value of IsTruncated in the response is true, and the - // value of TrafficPolicyIdMarker is the ID of the first traffic policy that - // Amazon Route 53 will return if you submit another request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // (Conditional) For your first request to ListTrafficPolicies, don't include - // the TrafficPolicyIdMarker parameter. - // - // If you have more traffic policies than the value of MaxItems, ListTrafficPolicies - // returns only the first MaxItems traffic policies. To get the next group of - // policies, submit another request to ListTrafficPolicies. For the value of - // TrafficPolicyIdMarker, specify the value of TrafficPolicyIdMarker that was - // returned in the previous response. - TrafficPolicyIdMarker *string `location:"querystring" locationName:"trafficpolicyid" min:"1" type:"string"` -} - -// String returns the string representation -func (s ListTrafficPoliciesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPoliciesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPoliciesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPoliciesInput"} - if s.TrafficPolicyIdMarker != nil && len(*s.TrafficPolicyIdMarker) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyIdMarker", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPoliciesInput) SetMaxItems(v string) *ListTrafficPoliciesInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyIdMarker sets the TrafficPolicyIdMarker field's value. -func (s *ListTrafficPoliciesInput) SetTrafficPolicyIdMarker(v string) *ListTrafficPoliciesInput { - s.TrafficPolicyIdMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPoliciesOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether there are more traffic policies to be listed. - // If the response was truncated, you can get the next group of traffic policies - // by submitting another ListTrafficPolicies request and specifying the value - // of TrafficPolicyIdMarker in the TrafficPolicyIdMarker request parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the ListTrafficPolicies - // request that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If the value of IsTruncated is true, TrafficPolicyIdMarker is the ID of the - // first traffic policy in the next group of MaxItems traffic policies. - // - // TrafficPolicyIdMarker is a required field - TrafficPolicyIdMarker *string `min:"1" type:"string" required:"true"` - - // A list that contains one TrafficPolicySummary element for each traffic policy - // that was created by the current AWS account. - // - // TrafficPolicySummaries is a required field - TrafficPolicySummaries []*TrafficPolicySummary `locationNameList:"TrafficPolicySummary" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPoliciesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPoliciesOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPoliciesOutput) SetIsTruncated(v bool) *ListTrafficPoliciesOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPoliciesOutput) SetMaxItems(v string) *ListTrafficPoliciesOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyIdMarker sets the TrafficPolicyIdMarker field's value. -func (s *ListTrafficPoliciesOutput) SetTrafficPolicyIdMarker(v string) *ListTrafficPoliciesOutput { - s.TrafficPolicyIdMarker = &v - return s -} - -// SetTrafficPolicySummaries sets the TrafficPolicySummaries field's value. -func (s *ListTrafficPoliciesOutput) SetTrafficPolicySummaries(v []*TrafficPolicySummary) *ListTrafficPoliciesOutput { - s.TrafficPolicySummaries = v - return s -} - -// A request for the traffic policy instances that you created in a specified -// hosted zone. -type ListTrafficPolicyInstancesByHostedZoneInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you want to list traffic policy instances - // for. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"querystring" locationName:"id" type:"string" required:"true"` - - // The maximum number of traffic policy instances to be included in the response - // body for this request. If you have more than MaxItems traffic policy instances, - // the value of the IsTruncated element in the response is true, and the values - // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance that Amazon Route 53 will return - // if you submit another request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // If the value of IsTruncated in the previous response is true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancename, - // specify the value of TrafficPolicyInstanceNameMarker from the previous response, - // which is the name of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - - // If the value of IsTruncated in the previous response is true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancetype, - // specify the value of TrafficPolicyInstanceTypeMarker from the previous response, - // which is the type of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPolicyInstancesByHostedZoneInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetHostedZoneId(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.HostedZoneId = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetMaxItems(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyInstancesByHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of traffic - // policy instances by submitting another ListTrafficPolicyInstancesByHostedZone - // request and specifying the values of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker in the corresponding request parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the ListTrafficPolicyInstancesByHostedZone - // request that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance in the next group of traffic policy instances. - TrafficPolicyInstanceNameMarker *string `type:"string"` - - // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of - // the resource record sets that are associated with the first traffic policy - // instance in the next group of traffic policy instances. - TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` - - // A list that contains one TrafficPolicyInstance element for each traffic policy - // instance that matches the elements in the request. - // - // TrafficPolicyInstances is a required field - TrafficPolicyInstances []*TrafficPolicyInstance `locationNameList:"TrafficPolicyInstance" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetIsTruncated(v bool) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetMaxItems(v string) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyInstances sets the TrafficPolicyInstances field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstances(v []*TrafficPolicyInstance) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.TrafficPolicyInstances = v - return s -} - -// A complex type that contains the information about the request to list your -// traffic policy instances. -type ListTrafficPolicyInstancesByPolicyInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstancesByPolicy request. - // - // For the value of hostedzoneid, specify the value of HostedZoneIdMarker from - // the previous response, which is the hosted zone ID of the first traffic policy - // instance that Amazon Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - HostedZoneIdMarker *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // The maximum number of traffic policy instances to be included in the response - // body for this request. If you have more than MaxItems traffic policy instances, - // the value of the IsTruncated element in the response is true, and the values - // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance that Amazon Route 53 will return - // if you submit another request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // The ID of the traffic policy for which you want to list traffic policy instances. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `location:"querystring" locationName:"id" min:"1" type:"string" required:"true"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstancesByPolicy request. - // - // For the value of trafficpolicyinstancename, specify the value of TrafficPolicyInstanceNameMarker - // from the previous response, which is the name of the first traffic policy - // instance that Amazon Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstancesByPolicy request. - // - // For the value of trafficpolicyinstancetype, specify the value of TrafficPolicyInstanceTypeMarker - // from the previous response, which is the name of the first traffic policy - // instance that Amazon Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` - - // The version of the traffic policy for which you want to list traffic policy - // instances. The version must be associated with the traffic policy that is - // specified by TrafficPolicyId. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `location:"querystring" locationName:"version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPolicyInstancesByPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPolicyInstancesByPolicyInput"} - if s.TrafficPolicyId == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyId")) - } - if s.TrafficPolicyId != nil && len(*s.TrafficPolicyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyId", 1)) - } - if s.TrafficPolicyVersion == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyVersion")) - } - if s.TrafficPolicyVersion != nil && *s.TrafficPolicyVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("TrafficPolicyVersion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.HostedZoneIdMarker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetMaxItems(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyId(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyVersion(v int64) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyInstancesByPolicyOutput struct { - _ struct{} `type:"structure"` - - // If IsTruncated is true, HostedZoneIdMarker is the ID of the hosted zone of - // the first traffic policy instance in the next group of traffic policy instances. - HostedZoneIdMarker *string `type:"string"` - - // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of traffic - // policy instances by calling ListTrafficPolicyInstancesByPolicy again and - // specifying the values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker elements in the corresponding request - // parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the call to ListTrafficPolicyInstancesByPolicy - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance in the next group of MaxItems traffic policy - // instances. - TrafficPolicyInstanceNameMarker *string `type:"string"` - - // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of - // the resource record sets that are associated with the first traffic policy - // instance in the next group of MaxItems traffic policy instances. - TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` - - // A list that contains one TrafficPolicyInstance element for each traffic policy - // instance that matches the elements in the request. - // - // TrafficPolicyInstances is a required field - TrafficPolicyInstances []*TrafficPolicyInstance `locationNameList:"TrafficPolicyInstance" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByPolicyOutput) GoString() string { - return s.String() -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.HostedZoneIdMarker = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetIsTruncated(v bool) *ListTrafficPolicyInstancesByPolicyOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetMaxItems(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyInstances sets the TrafficPolicyInstances field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstances(v []*TrafficPolicyInstance) *ListTrafficPolicyInstancesByPolicyOutput { - s.TrafficPolicyInstances = v - return s -} - -// A request to get information about the traffic policy instances that you -// created by using the current AWS account. -type ListTrafficPolicyInstancesInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of HostedZoneId, specify - // the value of HostedZoneIdMarker from the previous response, which is the - // hosted zone ID of the first traffic policy instance in the next group of - // traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - HostedZoneIdMarker *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // The maximum number of traffic policy instances that you want Amazon Route - // 53 to return in response to a ListTrafficPolicyInstances request. If you - // have more than MaxItems traffic policy instances, the value of the IsTruncated - // element in the response is true, and the values of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker represent the first traffic policy instance - // in the next group of MaxItems traffic policy instances. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancename, - // specify the value of TrafficPolicyInstanceNameMarker from the previous response, - // which is the name of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancetype, - // specify the value of TrafficPolicyInstanceTypeMarker from the previous response, - // which is the type of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesInput) GoString() string { - return s.String() -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesInput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesInput { - s.HostedZoneIdMarker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesInput) SetMaxItems(v string) *ListTrafficPolicyInstancesInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesInput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesInput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesInput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesInput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyInstancesOutput struct { - _ struct{} `type:"structure"` - - // If IsTruncated is true, HostedZoneIdMarker is the ID of the hosted zone of - // the first traffic policy instance that Amazon Route 53 will return if you - // submit another ListTrafficPolicyInstances request. - HostedZoneIdMarker *string `type:"string"` - - // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get more traffic policy - // instances by calling ListTrafficPolicyInstances again and specifying the - // values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // in the corresponding request parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the call to ListTrafficPolicyInstances - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance that Amazon Route 53 will return if you submit - // another ListTrafficPolicyInstances request. - TrafficPolicyInstanceNameMarker *string `type:"string"` - - // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of - // the resource record sets that are associated with the first traffic policy - // instance that Amazon Route 53 will return if you submit another ListTrafficPolicyInstances - // request. - TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` - - // A list that contains one TrafficPolicyInstance element for each traffic policy - // instance that matches the elements in the request. - // - // TrafficPolicyInstances is a required field - TrafficPolicyInstances []*TrafficPolicyInstance `locationNameList:"TrafficPolicyInstance" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesOutput) GoString() string { - return s.String() -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesOutput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesOutput { - s.HostedZoneIdMarker = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyInstancesOutput) SetIsTruncated(v bool) *ListTrafficPolicyInstancesOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesOutput) SetMaxItems(v string) *ListTrafficPolicyInstancesOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesOutput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesOutput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesOutput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesOutput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyInstances sets the TrafficPolicyInstances field's value. -func (s *ListTrafficPolicyInstancesOutput) SetTrafficPolicyInstances(v []*TrafficPolicyInstance) *ListTrafficPolicyInstancesOutput { - s.TrafficPolicyInstances = v - return s -} - -// A complex type that contains the information about the request to list your -// traffic policies. -type ListTrafficPolicyVersionsInput struct { - _ struct{} `type:"structure"` - - // Specify the value of Id of the traffic policy for which you want to list - // all versions. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The maximum number of traffic policy versions that you want Amazon Route - // 53 to include in the response body for this request. If the specified traffic - // policy has more than MaxItems versions, the value of IsTruncated in the response - // is true, and the value of the TrafficPolicyVersionMarker element is the ID - // of the first version that Amazon Route 53 will return if you submit another - // request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // For your first request to ListTrafficPolicyVersions, don't include the TrafficPolicyVersionMarker - // parameter. - // - // If you have more traffic policy versions than the value of MaxItems, ListTrafficPolicyVersions - // returns only the first group of MaxItems versions. To get more traffic policy - // versions, submit another ListTrafficPolicyVersions request. For the value - // of TrafficPolicyVersionMarker, specify the value of TrafficPolicyVersionMarker - // in the previous response. - TrafficPolicyVersionMarker *string `location:"querystring" locationName:"trafficpolicyversion" type:"string"` -} - -// String returns the string representation -func (s ListTrafficPolicyVersionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyVersionsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPolicyVersionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPolicyVersionsInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *ListTrafficPolicyVersionsInput) SetId(v string) *ListTrafficPolicyVersionsInput { - s.Id = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyVersionsInput) SetMaxItems(v string) *ListTrafficPolicyVersionsInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyVersionMarker sets the TrafficPolicyVersionMarker field's value. -func (s *ListTrafficPolicyVersionsInput) SetTrafficPolicyVersionMarker(v string) *ListTrafficPolicyVersionsInput { - s.TrafficPolicyVersionMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyVersionsOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether there are more traffic policies to be listed. - // If the response was truncated, you can get the next group of traffic policies - // by submitting another ListTrafficPolicyVersions request and specifying the - // value of NextMarker in the marker parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the maxitems parameter in the ListTrafficPolicyVersions - // request that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // A list that contains one TrafficPolicy element for each traffic policy version - // that is associated with the specified traffic policy. - // - // TrafficPolicies is a required field - TrafficPolicies []*TrafficPolicy `locationNameList:"TrafficPolicy" type:"list" required:"true"` - - // If IsTruncated is true, the value of TrafficPolicyVersionMarker identifies - // the first traffic policy that Amazon Route 53 will return if you submit another - // request. Call ListTrafficPolicyVersions again and specify the value of TrafficPolicyVersionMarker - // in the TrafficPolicyVersionMarker request parameter. - // - // This element is present only if IsTruncated is true. - // - // TrafficPolicyVersionMarker is a required field - TrafficPolicyVersionMarker *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyVersionsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyVersionsOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyVersionsOutput) SetIsTruncated(v bool) *ListTrafficPolicyVersionsOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyVersionsOutput) SetMaxItems(v string) *ListTrafficPolicyVersionsOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicies sets the TrafficPolicies field's value. -func (s *ListTrafficPolicyVersionsOutput) SetTrafficPolicies(v []*TrafficPolicy) *ListTrafficPolicyVersionsOutput { - s.TrafficPolicies = v - return s -} - -// SetTrafficPolicyVersionMarker sets the TrafficPolicyVersionMarker field's value. -func (s *ListTrafficPolicyVersionsOutput) SetTrafficPolicyVersionMarker(v string) *ListTrafficPolicyVersionsOutput { - s.TrafficPolicyVersionMarker = &v - return s -} - -// A complex type that contains information about that can be associated with -// your hosted zone. -type ListVPCAssociationAuthorizationsInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone for which you want a list of VPCs that can be associated - // with the hosted zone. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // Optional: An integer that specifies the maximum number of VPCs that you want - // Amazon Route 53 to return. If you don't specify a value for MaxResults, Amazon - // Route 53 returns up to 50 VPCs per page. - MaxResults *string `location:"querystring" locationName:"maxresults" type:"string"` - - // Optional: If a response includes a NextToken element, there are more VPCs - // that can be associated with the specified hosted zone. To get the next page - // of results, submit another request, and include the value of NextToken from - // the response in the nexttoken parameter in another ListVPCAssociationAuthorizations - // request. - NextToken *string `location:"querystring" locationName:"nexttoken" type:"string"` -} - -// String returns the string representation -func (s ListVPCAssociationAuthorizationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListVPCAssociationAuthorizationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListVPCAssociationAuthorizationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListVPCAssociationAuthorizationsInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListVPCAssociationAuthorizationsInput) SetHostedZoneId(v string) *ListVPCAssociationAuthorizationsInput { - s.HostedZoneId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListVPCAssociationAuthorizationsInput) SetMaxResults(v string) *ListVPCAssociationAuthorizationsInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListVPCAssociationAuthorizationsInput) SetNextToken(v string) *ListVPCAssociationAuthorizationsInput { - s.NextToken = &v - return s -} - -// A complex type that contains the response information for the request. -type ListVPCAssociationAuthorizationsOutput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you can associate the listed VPCs with. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // When the response includes a NextToken element, there are more VPCs that - // can be associated with the specified hosted zone. To get the next page of - // VPCs, submit another ListVPCAssociationAuthorizations request, and include - // the value of the NextToken element from the response in the nexttoken request - // parameter. - NextToken *string `type:"string"` - - // The list of VPCs that are authorized to be associated with the specified - // hosted zone. - // - // VPCs is a required field - VPCs []*VPC `locationNameList:"VPC" min:"1" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListVPCAssociationAuthorizationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListVPCAssociationAuthorizationsOutput) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListVPCAssociationAuthorizationsOutput) SetHostedZoneId(v string) *ListVPCAssociationAuthorizationsOutput { - s.HostedZoneId = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListVPCAssociationAuthorizationsOutput) SetNextToken(v string) *ListVPCAssociationAuthorizationsOutput { - s.NextToken = &v - return s -} - -// SetVPCs sets the VPCs field's value. -func (s *ListVPCAssociationAuthorizationsOutput) SetVPCs(v []*VPC) *ListVPCAssociationAuthorizationsOutput { - s.VPCs = v - return s -} - -// A complex type that contains information about a configuration for DNS query -// logging. -type QueryLoggingConfig struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the CloudWatch Logs log group that Amazon - // Route 53 is publishing logs to. - // - // CloudWatchLogsLogGroupArn is a required field - CloudWatchLogsLogGroupArn *string `type:"string" required:"true"` - - // The ID of the hosted zone that CloudWatch Logs is logging queries for. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The ID for a configuration for DNS query logging. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s QueryLoggingConfig) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s QueryLoggingConfig) GoString() string { - return s.String() -} - -// SetCloudWatchLogsLogGroupArn sets the CloudWatchLogsLogGroupArn field's value. -func (s *QueryLoggingConfig) SetCloudWatchLogsLogGroupArn(v string) *QueryLoggingConfig { - s.CloudWatchLogsLogGroupArn = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *QueryLoggingConfig) SetHostedZoneId(v string) *QueryLoggingConfig { - s.HostedZoneId = &v - return s -} - -// SetId sets the Id field's value. -func (s *QueryLoggingConfig) SetId(v string) *QueryLoggingConfig { - s.Id = &v - return s -} - -// Information specific to the resource record. -// -// If you're creating an alias resource record set, omit ResourceRecord. -type ResourceRecord struct { - _ struct{} `type:"structure"` - - // The current or new DNS record value, not to exceed 4,000 characters. In the - // case of a DELETE action, if the current value does not match the actual value, - // an error is returned. For descriptions about how to format Value for different - // record types, see Supported DNS Resource Record Types (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html) - // in the Amazon Route 53 Developer Guide. - // - // You can specify more than one value for all record types except CNAME and - // SOA. - // - // If you're creating an alias resource record set, omit Value. - // - // Value is a required field - Value *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s ResourceRecord) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceRecord) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ResourceRecord) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ResourceRecord"} - if s.Value == nil { - invalidParams.Add(request.NewErrParamRequired("Value")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetValue sets the Value field's value. -func (s *ResourceRecord) SetValue(v string) *ResourceRecord { - s.Value = &v - return s -} - -// Information about the resource record set to create or delete. -type ResourceRecordSet struct { - _ struct{} `type:"structure"` - - // Alias resource record sets only: Information about the CloudFront distribution, - // AWS Elastic Beanstalk environment, ELB load balancer, Amazon S3 bucket, or - // Amazon Route 53 resource record set to which you're redirecting queries. - // The AWS Elastic Beanstalk environment must have a regionalized subdomain. - // - // If you're creating resource records sets for a private hosted zone, note - // the following: - // - // * You can't create alias resource record sets for CloudFront distributions - // in a private hosted zone. - // - // * Creating geolocation alias resource record sets or latency alias resource - // record sets in a private hosted zone is unsupported. - // - // * For information about creating failover resource record sets in a private - // hosted zone, see Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - // in the Amazon Route 53 Developer Guide. - AliasTarget *AliasTarget `type:"structure"` - - // Failover resource record sets only: To configure failover, you add the Failover - // element to two resource record sets. For one resource record set, you specify - // PRIMARY as the value for Failover; for the other resource record set, you - // specify SECONDARY. In addition, you include the HealthCheckId element and - // specify the health check that you want Amazon Route 53 to perform for each - // resource record set. - // - // Except where noted, the following failover behaviors assume that you have - // included the HealthCheckId element in both resource record sets: - // - // * When the primary resource record set is healthy, Amazon Route 53 responds - // to DNS queries with the applicable value from the primary resource record - // set regardless of the health of the secondary resource record set. - // - // * When the primary resource record set is unhealthy and the secondary - // resource record set is healthy, Amazon Route 53 responds to DNS queries - // with the applicable value from the secondary resource record set. - // - // * When the secondary resource record set is unhealthy, Amazon Route 53 - // responds to DNS queries with the applicable value from the primary resource - // record set regardless of the health of the primary resource record set. - // - // * If you omit the HealthCheckId element for the secondary resource record - // set, and if the primary resource record set is unhealthy, Amazon Route - // 53 always responds to DNS queries with the applicable value from the secondary - // resource record set. This is true regardless of the health of the associated - // endpoint. - // - // You can't create non-failover resource record sets that have the same values - // for the Name and Type elements as failover resource record sets. - // - // For failover alias resource record sets, you must also include the EvaluateTargetHealth - // element and set the value to true. - // - // For more information about configuring failover for Amazon Route 53, see - // the following topics in the Amazon Route 53 Developer Guide: - // - // * Amazon Route 53 Health Checks and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) - // - // * Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - Failover *string `type:"string" enum:"ResourceRecordSetFailover"` - - // Geo location resource record sets only: A complex type that lets you control - // how Amazon Route 53 responds to DNS queries based on the geographic origin - // of the query. For example, if you want all queries from Africa to be routed - // to a web server with an IP address of 192.0.2.111, create a resource record - // set with a Type of A and a ContinentCode of AF. - // - // Creating geolocation and geolocation alias resource record sets in private - // hosted zones is not supported. - // - // If you create separate resource record sets for overlapping geographic regions - // (for example, one resource record set for a continent and one for a country - // on the same continent), priority goes to the smallest geographic region. - // This allows you to route most queries for a continent to one resource and - // to route queries for a country on that continent to a different resource. - // - // You can't create two geolocation resource record sets that specify the same - // geographic location. - // - // The value * in the CountryCode element matches all geographic locations that - // aren't specified in other geolocation resource record sets that have the - // same values for the Name and Type elements. - // - // Geolocation works by mapping IP addresses to locations. However, some IP - // addresses aren't mapped to geographic locations, so even if you create geolocation - // resource record sets that cover all seven continents, Amazon Route 53 will - // receive some DNS queries from locations that it can't identify. We recommend - // that you create a resource record set for which the value of CountryCode - // is *, which handles both queries that come from locations for which you haven't - // created geolocation resource record sets and queries from IP addresses that - // aren't mapped to a location. If you don't create a * resource record set, - // Amazon Route 53 returns a "no answer" response for queries from those locations. - // - // You can't create non-geolocation resource record sets that have the same - // values for the Name and Type elements as geolocation resource record sets. - GeoLocation *GeoLocation `type:"structure"` - - // If you want Amazon Route 53 to return this resource record set in response - // to a DNS query only when a health check is passing, include the HealthCheckId - // element and specify the ID of the applicable health check. - // - // Amazon Route 53 determines whether a resource record set is healthy based - // on one of the following: - // - // * By periodically sending a request to the endpoint that is specified - // in the health check - // - // * By aggregating the status of a specified group of health checks (calculated - // health checks) - // - // * By determining the current state of a CloudWatch alarm (CloudWatch metric - // health checks) - // - // For more information, see How Amazon Route 53 Determines Whether an Endpoint - // Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html). - // - // The HealthCheckId element is only useful when Amazon Route 53 is choosing - // between two or more resource record sets to respond to a DNS query, and you - // want Amazon Route 53 to base the choice in part on the status of a health - // check. Configuring health checks only makes sense in the following configurations: - // - // * You're checking the health of the resource record sets in a group of - // weighted, latency, geolocation, or failover resource record sets, and - // you specify health check IDs for all of the resource record sets. If the - // health check for one resource record set specifies an endpoint that is - // not healthy, Amazon Route 53 stops responding to queries using the value - // for that resource record set. - // - // * You set EvaluateTargetHealth to true for the resource record sets in - // a group of alias, weighted alias, latency alias, geolocation alias, or - // failover alias resource record sets, and you specify health check IDs - // for all of the resource record sets that are referenced by the alias resource - // record sets. - // - // Amazon Route 53 doesn't check the health of the endpoint specified in the - // resource record set, for example, the endpoint specified by the IP address - // in the Value element. When you add a HealthCheckId element to a resource - // record set, Amazon Route 53 checks the health of the endpoint that you specified - // in the health check. - // - // For geolocation resource record sets, if an endpoint is unhealthy, Amazon - // Route 53 looks for a resource record set for the larger, associated geographic - // region. For example, suppose you have resource record sets for a state in - // the United States, for the United States, for North America, and for all - // locations. If the endpoint for the state resource record set is unhealthy, - // Amazon Route 53 checks the resource record sets for the United States, for - // North America, and for all locations (a resource record set for which the - // value of CountryCode is *), in that order, until it finds a resource record - // set for which the endpoint is healthy. - // - // If your health checks specify the endpoint only by domain name, we recommend - // that you create a separate health check for each endpoint. For example, create - // a health check for each HTTP server that is serving content for www.example.com. - // For the value of FullyQualifiedDomainName, specify the domain name of the - // server (such as us-east-2-www.example.com), not the name of the resource - // record sets (example.com). - // - // n this configuration, if you create a health check for which the value of - // FullyQualifiedDomainName matches the name of the resource record sets and - // then associate the health check with those resource record sets, health check - // results will be unpredictable. - // - // For more information, see the following topics in the Amazon Route 53 Developer - // Guide: - // - // * Amazon Route 53 Health Checks and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) - // - // * Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - HealthCheckId *string `type:"string"` - - // Multivalue answer resource record sets only: To route traffic approximately - // randomly to multiple resources, such as web servers, create one multivalue - // answer record for each resource and specify true for MultiValueAnswer. Note - // the following: - // - // * If you associate a health check with a multivalue answer resource record - // set, Amazon Route 53 responds to DNS queries with the corresponding IP - // address only when the health check is healthy. - // - // * If you don't associate a health check with a multivalue answer record, - // Amazon Route 53 always considers the record to be healthy. - // - // * Amazon Route 53 responds to DNS queries with up to eight healthy records; - // if you have eight or fewer healthy records, Amazon Route 53 responds to - // all DNS queries with all the healthy records. - // - // * If you have more than eight healthy records, Amazon Route 53 responds - // to different DNS resolvers with different combinations of healthy records. - // - // * When all records are unhealthy, Amazon Route 53 responds to DNS queries - // with up to eight unhealthy records. - // - // * If a resource becomes unavailable after a resolver caches a response, - // client software typically tries another of the IP addresses in the response. - // - // You can't create multivalue answer alias records. - MultiValueAnswer *bool `type:"boolean"` - - // The name of the domain you want to perform the action on. - // - // Enter a fully qualified domain name, for example, www.example.com. You can - // optionally include a trailing dot. If you omit the trailing dot, Amazon Route - // 53 still assumes that the domain name that you specify is fully qualified. - // This means that Amazon Route 53 treats www.example.com (without a trailing - // dot) and www.example.com. (with a trailing dot) as identical. - // - // For information about how to specify characters other than a-z, 0-9, and - // - (hyphen) and how to specify internationalized domain names, see DNS Domain - // Name Format (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html) - // in the Amazon Route 53 Developer Guide. - // - // You can use the asterisk (*) wildcard to replace the leftmost label in a - // domain name, for example, *.example.com. Note the following: - // - // * The * must replace the entire label. For example, you can't specify - // *prod.example.com or prod*.example.com. - // - // * The * can't replace any of the middle labels, for example, marketing.*.example.com. - // - // * If you include * in any position other than the leftmost label in a - // domain name, DNS treats it as an * character (ASCII 42), not as a wildcard. - // - // You can't use the * wildcard for resource records sets that have a type of - // NS. - // - // You can use the * wildcard as the leftmost label in a domain name, for example, - // *.example.com. You can't use an * for one of the middle labels, for example, - // marketing.*.example.com. In addition, the * must replace the entire label; - // for example, you can't specify prod*.example.com. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // Latency-based resource record sets only: The Amazon EC2 Region where you - // created the resource that this resource record set refers to. The resource - // typically is an AWS resource, such as an EC2 instance or an ELB load balancer, - // and is referred to by an IP address or a DNS domain name, depending on the - // record type. - // - // Creating latency and latency alias resource record sets in private hosted - // zones is not supported. - // - // When Amazon Route 53 receives a DNS query for a domain name and type for - // which you have created latency resource record sets, Amazon Route 53 selects - // the latency resource record set that has the lowest latency between the end - // user and the associated Amazon EC2 Region. Amazon Route 53 then returns the - // value that is associated with the selected resource record set. - // - // Note the following: - // - // * You can only specify one ResourceRecord per latency resource record - // set. - // - // * You can only create one latency resource record set for each Amazon - // EC2 Region. - // - // * You aren't required to create latency resource record sets for all Amazon - // EC2 Regions. Amazon Route 53 will choose the region with the best latency - // from among the regions that you create latency resource record sets for. - // - // * You can't create non-latency resource record sets that have the same - // values for the Name and Type elements as latency resource record sets. - Region *string `min:"1" type:"string" enum:"ResourceRecordSetRegion"` - - // Information about the resource records to act upon. - // - // If you're creating an alias resource record set, omit ResourceRecords. - ResourceRecords []*ResourceRecord `locationNameList:"ResourceRecord" min:"1" type:"list"` - - // Weighted, Latency, Geo, and Failover resource record sets only: An identifier - // that differentiates among multiple resource record sets that have the same - // combination of DNS name and type. The value of SetIdentifier must be unique - // for each resource record set that has the same combination of DNS name and - // type. Omit SetIdentifier for any other types of record sets. - SetIdentifier *string `min:"1" type:"string"` - - // The resource record cache time to live (TTL), in seconds. Note the following: - // - // * If you're creating or updating an alias resource record set, omit TTL. - // Amazon Route 53 uses the value of TTL for the alias target. - // - // * If you're associating this resource record set with a health check (if - // you're adding a HealthCheckId element), we recommend that you specify - // a TTL of 60 seconds or less so clients respond quickly to changes in health - // status. - // - // * All of the resource record sets in a group of weighted resource record - // sets must have the same value for TTL. - // - // * If a group of weighted resource record sets includes one or more weighted - // alias resource record sets for which the alias target is an ELB load balancer, - // we recommend that you specify a TTL of 60 seconds for all of the non-alias - // weighted resource record sets that have the same name and type. Values - // other than 60 seconds (the TTL for load balancers) will change the effect - // of the values that you specify for Weight. - TTL *int64 `type:"long"` - - // When you create a traffic policy instance, Amazon Route 53 automatically - // creates a resource record set. TrafficPolicyInstanceId is the ID of the traffic - // policy instance that Amazon Route 53 created this resource record set for. - // - // To delete the resource record set that is associated with a traffic policy - // instance, use DeleteTrafficPolicyInstance. Amazon Route 53 will delete the - // resource record set automatically. If you delete the resource record set - // by using ChangeResourceRecordSets, Amazon Route 53 doesn't automatically - // delete the traffic policy instance, and you'll continue to be charged for - // it even though it's no longer in use. - TrafficPolicyInstanceId *string `min:"1" type:"string"` - - // The DNS record type. For information about different record types and how - // data is encoded for them, see Supported DNS Resource Record Types (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html) - // in the Amazon Route 53 Developer Guide. - // - // Valid values for basic resource record sets: A | AAAA | CAA | CNAME | MX - // | NAPTR | NS | PTR | SOA | SPF | SRV | TXT - // - // Values for weighted, latency, geolocation, and failover resource record sets: - // A | AAAA | CAA | CNAME | MX | NAPTR | PTR | SPF | SRV | TXT. When creating - // a group of weighted, latency, geolocation, or failover resource record sets, - // specify the same value for all of the resource record sets in the group. - // - // Valid values for multivalue answer resource record sets: A | AAAA | MX | - // NAPTR | PTR | SPF | SRV | TXT - // - // SPF records were formerly used to verify the identity of the sender of email - // messages. However, we no longer recommend that you create resource record - // sets for which the value of Type is SPF. RFC 7208, Sender Policy Framework - // (SPF) for Authorizing Use of Domains in Email, Version 1, has been updated - // to say, "...[I]ts existence and mechanism defined in [RFC4408] have led to - // some interoperability issues. Accordingly, its use is no longer appropriate - // for SPF version 1; implementations are not to use it." In RFC 7208, see section - // 14.1, The SPF DNS Record Type (http://tools.ietf.org/html/rfc7208#section-14.1). - // - // Values for alias resource record sets: - // - // * CloudFront distributions:A - // - // If IPv6 is enabled for the distribution, create two resource record sets - // to route traffic to your distribution, one with a value of A and one with - // a value of AAAA. - // - // * AWS Elastic Beanstalk environment that has a regionalized subdomain: - // A - // - // * ELB load balancers:A | AAAA - // - // * Amazon S3 buckets:A - // - // * Another resource record set in this hosted zone: Specify the type of - // the resource record set that you're creating the alias for. All values - // are supported except NS and SOA. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"RRType"` - - // Weighted resource record sets only: Among resource record sets that have - // the same combination of DNS name and type, a value that determines the proportion - // of DNS queries that Amazon Route 53 responds to using the current resource - // record set. Amazon Route 53 calculates the sum of the weights for the resource - // record sets that have the same combination of DNS name and type. Amazon Route - // 53 then responds to queries based on the ratio of a resource's weight to - // the total. Note the following: - // - // * You must specify a value for the Weight element for every weighted resource - // record set. - // - // * You can only specify one ResourceRecord per weighted resource record - // set. - // - // * You can't create latency, failover, or geolocation resource record sets - // that have the same values for the Name and Type elements as weighted resource - // record sets. - // - // * You can create a maximum of 100 weighted resource record sets that have - // the same values for the Name and Type elements. - // - // * For weighted (but not weighted alias) resource record sets, if you set - // Weight to 0 for a resource record set, Amazon Route 53 never responds - // to queries with the applicable value for that resource record set. However, - // if you set Weight to 0 for all resource record sets that have the same - // combination of DNS name and type, traffic is routed to all resources with - // equal probability. - // - // The effect of setting Weight to 0 is different when you associate health - // checks with weighted resource record sets. For more information, see Options - // for Configuring Amazon Route 53 Active-Active and Active-Passive Failover - // (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html) - // in the Amazon Route 53 Developer Guide. - Weight *int64 `type:"long"` -} - -// String returns the string representation -func (s ResourceRecordSet) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceRecordSet) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ResourceRecordSet) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ResourceRecordSet"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Region != nil && len(*s.Region) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Region", 1)) - } - if s.ResourceRecords != nil && len(s.ResourceRecords) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceRecords", 1)) - } - if s.SetIdentifier != nil && len(*s.SetIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SetIdentifier", 1)) - } - if s.TrafficPolicyInstanceId != nil && len(*s.TrafficPolicyInstanceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyInstanceId", 1)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.AliasTarget != nil { - if err := s.AliasTarget.Validate(); err != nil { - invalidParams.AddNested("AliasTarget", err.(request.ErrInvalidParams)) - } - } - if s.GeoLocation != nil { - if err := s.GeoLocation.Validate(); err != nil { - invalidParams.AddNested("GeoLocation", err.(request.ErrInvalidParams)) - } - } - if s.ResourceRecords != nil { - for i, v := range s.ResourceRecords { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ResourceRecords", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAliasTarget sets the AliasTarget field's value. -func (s *ResourceRecordSet) SetAliasTarget(v *AliasTarget) *ResourceRecordSet { - s.AliasTarget = v - return s -} - -// SetFailover sets the Failover field's value. -func (s *ResourceRecordSet) SetFailover(v string) *ResourceRecordSet { - s.Failover = &v - return s -} - -// SetGeoLocation sets the GeoLocation field's value. -func (s *ResourceRecordSet) SetGeoLocation(v *GeoLocation) *ResourceRecordSet { - s.GeoLocation = v - return s -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *ResourceRecordSet) SetHealthCheckId(v string) *ResourceRecordSet { - s.HealthCheckId = &v - return s -} - -// SetMultiValueAnswer sets the MultiValueAnswer field's value. -func (s *ResourceRecordSet) SetMultiValueAnswer(v bool) *ResourceRecordSet { - s.MultiValueAnswer = &v - return s -} - -// SetName sets the Name field's value. -func (s *ResourceRecordSet) SetName(v string) *ResourceRecordSet { - s.Name = &v - return s -} - -// SetRegion sets the Region field's value. -func (s *ResourceRecordSet) SetRegion(v string) *ResourceRecordSet { - s.Region = &v - return s -} - -// SetResourceRecords sets the ResourceRecords field's value. -func (s *ResourceRecordSet) SetResourceRecords(v []*ResourceRecord) *ResourceRecordSet { - s.ResourceRecords = v - return s -} - -// SetSetIdentifier sets the SetIdentifier field's value. -func (s *ResourceRecordSet) SetSetIdentifier(v string) *ResourceRecordSet { - s.SetIdentifier = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *ResourceRecordSet) SetTTL(v int64) *ResourceRecordSet { - s.TTL = &v - return s -} - -// SetTrafficPolicyInstanceId sets the TrafficPolicyInstanceId field's value. -func (s *ResourceRecordSet) SetTrafficPolicyInstanceId(v string) *ResourceRecordSet { - s.TrafficPolicyInstanceId = &v - return s -} - -// SetType sets the Type field's value. -func (s *ResourceRecordSet) SetType(v string) *ResourceRecordSet { - s.Type = &v - return s -} - -// SetWeight sets the Weight field's value. -func (s *ResourceRecordSet) SetWeight(v int64) *ResourceRecordSet { - s.Weight = &v - return s -} - -// A complex type containing a resource and its associated tags. -type ResourceTagSet struct { - _ struct{} `type:"structure"` - - // The ID for the specified resource. - ResourceId *string `type:"string"` - - // The type of the resource. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - ResourceType *string `type:"string" enum:"TagResourceType"` - - // The tags associated with the specified resource. - Tags []*Tag `locationNameList:"Tag" min:"1" type:"list"` -} - -// String returns the string representation -func (s ResourceTagSet) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceTagSet) GoString() string { - return s.String() -} - -// SetResourceId sets the ResourceId field's value. -func (s *ResourceTagSet) SetResourceId(v string) *ResourceTagSet { - s.ResourceId = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ResourceTagSet) SetResourceType(v string) *ResourceTagSet { - s.ResourceType = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *ResourceTagSet) SetTags(v []*Tag) *ResourceTagSet { - s.Tags = v - return s -} - -// A complex type that contains the type of limit that you specified in the -// request and the current value for that limit. -type ReusableDelegationSetLimit struct { - _ struct{} `type:"structure"` - - // The limit that you requested: MAX_ZONES_BY_REUSABLE_DELEGATION_SET, the maximum - // number of hosted zones that you can associate with the specified reusable - // delegation set. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"ReusableDelegationSetLimitType"` - - // The current value for the MAX_ZONES_BY_REUSABLE_DELEGATION_SET limit. - // - // Value is a required field - Value *int64 `min:"1" type:"long" required:"true"` -} - -// String returns the string representation -func (s ReusableDelegationSetLimit) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReusableDelegationSetLimit) GoString() string { - return s.String() -} - -// SetType sets the Type field's value. -func (s *ReusableDelegationSetLimit) SetType(v string) *ReusableDelegationSetLimit { - s.Type = &v - return s -} - -// SetValue sets the Value field's value. -func (s *ReusableDelegationSetLimit) SetValue(v int64) *ReusableDelegationSetLimit { - s.Value = &v - return s -} - -// A complex type that contains the status that one Amazon Route 53 health checker -// reports and the time of the health check. -type StatusReport struct { - _ struct{} `type:"structure"` - - // The date and time that the health checker performed the health check in ISO - // 8601 format (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal - // Time (UTC). For example, the value 2017-03-27T17:48:16.751Z represents March - // 27, 2017 at 17:48:16.751 UTC. - CheckedTime *time.Time `type:"timestamp"` - - // A description of the status of the health check endpoint as reported by one - // of the Amazon Route 53 health checkers. - Status *string `type:"string"` -} - -// String returns the string representation -func (s StatusReport) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StatusReport) GoString() string { - return s.String() -} - -// SetCheckedTime sets the CheckedTime field's value. -func (s *StatusReport) SetCheckedTime(v time.Time) *StatusReport { - s.CheckedTime = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *StatusReport) SetStatus(v string) *StatusReport { - s.Status = &v - return s -} - -// A complex type that contains information about a tag that you want to add -// or edit for the specified health check or hosted zone. -type Tag struct { - _ struct{} `type:"structure"` - - // The value of Key depends on the operation that you want to perform: - // - // * Add a tag to a health check or hosted zone: Key is the name that you - // want to give the new tag. - // - // * Edit a tag: Key is the name of the tag that you want to change the Value - // for. - // - // * Delete a key: Key is the name of the tag you want to remove. - // - // * Give a name to a health check: Edit the default Name tag. In the Amazon - // Route 53 console, the list of your health checks includes a Name column - // that lets you see the name that you've given to each health check. - Key *string `type:"string"` - - // The value of Value depends on the operation that you want to perform: - // - // * Add a tag to a health check or hosted zone: Value is the value that - // you want to give the new tag. - // - // * Edit a tag: Value is the new value that you want to assign the tag. - Value *string `type:"string"` -} - -// String returns the string representation -func (s Tag) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Tag) GoString() string { - return s.String() -} - -// SetKey sets the Key field's value. -func (s *Tag) SetKey(v string) *Tag { - s.Key = &v - return s -} - -// SetValue sets the Value field's value. -func (s *Tag) SetValue(v string) *Tag { - s.Value = &v - return s -} - -// Gets the value that Amazon Route 53 returns in response to a DNS request -// for a specified record name and type. You can optionally specify the IP address -// of a DNS resolver, an EDNS0 client subnet IP address, and a subnet mask. -type TestDNSAnswerInput struct { - _ struct{} `type:"structure"` - - // If the resolver that you specified for resolverip supports EDNS0, specify - // the IPv4 or IPv6 address of a client in the applicable location, for example, - // 192.0.2.44 or 2001:db8:85a3::8a2e:370:7334. - EDNS0ClientSubnetIP *string `location:"querystring" locationName:"edns0clientsubnetip" type:"string"` - - // If you specify an IP address for edns0clientsubnetip, you can optionally - // specify the number of bits of the IP address that you want the checking tool - // to include in the DNS query. For example, if you specify 192.0.2.44 for edns0clientsubnetip - // and 24 for edns0clientsubnetmask, the checking tool will simulate a request - // from 192.0.2.0/24. The default value is 24 bits for IPv4 addresses and 64 - // bits for IPv6 addresses. - EDNS0ClientSubnetMask *string `location:"querystring" locationName:"edns0clientsubnetmask" type:"string"` - - // The ID of the hosted zone that you want Amazon Route 53 to simulate a query - // for. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"querystring" locationName:"hostedzoneid" type:"string" required:"true"` - - // The name of the resource record set that you want Amazon Route 53 to simulate - // a query for. - // - // RecordName is a required field - RecordName *string `location:"querystring" locationName:"recordname" type:"string" required:"true"` - - // The type of the resource record set. - // - // RecordType is a required field - RecordType *string `location:"querystring" locationName:"recordtype" type:"string" required:"true" enum:"RRType"` - - // If you want to simulate a request from a specific DNS resolver, specify the - // IP address for that resolver. If you omit this value, TestDnsAnswer uses - // the IP address of a DNS resolver in the AWS US East (N. Virginia) Region - // (us-east-1). - ResolverIP *string `location:"querystring" locationName:"resolverip" type:"string"` -} - -// String returns the string representation -func (s TestDNSAnswerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TestDNSAnswerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TestDNSAnswerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TestDNSAnswerInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.RecordName == nil { - invalidParams.Add(request.NewErrParamRequired("RecordName")) - } - if s.RecordType == nil { - invalidParams.Add(request.NewErrParamRequired("RecordType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEDNS0ClientSubnetIP sets the EDNS0ClientSubnetIP field's value. -func (s *TestDNSAnswerInput) SetEDNS0ClientSubnetIP(v string) *TestDNSAnswerInput { - s.EDNS0ClientSubnetIP = &v - return s -} - -// SetEDNS0ClientSubnetMask sets the EDNS0ClientSubnetMask field's value. -func (s *TestDNSAnswerInput) SetEDNS0ClientSubnetMask(v string) *TestDNSAnswerInput { - s.EDNS0ClientSubnetMask = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *TestDNSAnswerInput) SetHostedZoneId(v string) *TestDNSAnswerInput { - s.HostedZoneId = &v - return s -} - -// SetRecordName sets the RecordName field's value. -func (s *TestDNSAnswerInput) SetRecordName(v string) *TestDNSAnswerInput { - s.RecordName = &v - return s -} - -// SetRecordType sets the RecordType field's value. -func (s *TestDNSAnswerInput) SetRecordType(v string) *TestDNSAnswerInput { - s.RecordType = &v - return s -} - -// SetResolverIP sets the ResolverIP field's value. -func (s *TestDNSAnswerInput) SetResolverIP(v string) *TestDNSAnswerInput { - s.ResolverIP = &v - return s -} - -// A complex type that contains the response to a TestDNSAnswer request. -type TestDNSAnswerOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Route 53 name server used to respond to the request. - // - // Nameserver is a required field - Nameserver *string `type:"string" required:"true"` - - // The protocol that Amazon Route 53 used to respond to the request, either - // UDP or TCP. - // - // Protocol is a required field - Protocol *string `type:"string" required:"true"` - - // A list that contains values that Amazon Route 53 returned for this resource - // record set. - // - // RecordData is a required field - RecordData []*string `locationNameList:"RecordDataEntry" type:"list" required:"true"` - - // The name of the resource record set that you submitted a request for. - // - // RecordName is a required field - RecordName *string `type:"string" required:"true"` - - // The type of the resource record set that you submitted a request for. - // - // RecordType is a required field - RecordType *string `type:"string" required:"true" enum:"RRType"` - - // A code that indicates whether the request is valid or not. The most common - // response code is NOERROR, meaning that the request is valid. If the response - // is not valid, Amazon Route 53 returns a response code that describes the - // error. For a list of possible response codes, see DNS RCODES (http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6) - // on the IANA website. - // - // ResponseCode is a required field - ResponseCode *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s TestDNSAnswerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TestDNSAnswerOutput) GoString() string { - return s.String() -} - -// SetNameserver sets the Nameserver field's value. -func (s *TestDNSAnswerOutput) SetNameserver(v string) *TestDNSAnswerOutput { - s.Nameserver = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *TestDNSAnswerOutput) SetProtocol(v string) *TestDNSAnswerOutput { - s.Protocol = &v - return s -} - -// SetRecordData sets the RecordData field's value. -func (s *TestDNSAnswerOutput) SetRecordData(v []*string) *TestDNSAnswerOutput { - s.RecordData = v - return s -} - -// SetRecordName sets the RecordName field's value. -func (s *TestDNSAnswerOutput) SetRecordName(v string) *TestDNSAnswerOutput { - s.RecordName = &v - return s -} - -// SetRecordType sets the RecordType field's value. -func (s *TestDNSAnswerOutput) SetRecordType(v string) *TestDNSAnswerOutput { - s.RecordType = &v - return s -} - -// SetResponseCode sets the ResponseCode field's value. -func (s *TestDNSAnswerOutput) SetResponseCode(v string) *TestDNSAnswerOutput { - s.ResponseCode = &v - return s -} - -// A complex type that contains settings for a traffic policy. -type TrafficPolicy struct { - _ struct{} `type:"structure"` - - // The comment that you specify in the CreateTrafficPolicy request, if any. - Comment *string `type:"string"` - - // The definition of a traffic policy in JSON format. You specify the JSON document - // to use for a new traffic policy in the CreateTrafficPolicy request. For more - // information about the JSON format, see Traffic Policy Document Format (http://docs.aws.amazon.com/Route53/latest/APIReference/api-policies-traffic-policy-document-format.html). - // - // Document is a required field - Document *string `type:"string" required:"true"` - - // The ID that Amazon Route 53 assigned to a traffic policy when you created - // it. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` - - // The name that you specified when you created the traffic policy. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The DNS type of the resource record sets that Amazon Route 53 creates when - // you use a traffic policy to create a traffic policy instance. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"RRType"` - - // The version number that Amazon Route 53 assigns to a traffic policy. For - // a new traffic policy, the value of Version is always 1. - // - // Version is a required field - Version *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s TrafficPolicy) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TrafficPolicy) GoString() string { - return s.String() -} - -// SetComment sets the Comment field's value. -func (s *TrafficPolicy) SetComment(v string) *TrafficPolicy { - s.Comment = &v - return s -} - -// SetDocument sets the Document field's value. -func (s *TrafficPolicy) SetDocument(v string) *TrafficPolicy { - s.Document = &v - return s -} - -// SetId sets the Id field's value. -func (s *TrafficPolicy) SetId(v string) *TrafficPolicy { - s.Id = &v - return s -} - -// SetName sets the Name field's value. -func (s *TrafficPolicy) SetName(v string) *TrafficPolicy { - s.Name = &v - return s -} - -// SetType sets the Type field's value. -func (s *TrafficPolicy) SetType(v string) *TrafficPolicy { - s.Type = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *TrafficPolicy) SetVersion(v int64) *TrafficPolicy { - s.Version = &v - return s -} - -// A complex type that contains settings for the new traffic policy instance. -type TrafficPolicyInstance struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that Amazon Route 53 created resource record sets - // in. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The ID that Amazon Route 53 assigned to the new traffic policy instance. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` - - // If State is Failed, an explanation of the reason for the failure. If State - // is another value, Message is empty. - // - // Message is a required field - Message *string `type:"string" required:"true"` - - // The DNS name, such as www.example.com, for which Amazon Route 53 responds - // to queries by using the resource record sets that are associated with this - // traffic policy instance. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The value of State is one of the following values: - // - // AppliedAmazon Route 53 has finished creating resource record sets, and changes - // have propagated to all Amazon Route 53 edge locations. - // - // CreatingAmazon Route 53 is creating the resource record sets. Use GetTrafficPolicyInstance - // to confirm that the CreateTrafficPolicyInstance request completed successfully. - // - // FailedAmazon Route 53 wasn't able to create or update the resource record - // sets. When the value of State is Failed, see Message for an explanation of - // what caused the request to fail. - // - // State is a required field - State *string `type:"string" required:"true"` - - // The TTL that Amazon Route 53 assigned to all of the resource record sets - // that it created in the specified hosted zone. - // - // TTL is a required field - TTL *int64 `type:"long" required:"true"` - - // The ID of the traffic policy that Amazon Route 53 used to create resource - // record sets in the specified hosted zone. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `min:"1" type:"string" required:"true"` - - // The DNS type that Amazon Route 53 assigned to all of the resource record - // sets that it created for this traffic policy instance. - // - // TrafficPolicyType is a required field - TrafficPolicyType *string `type:"string" required:"true" enum:"RRType"` - - // The version of the traffic policy that Amazon Route 53 used to create resource - // record sets in the specified hosted zone. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s TrafficPolicyInstance) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TrafficPolicyInstance) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *TrafficPolicyInstance) SetHostedZoneId(v string) *TrafficPolicyInstance { - s.HostedZoneId = &v - return s -} - -// SetId sets the Id field's value. -func (s *TrafficPolicyInstance) SetId(v string) *TrafficPolicyInstance { - s.Id = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *TrafficPolicyInstance) SetMessage(v string) *TrafficPolicyInstance { - s.Message = &v - return s -} - -// SetName sets the Name field's value. -func (s *TrafficPolicyInstance) SetName(v string) *TrafficPolicyInstance { - s.Name = &v - return s -} - -// SetState sets the State field's value. -func (s *TrafficPolicyInstance) SetState(v string) *TrafficPolicyInstance { - s.State = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *TrafficPolicyInstance) SetTTL(v int64) *TrafficPolicyInstance { - s.TTL = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *TrafficPolicyInstance) SetTrafficPolicyId(v string) *TrafficPolicyInstance { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyType sets the TrafficPolicyType field's value. -func (s *TrafficPolicyInstance) SetTrafficPolicyType(v string) *TrafficPolicyInstance { - s.TrafficPolicyType = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *TrafficPolicyInstance) SetTrafficPolicyVersion(v int64) *TrafficPolicyInstance { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains information about the latest version of one -// traffic policy that is associated with the current AWS account. -type TrafficPolicySummary struct { - _ struct{} `type:"structure"` - - // The ID that Amazon Route 53 assigned to the traffic policy when you created - // it. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` - - // The version number of the latest version of the traffic policy. - // - // LatestVersion is a required field - LatestVersion *int64 `min:"1" type:"integer" required:"true"` - - // The name that you specified for the traffic policy when you created it. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The number of traffic policies that are associated with the current AWS account. - // - // TrafficPolicyCount is a required field - TrafficPolicyCount *int64 `min:"1" type:"integer" required:"true"` - - // The DNS type of the resource record sets that Amazon Route 53 creates when - // you use a traffic policy to create a traffic policy instance. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"RRType"` -} - -// String returns the string representation -func (s TrafficPolicySummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TrafficPolicySummary) GoString() string { - return s.String() -} - -// SetId sets the Id field's value. -func (s *TrafficPolicySummary) SetId(v string) *TrafficPolicySummary { - s.Id = &v - return s -} - -// SetLatestVersion sets the LatestVersion field's value. -func (s *TrafficPolicySummary) SetLatestVersion(v int64) *TrafficPolicySummary { - s.LatestVersion = &v - return s -} - -// SetName sets the Name field's value. -func (s *TrafficPolicySummary) SetName(v string) *TrafficPolicySummary { - s.Name = &v - return s -} - -// SetTrafficPolicyCount sets the TrafficPolicyCount field's value. -func (s *TrafficPolicySummary) SetTrafficPolicyCount(v int64) *TrafficPolicySummary { - s.TrafficPolicyCount = &v - return s -} - -// SetType sets the Type field's value. -func (s *TrafficPolicySummary) SetType(v string) *TrafficPolicySummary { - s.Type = &v - return s -} - -// A complex type that contains information about a request to update a health -// check. -type UpdateHealthCheckInput struct { - _ struct{} `locationName:"UpdateHealthCheckRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that identifies the CloudWatch alarm that you want Amazon - // Route 53 health checkers to use to determine whether this health check is - // healthy. - AlarmIdentifier *AlarmIdentifier `type:"structure"` - - // A complex type that contains one ChildHealthCheck element for each health - // check that you want to associate with a CALCULATED health check. - ChildHealthChecks []*string `locationNameList:"ChildHealthCheck" type:"list"` - - // Specify whether you want Amazon Route 53 to send the value of FullyQualifiedDomainName - // to the endpoint in the client_hello message during TLS negotiation. This - // allows the endpoint to respond to HTTPS health check requests with the applicable - // SSL/TLS certificate. - // - // Some endpoints require that HTTPS requests include the host name in the client_hello - // message. If you don't enable SNI, the status of the health check will be - // SSL alert handshake_failure. A health check can also have that status for - // other reasons. If SNI is enabled and you're still getting the error, check - // the SSL/TLS configuration on your endpoint and confirm that your certificate - // is valid. - // - // The SSL/TLS certificate on your endpoint includes a domain name in the Common - // Name field and possibly several more in the Subject Alternative Names field. - // One of the domain names in the certificate should match the value that you - // specify for FullyQualifiedDomainName. If the endpoint responds to the client_hello - // message with a certificate that does not include the domain name that you - // specified in FullyQualifiedDomainName, a health checker will retry the handshake. - // In the second attempt, the health checker will omit FullyQualifiedDomainName - // from the client_hello message. - EnableSNI *bool `type:"boolean"` - - // The number of consecutive health checks that an endpoint must pass or fail - // for Amazon Route 53 to change the current status of the endpoint from unhealthy - // to healthy or vice versa. For more information, see How Amazon Route 53 Determines - // Whether an Endpoint Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - // in the Amazon Route 53 Developer Guide. - // - // If you don't specify a value for FailureThreshold, the default value is three - // health checks. - FailureThreshold *int64 `min:"1" type:"integer"` - - // Amazon Route 53 behavior depends on whether you specify a value for IPAddress. - // - // If a health check already has a value for IPAddress, you can change the value. - // However, you can't update an existing health check to add or remove the value - // of IPAddress. - // - // If you specify a value forIPAddress: - // - // Amazon Route 53 sends health check requests to the specified IPv4 or IPv6 - // address and passes the value of FullyQualifiedDomainName in the Host header - // for all health checks except TCP health checks. This is typically the fully - // qualified DNS name of the endpoint on which you want Amazon Route 53 to perform - // health checks. - // - // When Amazon Route 53 checks the health of an endpoint, here is how it constructs - // the Host header: - // - // * If you specify a value of 80 for Port and HTTP or HTTP_STR_MATCH for - // Type, Amazon Route 53 passes the value of FullyQualifiedDomainName to - // the endpoint in the Host header. - // - // * If you specify a value of 443 for Port and HTTPS or HTTPS_STR_MATCH - // for Type, Amazon Route 53 passes the value of FullyQualifiedDomainName - // to the endpoint in the Host header. - // - // * If you specify another value for Port and any value except TCP for Type, - // Amazon Route 53 passes FullyQualifiedDomainName:Port to the endpoint in - // the Host header. - // - // If you don't specify a value for FullyQualifiedDomainName, Amazon Route 53 - // substitutes the value of IPAddress in the Host header in each of the above - // cases. - // - // If you don't specify a value forIPAddress: - // - // If you don't specify a value for IPAddress, Amazon Route 53 sends a DNS request - // to the domain that you specify in FullyQualifiedDomainName at the interval - // you specify in RequestInterval. Using an IPv4 address that is returned by - // DNS, Amazon Route 53 then checks the health of the endpoint. - // - // If you don't specify a value for IPAddress, Amazon Route 53 uses only IPv4 - // to send health checks to the endpoint. If there's no resource record set - // with a type of A for the name that you specify for FullyQualifiedDomainName, - // the health check fails with a "DNS resolution failed" error. - // - // If you want to check the health of weighted, latency, or failover resource - // record sets and you choose to specify the endpoint only by FullyQualifiedDomainName, - // we recommend that you create a separate health check for each endpoint. For - // example, create a health check for each HTTP server that is serving content - // for www.example.com. For the value of FullyQualifiedDomainName, specify the - // domain name of the server (such as us-east-2-www.example.com), not the name - // of the resource record sets (www.example.com). - // - // In this configuration, if the value of FullyQualifiedDomainName matches the - // name of the resource record sets and you then associate the health check - // with those resource record sets, health check results will be unpredictable. - // - // In addition, if the value of Type is HTTP, HTTPS, HTTP_STR_MATCH, or HTTPS_STR_MATCH, - // Amazon Route 53 passes the value of FullyQualifiedDomainName in the Host - // header, as it does when you specify a value for IPAddress. If the value of - // Type is TCP, Amazon Route 53 doesn't pass a Host header. - FullyQualifiedDomainName *string `type:"string"` - - // The ID for the health check for which you want detailed information. When - // you created the health check, CreateHealthCheck returned the ID in the response, - // in the HealthCheckId element. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` - - // A sequential counter that Amazon Route 53 sets to 1 when you create a health - // check and increments by 1 each time you update settings for the health check. - // - // We recommend that you use GetHealthCheck or ListHealthChecks to get the current - // value of HealthCheckVersion for the health check that you want to update, - // and that you include that value in your UpdateHealthCheck request. This prevents - // Amazon Route 53 from overwriting an intervening update: - // - // * If the value in the UpdateHealthCheck request matches the value of HealthCheckVersion - // in the health check, Amazon Route 53 updates the health check with the - // new settings. - // - // * If the value of HealthCheckVersion in the health check is greater, the - // health check was changed after you got the version number. Amazon Route - // 53 does not update the health check, and it returns a HealthCheckVersionMismatch - // error. - HealthCheckVersion *int64 `min:"1" type:"long"` - - // The number of child health checks that are associated with a CALCULATED health - // that Amazon Route 53 must consider healthy for the CALCULATED health check - // to be considered healthy. To specify the child health checks that you want - // to associate with a CALCULATED health check, use the ChildHealthChecks and - // ChildHealthCheck elements. - // - // Note the following: - // - // * If you specify a number greater than the number of child health checks, - // Amazon Route 53 always considers this health check to be unhealthy. - // - // * If you specify 0, Amazon Route 53 always considers this health check - // to be healthy. - HealthThreshold *int64 `type:"integer"` - - // The IPv4 or IPv6 IP address for the endpoint that you want Amazon Route 53 - // to perform health checks on. If you don't specify a value for IPAddress, - // Amazon Route 53 sends a DNS request to resolve the domain name that you specify - // in FullyQualifiedDomainName at the interval that you specify in RequestInterval. - // Using an IP address that is returned by DNS, Amazon Route 53 then checks - // the health of the endpoint. - // - // Use one of the following formats for the value of IPAddress: - // - // * IPv4 address: four values between 0 and 255, separated by periods (.), - // for example, 192.0.2.44. - // - // * IPv6 address: eight groups of four hexadecimal values, separated by - // colons (:), for example, 2001:0db8:85a3:0000:0000:abcd:0001:2345. You - // can also shorten IPv6 addresses as described in RFC 5952, for example, - // 2001:db8:85a3::abcd:1:2345. - // - // If the endpoint is an EC2 instance, we recommend that you create an Elastic - // IP address, associate it with your EC2 instance, and specify the Elastic - // IP address for IPAddress. This ensures that the IP address of your instance - // never changes. For more information, see the applicable documentation: - // - // * Linux: Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) - // in the Amazon EC2 User Guide for Linux Instances - // - // * Windows: Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-ip-addresses-eip.html) - // in the Amazon EC2 User Guide for Windows Instances - // - // If a health check already has a value for IPAddress, you can change the value. - // However, you can't update an existing health check to add or remove the value - // of IPAddress. - // - // For more information, see UpdateHealthCheckRequest$FullyQualifiedDomainName. - // - // Constraints: Amazon Route 53 can't check the health of endpoints for which - // the IP address is in local, private, non-routable, or multicast ranges. For - // more information about IP addresses for which you can't create health checks, - // see the following documents: - // - // * RFC 5735, Special Use IPv4 Addresses (https://tools.ietf.org/html/rfc5735) - // - // * RFC 6598, IANA-Reserved IPv4 Prefix for Shared Address Space (https://tools.ietf.org/html/rfc6598) - // - // * RFC 5156, Special-Use IPv6 Addresses (https://tools.ietf.org/html/rfc5156) - IPAddress *string `type:"string"` - - // When CloudWatch has insufficient data about the metric to determine the alarm - // state, the status that you want Amazon Route 53 to assign to the health check: - // - // * Healthy: Amazon Route 53 considers the health check to be healthy. - // - // * Unhealthy: Amazon Route 53 considers the health check to be unhealthy. - // - // * LastKnownStatus: Amazon Route 53 uses the status of the health check - // from the last time CloudWatch had sufficient data to determine the alarm - // state. For new health checks that have no last known status, the default - // status for the health check is healthy. - InsufficientDataHealthStatus *string `type:"string" enum:"InsufficientDataHealthStatus"` - - // Specify whether you want Amazon Route 53 to invert the status of a health - // check, for example, to consider a health check unhealthy when it otherwise - // would be considered healthy. - Inverted *bool `type:"boolean"` - - // The port on the endpoint on which you want Amazon Route 53 to perform health - // checks. - Port *int64 `min:"1" type:"integer"` - - // A complex type that contains one Region element for each region that you - // want Amazon Route 53 health checkers to check the specified endpoint from. - Regions []*string `locationNameList:"Region" min:"3" type:"list"` - - // A complex type that contains one ResettableElementName element for each element - // that you want to reset to the default value. Valid values for ResettableElementName - // include the following: - // - // * ChildHealthChecks: Amazon Route 53 resets HealthCheckConfig$ChildHealthChecks - // to null. - // - // * FullyQualifiedDomainName: Amazon Route 53 resets HealthCheckConfig$FullyQualifiedDomainName - // to null. - // - // * Regions: Amazon Route 53 resets the HealthCheckConfig$Regions list to - // the default set of regions. - // - // * ResourcePath: Amazon Route 53 resets HealthCheckConfig$ResourcePath - // to null. - ResetElements []*string `locationNameList:"ResettableElementName" type:"list"` - - // The path that you want Amazon Route 53 to request when performing health - // checks. The path can be any value for which your endpoint will return an - // HTTP status code of 2xx or 3xx when the endpoint is healthy, for example - // the file /docs/route53-health-check.html. - // - // Specify this value only if you want to change it. - ResourcePath *string `type:"string"` - - // If the value of Type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string that - // you want Amazon Route 53 to search for in the response body from the specified - // resource. If the string appears in the response body, Amazon Route 53 considers - // the resource healthy. (You can't change the value of Type when you update - // a health check.) - SearchString *string `type:"string"` -} - -// String returns the string representation -func (s UpdateHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateHealthCheckInput"} - if s.FailureThreshold != nil && *s.FailureThreshold < 1 { - invalidParams.Add(request.NewErrParamMinValue("FailureThreshold", 1)) - } - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - if s.HealthCheckVersion != nil && *s.HealthCheckVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("HealthCheckVersion", 1)) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } - if s.Regions != nil && len(s.Regions) < 3 { - invalidParams.Add(request.NewErrParamMinLen("Regions", 3)) - } - if s.AlarmIdentifier != nil { - if err := s.AlarmIdentifier.Validate(); err != nil { - invalidParams.AddNested("AlarmIdentifier", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAlarmIdentifier sets the AlarmIdentifier field's value. -func (s *UpdateHealthCheckInput) SetAlarmIdentifier(v *AlarmIdentifier) *UpdateHealthCheckInput { - s.AlarmIdentifier = v - return s -} - -// SetChildHealthChecks sets the ChildHealthChecks field's value. -func (s *UpdateHealthCheckInput) SetChildHealthChecks(v []*string) *UpdateHealthCheckInput { - s.ChildHealthChecks = v - return s -} - -// SetEnableSNI sets the EnableSNI field's value. -func (s *UpdateHealthCheckInput) SetEnableSNI(v bool) *UpdateHealthCheckInput { - s.EnableSNI = &v - return s -} - -// SetFailureThreshold sets the FailureThreshold field's value. -func (s *UpdateHealthCheckInput) SetFailureThreshold(v int64) *UpdateHealthCheckInput { - s.FailureThreshold = &v - return s -} - -// SetFullyQualifiedDomainName sets the FullyQualifiedDomainName field's value. -func (s *UpdateHealthCheckInput) SetFullyQualifiedDomainName(v string) *UpdateHealthCheckInput { - s.FullyQualifiedDomainName = &v - return s -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *UpdateHealthCheckInput) SetHealthCheckId(v string) *UpdateHealthCheckInput { - s.HealthCheckId = &v - return s -} - -// SetHealthCheckVersion sets the HealthCheckVersion field's value. -func (s *UpdateHealthCheckInput) SetHealthCheckVersion(v int64) *UpdateHealthCheckInput { - s.HealthCheckVersion = &v - return s -} - -// SetHealthThreshold sets the HealthThreshold field's value. -func (s *UpdateHealthCheckInput) SetHealthThreshold(v int64) *UpdateHealthCheckInput { - s.HealthThreshold = &v - return s -} - -// SetIPAddress sets the IPAddress field's value. -func (s *UpdateHealthCheckInput) SetIPAddress(v string) *UpdateHealthCheckInput { - s.IPAddress = &v - return s -} - -// SetInsufficientDataHealthStatus sets the InsufficientDataHealthStatus field's value. -func (s *UpdateHealthCheckInput) SetInsufficientDataHealthStatus(v string) *UpdateHealthCheckInput { - s.InsufficientDataHealthStatus = &v - return s -} - -// SetInverted sets the Inverted field's value. -func (s *UpdateHealthCheckInput) SetInverted(v bool) *UpdateHealthCheckInput { - s.Inverted = &v - return s -} - -// SetPort sets the Port field's value. -func (s *UpdateHealthCheckInput) SetPort(v int64) *UpdateHealthCheckInput { - s.Port = &v - return s -} - -// SetRegions sets the Regions field's value. -func (s *UpdateHealthCheckInput) SetRegions(v []*string) *UpdateHealthCheckInput { - s.Regions = v - return s -} - -// SetResetElements sets the ResetElements field's value. -func (s *UpdateHealthCheckInput) SetResetElements(v []*string) *UpdateHealthCheckInput { - s.ResetElements = v - return s -} - -// SetResourcePath sets the ResourcePath field's value. -func (s *UpdateHealthCheckInput) SetResourcePath(v string) *UpdateHealthCheckInput { - s.ResourcePath = &v - return s -} - -// SetSearchString sets the SearchString field's value. -func (s *UpdateHealthCheckInput) SetSearchString(v string) *UpdateHealthCheckInput { - s.SearchString = &v - return s -} - -type UpdateHealthCheckOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about one health check that is associated - // with the current AWS account. - // - // HealthCheck is a required field - HealthCheck *HealthCheck `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHealthCheckOutput) GoString() string { - return s.String() -} - -// SetHealthCheck sets the HealthCheck field's value. -func (s *UpdateHealthCheckOutput) SetHealthCheck(v *HealthCheck) *UpdateHealthCheckOutput { - s.HealthCheck = v - return s -} - -// A request to update the comment for a hosted zone. -type UpdateHostedZoneCommentInput struct { - _ struct{} `locationName:"UpdateHostedZoneCommentRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The new comment for the hosted zone. If you don't specify a value for Comment, - // Amazon Route 53 deletes the existing value of the Comment element, if any. - Comment *string `type:"string"` - - // The ID for the hosted zone that you want to update the comment for. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s UpdateHostedZoneCommentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHostedZoneCommentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateHostedZoneCommentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateHostedZoneCommentInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *UpdateHostedZoneCommentInput) SetComment(v string) *UpdateHostedZoneCommentInput { - s.Comment = &v - return s -} - -// SetId sets the Id field's value. -func (s *UpdateHostedZoneCommentInput) SetId(v string) *UpdateHostedZoneCommentInput { - s.Id = &v - return s -} - -// A complex type that contains the response to the UpdateHostedZoneComment -// request. -type UpdateHostedZoneCommentOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZone is a required field - HostedZone *HostedZone `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateHostedZoneCommentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHostedZoneCommentOutput) GoString() string { - return s.String() -} - -// SetHostedZone sets the HostedZone field's value. -func (s *UpdateHostedZoneCommentOutput) SetHostedZone(v *HostedZone) *UpdateHostedZoneCommentOutput { - s.HostedZone = v - return s -} - -// A complex type that contains information about the traffic policy that you -// want to update the comment for. -type UpdateTrafficPolicyCommentInput struct { - _ struct{} `locationName:"UpdateTrafficPolicyCommentRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The new comment for the specified traffic policy and version. - // - // Comment is a required field - Comment *string `type:"string" required:"true"` - - // The value of Id for the traffic policy that you want to update the comment - // for. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The value of Version for the traffic policy that you want to update the comment - // for. - // - // Version is a required field - Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyCommentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyCommentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTrafficPolicyCommentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTrafficPolicyCommentInput"} - if s.Comment == nil { - invalidParams.Add(request.NewErrParamRequired("Comment")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.Version == nil { - invalidParams.Add(request.NewErrParamRequired("Version")) - } - if s.Version != nil && *s.Version < 1 { - invalidParams.Add(request.NewErrParamMinValue("Version", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *UpdateTrafficPolicyCommentInput) SetComment(v string) *UpdateTrafficPolicyCommentInput { - s.Comment = &v - return s -} - -// SetId sets the Id field's value. -func (s *UpdateTrafficPolicyCommentInput) SetId(v string) *UpdateTrafficPolicyCommentInput { - s.Id = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *UpdateTrafficPolicyCommentInput) SetVersion(v int64) *UpdateTrafficPolicyCommentInput { - s.Version = &v - return s -} - -// A complex type that contains the response information for the traffic policy. -type UpdateTrafficPolicyCommentOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the specified traffic policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyCommentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyCommentOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *UpdateTrafficPolicyCommentOutput) SetTrafficPolicy(v *TrafficPolicy) *UpdateTrafficPolicyCommentOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about the resource record sets that -// you want to update based on a specified traffic policy instance. -type UpdateTrafficPolicyInstanceInput struct { - _ struct{} `locationName:"UpdateTrafficPolicyInstanceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The ID of the traffic policy instance that you want to update. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The TTL that you want Amazon Route 53 to assign to all of the updated resource - // record sets. - // - // TTL is a required field - TTL *int64 `type:"long" required:"true"` - - // The ID of the traffic policy that you want Amazon Route 53 to use to update - // resource record sets for the specified traffic policy instance. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `min:"1" type:"string" required:"true"` - - // The version of the traffic policy that you want Amazon Route 53 to use to - // update resource record sets for the specified traffic policy instance. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTrafficPolicyInstanceInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.TTL == nil { - invalidParams.Add(request.NewErrParamRequired("TTL")) - } - if s.TrafficPolicyId == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyId")) - } - if s.TrafficPolicyId != nil && len(*s.TrafficPolicyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyId", 1)) - } - if s.TrafficPolicyVersion == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyVersion")) - } - if s.TrafficPolicyVersion != nil && *s.TrafficPolicyVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("TrafficPolicyVersion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetId(v string) *UpdateTrafficPolicyInstanceInput { - s.Id = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetTTL(v int64) *UpdateTrafficPolicyInstanceInput { - s.TTL = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetTrafficPolicyId(v string) *UpdateTrafficPolicyInstanceInput { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetTrafficPolicyVersion(v int64) *UpdateTrafficPolicyInstanceInput { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains information about the resource record sets that -// Amazon Route 53 created based on a specified traffic policy. -type UpdateTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the updated traffic policy instance. - // - // TrafficPolicyInstance is a required field - TrafficPolicyInstance *TrafficPolicyInstance `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicyInstance sets the TrafficPolicyInstance field's value. -func (s *UpdateTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficPolicyInstance) *UpdateTrafficPolicyInstanceOutput { - s.TrafficPolicyInstance = v - return s -} - -// (Private hosted zones only) A complex type that contains information about -// an Amazon VPC. -type VPC struct { - _ struct{} `type:"structure"` - - // (Private hosted zones only) The ID of an Amazon VPC. - VPCId *string `type:"string"` - - // (Private hosted zones only) The region in which you created an Amazon VPC. - VPCRegion *string `min:"1" type:"string" enum:"VPCRegion"` -} - -// String returns the string representation -func (s VPC) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s VPC) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *VPC) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "VPC"} - if s.VPCRegion != nil && len(*s.VPCRegion) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VPCRegion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetVPCId sets the VPCId field's value. -func (s *VPC) SetVPCId(v string) *VPC { - s.VPCId = &v - return s -} - -// SetVPCRegion sets the VPCRegion field's value. -func (s *VPC) SetVPCRegion(v string) *VPC { - s.VPCRegion = &v - return s -} - -const ( - // AccountLimitTypeMaxHealthChecksByOwner is a AccountLimitType enum value - AccountLimitTypeMaxHealthChecksByOwner = "MAX_HEALTH_CHECKS_BY_OWNER" - - // AccountLimitTypeMaxHostedZonesByOwner is a AccountLimitType enum value - AccountLimitTypeMaxHostedZonesByOwner = "MAX_HOSTED_ZONES_BY_OWNER" - - // AccountLimitTypeMaxTrafficPolicyInstancesByOwner is a AccountLimitType enum value - AccountLimitTypeMaxTrafficPolicyInstancesByOwner = "MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER" - - // AccountLimitTypeMaxReusableDelegationSetsByOwner is a AccountLimitType enum value - AccountLimitTypeMaxReusableDelegationSetsByOwner = "MAX_REUSABLE_DELEGATION_SETS_BY_OWNER" - - // AccountLimitTypeMaxTrafficPoliciesByOwner is a AccountLimitType enum value - AccountLimitTypeMaxTrafficPoliciesByOwner = "MAX_TRAFFIC_POLICIES_BY_OWNER" -) - -const ( - // ChangeActionCreate is a ChangeAction enum value - ChangeActionCreate = "CREATE" - - // ChangeActionDelete is a ChangeAction enum value - ChangeActionDelete = "DELETE" - - // ChangeActionUpsert is a ChangeAction enum value - ChangeActionUpsert = "UPSERT" -) - -const ( - // ChangeStatusPending is a ChangeStatus enum value - ChangeStatusPending = "PENDING" - - // ChangeStatusInsync is a ChangeStatus enum value - ChangeStatusInsync = "INSYNC" -) - -const ( - // CloudWatchRegionUsEast1 is a CloudWatchRegion enum value - CloudWatchRegionUsEast1 = "us-east-1" - - // CloudWatchRegionUsEast2 is a CloudWatchRegion enum value - CloudWatchRegionUsEast2 = "us-east-2" - - // CloudWatchRegionUsWest1 is a CloudWatchRegion enum value - CloudWatchRegionUsWest1 = "us-west-1" - - // CloudWatchRegionUsWest2 is a CloudWatchRegion enum value - CloudWatchRegionUsWest2 = "us-west-2" - - // CloudWatchRegionCaCentral1 is a CloudWatchRegion enum value - CloudWatchRegionCaCentral1 = "ca-central-1" - - // CloudWatchRegionEuCentral1 is a CloudWatchRegion enum value - CloudWatchRegionEuCentral1 = "eu-central-1" - - // CloudWatchRegionEuWest1 is a CloudWatchRegion enum value - CloudWatchRegionEuWest1 = "eu-west-1" - - // CloudWatchRegionEuWest2 is a CloudWatchRegion enum value - CloudWatchRegionEuWest2 = "eu-west-2" - - // CloudWatchRegionEuWest3 is a CloudWatchRegion enum value - CloudWatchRegionEuWest3 = "eu-west-3" - - // CloudWatchRegionApSouth1 is a CloudWatchRegion enum value - CloudWatchRegionApSouth1 = "ap-south-1" - - // CloudWatchRegionApSoutheast1 is a CloudWatchRegion enum value - CloudWatchRegionApSoutheast1 = "ap-southeast-1" - - // CloudWatchRegionApSoutheast2 is a CloudWatchRegion enum value - CloudWatchRegionApSoutheast2 = "ap-southeast-2" - - // CloudWatchRegionApNortheast1 is a CloudWatchRegion enum value - CloudWatchRegionApNortheast1 = "ap-northeast-1" - - // CloudWatchRegionApNortheast2 is a CloudWatchRegion enum value - CloudWatchRegionApNortheast2 = "ap-northeast-2" - - // CloudWatchRegionApNortheast3 is a CloudWatchRegion enum value - CloudWatchRegionApNortheast3 = "ap-northeast-3" - - // CloudWatchRegionSaEast1 is a CloudWatchRegion enum value - CloudWatchRegionSaEast1 = "sa-east-1" -) - -const ( - // ComparisonOperatorGreaterThanOrEqualToThreshold is a ComparisonOperator enum value - ComparisonOperatorGreaterThanOrEqualToThreshold = "GreaterThanOrEqualToThreshold" - - // ComparisonOperatorGreaterThanThreshold is a ComparisonOperator enum value - ComparisonOperatorGreaterThanThreshold = "GreaterThanThreshold" - - // ComparisonOperatorLessThanThreshold is a ComparisonOperator enum value - ComparisonOperatorLessThanThreshold = "LessThanThreshold" - - // ComparisonOperatorLessThanOrEqualToThreshold is a ComparisonOperator enum value - ComparisonOperatorLessThanOrEqualToThreshold = "LessThanOrEqualToThreshold" -) - -const ( - // HealthCheckRegionUsEast1 is a HealthCheckRegion enum value - HealthCheckRegionUsEast1 = "us-east-1" - - // HealthCheckRegionUsWest1 is a HealthCheckRegion enum value - HealthCheckRegionUsWest1 = "us-west-1" - - // HealthCheckRegionUsWest2 is a HealthCheckRegion enum value - HealthCheckRegionUsWest2 = "us-west-2" - - // HealthCheckRegionEuWest1 is a HealthCheckRegion enum value - HealthCheckRegionEuWest1 = "eu-west-1" - - // HealthCheckRegionApSoutheast1 is a HealthCheckRegion enum value - HealthCheckRegionApSoutheast1 = "ap-southeast-1" - - // HealthCheckRegionApSoutheast2 is a HealthCheckRegion enum value - HealthCheckRegionApSoutheast2 = "ap-southeast-2" - - // HealthCheckRegionApNortheast1 is a HealthCheckRegion enum value - HealthCheckRegionApNortheast1 = "ap-northeast-1" - - // HealthCheckRegionSaEast1 is a HealthCheckRegion enum value - HealthCheckRegionSaEast1 = "sa-east-1" -) - -const ( - // HealthCheckTypeHttp is a HealthCheckType enum value - HealthCheckTypeHttp = "HTTP" - - // HealthCheckTypeHttps is a HealthCheckType enum value - HealthCheckTypeHttps = "HTTPS" - - // HealthCheckTypeHttpStrMatch is a HealthCheckType enum value - HealthCheckTypeHttpStrMatch = "HTTP_STR_MATCH" - - // HealthCheckTypeHttpsStrMatch is a HealthCheckType enum value - HealthCheckTypeHttpsStrMatch = "HTTPS_STR_MATCH" - - // HealthCheckTypeTcp is a HealthCheckType enum value - HealthCheckTypeTcp = "TCP" - - // HealthCheckTypeCalculated is a HealthCheckType enum value - HealthCheckTypeCalculated = "CALCULATED" - - // HealthCheckTypeCloudwatchMetric is a HealthCheckType enum value - HealthCheckTypeCloudwatchMetric = "CLOUDWATCH_METRIC" -) - -const ( - // HostedZoneLimitTypeMaxRrsetsByZone is a HostedZoneLimitType enum value - HostedZoneLimitTypeMaxRrsetsByZone = "MAX_RRSETS_BY_ZONE" - - // HostedZoneLimitTypeMaxVpcsAssociatedByZone is a HostedZoneLimitType enum value - HostedZoneLimitTypeMaxVpcsAssociatedByZone = "MAX_VPCS_ASSOCIATED_BY_ZONE" -) - -const ( - // InsufficientDataHealthStatusHealthy is a InsufficientDataHealthStatus enum value - InsufficientDataHealthStatusHealthy = "Healthy" - - // InsufficientDataHealthStatusUnhealthy is a InsufficientDataHealthStatus enum value - InsufficientDataHealthStatusUnhealthy = "Unhealthy" - - // InsufficientDataHealthStatusLastKnownStatus is a InsufficientDataHealthStatus enum value - InsufficientDataHealthStatusLastKnownStatus = "LastKnownStatus" -) - -const ( - // RRTypeSoa is a RRType enum value - RRTypeSoa = "SOA" - - // RRTypeA is a RRType enum value - RRTypeA = "A" - - // RRTypeTxt is a RRType enum value - RRTypeTxt = "TXT" - - // RRTypeNs is a RRType enum value - RRTypeNs = "NS" - - // RRTypeCname is a RRType enum value - RRTypeCname = "CNAME" - - // RRTypeMx is a RRType enum value - RRTypeMx = "MX" - - // RRTypeNaptr is a RRType enum value - RRTypeNaptr = "NAPTR" - - // RRTypePtr is a RRType enum value - RRTypePtr = "PTR" - - // RRTypeSrv is a RRType enum value - RRTypeSrv = "SRV" - - // RRTypeSpf is a RRType enum value - RRTypeSpf = "SPF" - - // RRTypeAaaa is a RRType enum value - RRTypeAaaa = "AAAA" - - // RRTypeCaa is a RRType enum value - RRTypeCaa = "CAA" -) - -const ( - // ResettableElementNameFullyQualifiedDomainName is a ResettableElementName enum value - ResettableElementNameFullyQualifiedDomainName = "FullyQualifiedDomainName" - - // ResettableElementNameRegions is a ResettableElementName enum value - ResettableElementNameRegions = "Regions" - - // ResettableElementNameResourcePath is a ResettableElementName enum value - ResettableElementNameResourcePath = "ResourcePath" - - // ResettableElementNameChildHealthChecks is a ResettableElementName enum value - ResettableElementNameChildHealthChecks = "ChildHealthChecks" -) - -const ( - // ResourceRecordSetFailoverPrimary is a ResourceRecordSetFailover enum value - ResourceRecordSetFailoverPrimary = "PRIMARY" - - // ResourceRecordSetFailoverSecondary is a ResourceRecordSetFailover enum value - ResourceRecordSetFailoverSecondary = "SECONDARY" -) - -const ( - // ResourceRecordSetRegionUsEast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsEast1 = "us-east-1" - - // ResourceRecordSetRegionUsEast2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsEast2 = "us-east-2" - - // ResourceRecordSetRegionUsWest1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsWest1 = "us-west-1" - - // ResourceRecordSetRegionUsWest2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsWest2 = "us-west-2" - - // ResourceRecordSetRegionCaCentral1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionCaCentral1 = "ca-central-1" - - // ResourceRecordSetRegionEuWest1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuWest1 = "eu-west-1" - - // ResourceRecordSetRegionEuWest2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuWest2 = "eu-west-2" - - // ResourceRecordSetRegionEuWest3 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuWest3 = "eu-west-3" - - // ResourceRecordSetRegionEuCentral1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuCentral1 = "eu-central-1" - - // ResourceRecordSetRegionApSoutheast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApSoutheast1 = "ap-southeast-1" - - // ResourceRecordSetRegionApSoutheast2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApSoutheast2 = "ap-southeast-2" - - // ResourceRecordSetRegionApNortheast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApNortheast1 = "ap-northeast-1" - - // ResourceRecordSetRegionApNortheast2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApNortheast2 = "ap-northeast-2" - - // ResourceRecordSetRegionApNortheast3 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApNortheast3 = "ap-northeast-3" - - // ResourceRecordSetRegionSaEast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionSaEast1 = "sa-east-1" - - // ResourceRecordSetRegionCnNorth1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionCnNorth1 = "cn-north-1" - - // ResourceRecordSetRegionCnNorthwest1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionCnNorthwest1 = "cn-northwest-1" - - // ResourceRecordSetRegionApSouth1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApSouth1 = "ap-south-1" -) - -const ( - // ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet is a ReusableDelegationSetLimitType enum value - ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet = "MAX_ZONES_BY_REUSABLE_DELEGATION_SET" -) - -const ( - // StatisticAverage is a Statistic enum value - StatisticAverage = "Average" - - // StatisticSum is a Statistic enum value - StatisticSum = "Sum" - - // StatisticSampleCount is a Statistic enum value - StatisticSampleCount = "SampleCount" - - // StatisticMaximum is a Statistic enum value - StatisticMaximum = "Maximum" - - // StatisticMinimum is a Statistic enum value - StatisticMinimum = "Minimum" -) - -const ( - // TagResourceTypeHealthcheck is a TagResourceType enum value - TagResourceTypeHealthcheck = "healthcheck" - - // TagResourceTypeHostedzone is a TagResourceType enum value - TagResourceTypeHostedzone = "hostedzone" -) - -const ( - // VPCRegionUsEast1 is a VPCRegion enum value - VPCRegionUsEast1 = "us-east-1" - - // VPCRegionUsEast2 is a VPCRegion enum value - VPCRegionUsEast2 = "us-east-2" - - // VPCRegionUsWest1 is a VPCRegion enum value - VPCRegionUsWest1 = "us-west-1" - - // VPCRegionUsWest2 is a VPCRegion enum value - VPCRegionUsWest2 = "us-west-2" - - // VPCRegionEuWest1 is a VPCRegion enum value - VPCRegionEuWest1 = "eu-west-1" - - // VPCRegionEuWest2 is a VPCRegion enum value - VPCRegionEuWest2 = "eu-west-2" - - // VPCRegionEuWest3 is a VPCRegion enum value - VPCRegionEuWest3 = "eu-west-3" - - // VPCRegionEuCentral1 is a VPCRegion enum value - VPCRegionEuCentral1 = "eu-central-1" - - // VPCRegionApSoutheast1 is a VPCRegion enum value - VPCRegionApSoutheast1 = "ap-southeast-1" - - // VPCRegionApSoutheast2 is a VPCRegion enum value - VPCRegionApSoutheast2 = "ap-southeast-2" - - // VPCRegionApSouth1 is a VPCRegion enum value - VPCRegionApSouth1 = "ap-south-1" - - // VPCRegionApNortheast1 is a VPCRegion enum value - VPCRegionApNortheast1 = "ap-northeast-1" - - // VPCRegionApNortheast2 is a VPCRegion enum value - VPCRegionApNortheast2 = "ap-northeast-2" - - // VPCRegionApNortheast3 is a VPCRegion enum value - VPCRegionApNortheast3 = "ap-northeast-3" - - // VPCRegionSaEast1 is a VPCRegion enum value - VPCRegionSaEast1 = "sa-east-1" - - // VPCRegionCaCentral1 is a VPCRegion enum value - VPCRegionCaCentral1 = "ca-central-1" - - // VPCRegionCnNorth1 is a VPCRegion enum value - VPCRegionCnNorth1 = "cn-north-1" -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go deleted file mode 100644 index efe2d6e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go +++ /dev/null @@ -1,42 +0,0 @@ -package route53 - -import ( - "net/url" - "regexp" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -func init() { - initClient = func(c *client.Client) { - c.Handlers.Build.PushBack(sanitizeURL) - } - - initRequest = func(r *request.Request) { - switch r.Operation.Name { - case opChangeResourceRecordSets: - r.Handlers.UnmarshalError.Remove(restxml.UnmarshalErrorHandler) - r.Handlers.UnmarshalError.PushBack(unmarshalChangeResourceRecordSetsError) - } - } -} - -var reSanitizeURL = regexp.MustCompile(`\/%2F\w+%2F`) - -func sanitizeURL(r *request.Request) { - r.HTTPRequest.URL.RawPath = - reSanitizeURL.ReplaceAllString(r.HTTPRequest.URL.RawPath, "/") - - // Update Path so that it reflects the cleaned RawPath - updated, err := url.Parse(r.HTTPRequest.URL.RawPath) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to clean Route53 URL", err) - return - } - - // Take the updated path so the requests's URL Path has parity with RawPath. - r.HTTPRequest.URL.Path = updated.Path -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go deleted file mode 100644 index 7965fea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package route53 provides the client and types for making API -// requests to Amazon Route 53. -// -// See https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01 for more information on this service. -// -// See route53 package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/ -// -// Using the Client -// -// To contact Amazon Route 53 with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the Amazon Route 53 client Route53 for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/#New -package route53 diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go deleted file mode 100644 index d37e10c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go +++ /dev/null @@ -1,436 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -const ( - - // ErrCodeConcurrentModification for service response error code - // "ConcurrentModification". - // - // Another user submitted a request to create, update, or delete the object - // at the same time that you did. Retry the request. - ErrCodeConcurrentModification = "ConcurrentModification" - - // ErrCodeConflictingDomainExists for service response error code - // "ConflictingDomainExists". - // - // The cause of this error depends on whether you're trying to create a public - // or a private hosted zone: - // - // * Public hosted zone: Two hosted zones that have the same name or that - // have a parent/child relationship (example.com and test.example.com) can't - // have any common name servers. You tried to create a hosted zone that has - // the same name as an existing hosted zone or that's the parent or child - // of an existing hosted zone, and you specified a delegation set that shares - // one or more name servers with the existing hosted zone. For more information, - // see CreateReusableDelegationSet. - // - // * Private hosted zone: You specified an Amazon VPC that you're already - // using for another hosted zone, and the domain that you specified for one - // of the hosted zones is a subdomain of the domain that you specified for - // the other hosted zone. For example, you can't use the same Amazon VPC - // for the hosted zones for example.com and test.example.com. - ErrCodeConflictingDomainExists = "ConflictingDomainExists" - - // ErrCodeConflictingTypes for service response error code - // "ConflictingTypes". - // - // You tried to update a traffic policy instance by using a traffic policy version - // that has a different DNS type than the current type for the instance. You - // specified the type in the JSON document in the CreateTrafficPolicy or CreateTrafficPolicyVersionrequest. - ErrCodeConflictingTypes = "ConflictingTypes" - - // ErrCodeDelegationSetAlreadyCreated for service response error code - // "DelegationSetAlreadyCreated". - // - // A delegation set with the same owner and caller reference combination has - // already been created. - ErrCodeDelegationSetAlreadyCreated = "DelegationSetAlreadyCreated" - - // ErrCodeDelegationSetAlreadyReusable for service response error code - // "DelegationSetAlreadyReusable". - // - // The specified delegation set has already been marked as reusable. - ErrCodeDelegationSetAlreadyReusable = "DelegationSetAlreadyReusable" - - // ErrCodeDelegationSetInUse for service response error code - // "DelegationSetInUse". - // - // The specified delegation contains associated hosted zones which must be deleted - // before the reusable delegation set can be deleted. - ErrCodeDelegationSetInUse = "DelegationSetInUse" - - // ErrCodeDelegationSetNotAvailable for service response error code - // "DelegationSetNotAvailable". - // - // You can create a hosted zone that has the same name as an existing hosted - // zone (example.com is common), but there is a limit to the number of hosted - // zones that have the same name. If you get this error, Amazon Route 53 has - // reached that limit. If you own the domain name and Amazon Route 53 generates - // this error, contact Customer Support. - ErrCodeDelegationSetNotAvailable = "DelegationSetNotAvailable" - - // ErrCodeDelegationSetNotReusable for service response error code - // "DelegationSetNotReusable". - // - // A reusable delegation set with the specified ID does not exist. - ErrCodeDelegationSetNotReusable = "DelegationSetNotReusable" - - // ErrCodeHealthCheckAlreadyExists for service response error code - // "HealthCheckAlreadyExists". - // - // The health check you're attempting to create already exists. Amazon Route - // 53 returns this error when you submit a request that has the following values: - // - // * The same value for CallerReference as an existing health check, and - // one or more values that differ from the existing health check that has - // the same caller reference. - // - // * The same value for CallerReference as a health check that you created - // and later deleted, regardless of the other settings in the request. - ErrCodeHealthCheckAlreadyExists = "HealthCheckAlreadyExists" - - // ErrCodeHealthCheckInUse for service response error code - // "HealthCheckInUse". - // - // This error code is not in use. - ErrCodeHealthCheckInUse = "HealthCheckInUse" - - // ErrCodeHealthCheckVersionMismatch for service response error code - // "HealthCheckVersionMismatch". - // - // The value of HealthCheckVersion in the request doesn't match the value of - // HealthCheckVersion in the health check. - ErrCodeHealthCheckVersionMismatch = "HealthCheckVersionMismatch" - - // ErrCodeHostedZoneAlreadyExists for service response error code - // "HostedZoneAlreadyExists". - // - // The hosted zone you're trying to create already exists. Amazon Route 53 returns - // this error when a hosted zone has already been created with the specified - // CallerReference. - ErrCodeHostedZoneAlreadyExists = "HostedZoneAlreadyExists" - - // ErrCodeHostedZoneNotEmpty for service response error code - // "HostedZoneNotEmpty". - // - // The hosted zone contains resource records that are not SOA or NS records. - ErrCodeHostedZoneNotEmpty = "HostedZoneNotEmpty" - - // ErrCodeHostedZoneNotFound for service response error code - // "HostedZoneNotFound". - // - // The specified HostedZone can't be found. - ErrCodeHostedZoneNotFound = "HostedZoneNotFound" - - // ErrCodeHostedZoneNotPrivate for service response error code - // "HostedZoneNotPrivate". - // - // The specified hosted zone is a public hosted zone, not a private hosted zone. - ErrCodeHostedZoneNotPrivate = "HostedZoneNotPrivate" - - // ErrCodeIncompatibleVersion for service response error code - // "IncompatibleVersion". - // - // The resource you're trying to access is unsupported on this Amazon Route - // 53 endpoint. - ErrCodeIncompatibleVersion = "IncompatibleVersion" - - // ErrCodeInsufficientCloudWatchLogsResourcePolicy for service response error code - // "InsufficientCloudWatchLogsResourcePolicy". - // - // Amazon Route 53 doesn't have the permissions required to create log streams - // and send query logs to log streams. Possible causes include the following: - // - // * There is no resource policy that specifies the log group ARN in the - // value for Resource. - // - // * The resource policy that includes the log group ARN in the value for - // Resource doesn't have the necessary permissions. - // - // * The resource policy hasn't finished propagating yet. - ErrCodeInsufficientCloudWatchLogsResourcePolicy = "InsufficientCloudWatchLogsResourcePolicy" - - // ErrCodeInvalidArgument for service response error code - // "InvalidArgument". - // - // Parameter name is invalid. - ErrCodeInvalidArgument = "InvalidArgument" - - // ErrCodeInvalidChangeBatch for service response error code - // "InvalidChangeBatch". - // - // This exception contains a list of messages that might contain one or more - // error messages. Each error message indicates one error in the change batch. - ErrCodeInvalidChangeBatch = "InvalidChangeBatch" - - // ErrCodeInvalidDomainName for service response error code - // "InvalidDomainName". - // - // The specified domain name is not valid. - ErrCodeInvalidDomainName = "InvalidDomainName" - - // ErrCodeInvalidInput for service response error code - // "InvalidInput". - // - // The input is not valid. - ErrCodeInvalidInput = "InvalidInput" - - // ErrCodeInvalidPaginationToken for service response error code - // "InvalidPaginationToken". - // - // The value that you specified to get the second or subsequent page of results - // is invalid. - ErrCodeInvalidPaginationToken = "InvalidPaginationToken" - - // ErrCodeInvalidTrafficPolicyDocument for service response error code - // "InvalidTrafficPolicyDocument". - // - // The format of the traffic policy document that you specified in the Document - // element is invalid. - ErrCodeInvalidTrafficPolicyDocument = "InvalidTrafficPolicyDocument" - - // ErrCodeInvalidVPCId for service response error code - // "InvalidVPCId". - // - // The VPC ID that you specified either isn't a valid ID or the current account - // is not authorized to access this VPC. - ErrCodeInvalidVPCId = "InvalidVPCId" - - // ErrCodeLastVPCAssociation for service response error code - // "LastVPCAssociation". - // - // The VPC that you're trying to disassociate from the private hosted zone is - // the last VPC that is associated with the hosted zone. Amazon Route 53 doesn't - // support disassociating the last VPC from a hosted zone. - ErrCodeLastVPCAssociation = "LastVPCAssociation" - - // ErrCodeLimitsExceeded for service response error code - // "LimitsExceeded". - // - // This operation can't be completed either because the current account has - // reached the limit on reusable delegation sets that it can create or because - // you've reached the limit on the number of Amazon VPCs that you can associate - // with a private hosted zone. To get the current limit on the number of reusable - // delegation sets, see GetAccountLimit. To get the current limit on the number - // of Amazon VPCs that you can associate with a private hosted zone, see GetHostedZoneLimit. - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeLimitsExceeded = "LimitsExceeded" - - // ErrCodeNoSuchChange for service response error code - // "NoSuchChange". - // - // A change with the specified change ID does not exist. - ErrCodeNoSuchChange = "NoSuchChange" - - // ErrCodeNoSuchCloudWatchLogsLogGroup for service response error code - // "NoSuchCloudWatchLogsLogGroup". - // - // There is no CloudWatch Logs log group with the specified ARN. - ErrCodeNoSuchCloudWatchLogsLogGroup = "NoSuchCloudWatchLogsLogGroup" - - // ErrCodeNoSuchDelegationSet for service response error code - // "NoSuchDelegationSet". - // - // A reusable delegation set with the specified ID does not exist. - ErrCodeNoSuchDelegationSet = "NoSuchDelegationSet" - - // ErrCodeNoSuchGeoLocation for service response error code - // "NoSuchGeoLocation". - // - // Amazon Route 53 doesn't support the specified geolocation. - ErrCodeNoSuchGeoLocation = "NoSuchGeoLocation" - - // ErrCodeNoSuchHealthCheck for service response error code - // "NoSuchHealthCheck". - // - // No health check exists with the ID that you specified in the DeleteHealthCheck - // request. - ErrCodeNoSuchHealthCheck = "NoSuchHealthCheck" - - // ErrCodeNoSuchHostedZone for service response error code - // "NoSuchHostedZone". - // - // No hosted zone exists with the ID that you specified. - ErrCodeNoSuchHostedZone = "NoSuchHostedZone" - - // ErrCodeNoSuchQueryLoggingConfig for service response error code - // "NoSuchQueryLoggingConfig". - // - // There is no DNS query logging configuration with the specified ID. - ErrCodeNoSuchQueryLoggingConfig = "NoSuchQueryLoggingConfig" - - // ErrCodeNoSuchTrafficPolicy for service response error code - // "NoSuchTrafficPolicy". - // - // No traffic policy exists with the specified ID. - ErrCodeNoSuchTrafficPolicy = "NoSuchTrafficPolicy" - - // ErrCodeNoSuchTrafficPolicyInstance for service response error code - // "NoSuchTrafficPolicyInstance". - // - // No traffic policy instance exists with the specified ID. - ErrCodeNoSuchTrafficPolicyInstance = "NoSuchTrafficPolicyInstance" - - // ErrCodeNotAuthorizedException for service response error code - // "NotAuthorizedException". - // - // Associating the specified VPC with the specified hosted zone has not been - // authorized. - ErrCodeNotAuthorizedException = "NotAuthorizedException" - - // ErrCodePriorRequestNotComplete for service response error code - // "PriorRequestNotComplete". - // - // If Amazon Route 53 can't process a request before the next request arrives, - // it will reject subsequent requests for the same hosted zone and return an - // HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly - // for the same request, we recommend that you wait, in intervals of increasing - // duration, before you try the request again. - ErrCodePriorRequestNotComplete = "PriorRequestNotComplete" - - // ErrCodePublicZoneVPCAssociation for service response error code - // "PublicZoneVPCAssociation". - // - // You're trying to associate a VPC with a public hosted zone. Amazon Route - // 53 doesn't support associating a VPC with a public hosted zone. - ErrCodePublicZoneVPCAssociation = "PublicZoneVPCAssociation" - - // ErrCodeQueryLoggingConfigAlreadyExists for service response error code - // "QueryLoggingConfigAlreadyExists". - // - // You can create only one query logging configuration for a hosted zone, and - // a query logging configuration already exists for this hosted zone. - ErrCodeQueryLoggingConfigAlreadyExists = "QueryLoggingConfigAlreadyExists" - - // ErrCodeThrottlingException for service response error code - // "ThrottlingException". - // - // The limit on the number of requests per second was exceeded. - ErrCodeThrottlingException = "ThrottlingException" - - // ErrCodeTooManyHealthChecks for service response error code - // "TooManyHealthChecks". - // - // This health check can't be created because the current account has reached - // the limit on the number of active health checks. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // For information about how to get the current limit for an account, see GetAccountLimit. - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - // - // You have reached the maximum number of active health checks for an AWS account. - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyHealthChecks = "TooManyHealthChecks" - - // ErrCodeTooManyHostedZones for service response error code - // "TooManyHostedZones". - // - // This operation can't be completed either because the current account has - // reached the limit on the number of hosted zones or because you've reached - // the limit on the number of hosted zones that can be associated with a reusable - // delegation set. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // To get the current limit on hosted zones that can be created by an account, - // see GetAccountLimit. - // - // To get the current limit on hosted zones that can be associated with a reusable - // delegation set, see GetReusableDelegationSetLimit. - // - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyHostedZones = "TooManyHostedZones" - - // ErrCodeTooManyTrafficPolicies for service response error code - // "TooManyTrafficPolicies". - // - // This traffic policy can't be created because the current account has reached - // the limit on the number of traffic policies. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // To get the current limit for an account, see GetAccountLimit. - // - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyTrafficPolicies = "TooManyTrafficPolicies" - - // ErrCodeTooManyTrafficPolicyInstances for service response error code - // "TooManyTrafficPolicyInstances". - // - // This traffic policy instance can't be created because the current account - // has reached the limit on the number of traffic policy instances. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // For information about how to get the current limit for an account, see GetAccountLimit. - // - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyTrafficPolicyInstances = "TooManyTrafficPolicyInstances" - - // ErrCodeTooManyTrafficPolicyVersionsForCurrentPolicy for service response error code - // "TooManyTrafficPolicyVersionsForCurrentPolicy". - // - // This traffic policy version can't be created because you've reached the limit - // of 1000 on the number of versions that you can create for the current traffic - // policy. - // - // To create more traffic policy versions, you can use GetTrafficPolicy to get - // the traffic policy document for a specified traffic policy version, and then - // use CreateTrafficPolicy to create a new traffic policy using the traffic - // policy document. - ErrCodeTooManyTrafficPolicyVersionsForCurrentPolicy = "TooManyTrafficPolicyVersionsForCurrentPolicy" - - // ErrCodeTooManyVPCAssociationAuthorizations for service response error code - // "TooManyVPCAssociationAuthorizations". - // - // You've created the maximum number of authorizations that can be created for - // the specified hosted zone. To authorize another VPC to be associated with - // the hosted zone, submit a DeleteVPCAssociationAuthorization request to remove - // an existing authorization. To get a list of existing authorizations, submit - // a ListVPCAssociationAuthorizations request. - ErrCodeTooManyVPCAssociationAuthorizations = "TooManyVPCAssociationAuthorizations" - - // ErrCodeTrafficPolicyAlreadyExists for service response error code - // "TrafficPolicyAlreadyExists". - // - // A traffic policy that has the same value for Name already exists. - ErrCodeTrafficPolicyAlreadyExists = "TrafficPolicyAlreadyExists" - - // ErrCodeTrafficPolicyInUse for service response error code - // "TrafficPolicyInUse". - // - // One or more traffic policy instances were created by using the specified - // traffic policy. - ErrCodeTrafficPolicyInUse = "TrafficPolicyInUse" - - // ErrCodeTrafficPolicyInstanceAlreadyExists for service response error code - // "TrafficPolicyInstanceAlreadyExists". - // - // There is already a traffic policy instance with the specified ID. - ErrCodeTrafficPolicyInstanceAlreadyExists = "TrafficPolicyInstanceAlreadyExists" - - // ErrCodeVPCAssociationAuthorizationNotFound for service response error code - // "VPCAssociationAuthorizationNotFound". - // - // The VPC that you specified is not authorized to be associated with the hosted - // zone. - ErrCodeVPCAssociationAuthorizationNotFound = "VPCAssociationAuthorizationNotFound" - - // ErrCodeVPCAssociationNotFound for service response error code - // "VPCAssociationNotFound". - // - // The specified VPC and hosted zone are not currently associated. - ErrCodeVPCAssociationNotFound = "VPCAssociationNotFound" -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/service.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/service.go deleted file mode 100644 index dd22cb2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/service.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -// Route53 provides the API operation methods for making requests to -// Amazon Route 53. See this package's package overview docs -// for details on the service. -// -// Route53 methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type Route53 struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "route53" // Name of service. - EndpointsID = ServiceName // ID to lookup a service endpoint with. - ServiceID = "Route 53" // ServiceID is a unique identifer of a specific service. -) - -// New creates a new instance of the Route53 client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a Route53 client from just a session. -// svc := route53.New(mySession) -// -// // Create a Route53 client with additional configuration -// svc := route53.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *Route53 { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Route53 { - svc := &Route53{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2013-04-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(restxml.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a Route53 operation and runs any -// custom request initialization. -func (c *Route53) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/unmarshal_error.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/unmarshal_error.go deleted file mode 100644 index 266e9a8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/unmarshal_error.go +++ /dev/null @@ -1,77 +0,0 @@ -package route53 - -import ( - "bytes" - "encoding/xml" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -type baseXMLErrorResponse struct { - XMLName xml.Name -} - -type standardXMLErrorResponse struct { - XMLName xml.Name `xml:"ErrorResponse"` - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -type invalidChangeBatchXMLErrorResponse struct { - XMLName xml.Name `xml:"InvalidChangeBatch"` - Messages []string `xml:"Messages>Message"` -} - -func unmarshalChangeResourceRecordSetsError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - responseBody, err := ioutil.ReadAll(r.HTTPResponse.Body) - - if err != nil { - r.Error = awserr.New("SerializationError", "failed to read Route53 XML error response", err) - return - } - - baseError := &baseXMLErrorResponse{} - - if err := xml.Unmarshal(responseBody, baseError); err != nil { - r.Error = awserr.New("SerializationError", "failed to decode Route53 XML error response", err) - return - } - - switch baseError.XMLName.Local { - case "InvalidChangeBatch": - unmarshalInvalidChangeBatchError(r, responseBody) - default: - r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader(responseBody)) - restxml.UnmarshalError(r) - } -} - -func unmarshalInvalidChangeBatchError(r *request.Request, requestBody []byte) { - resp := &invalidChangeBatchXMLErrorResponse{} - err := xml.Unmarshal(requestBody, resp) - - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode query XML error response", err) - return - } - - const errorCode = "InvalidChangeBatch" - errors := []error{} - - for _, msg := range resp.Messages { - errors = append(errors, awserr.New(errorCode, msg, nil)) - } - - r.Error = awserr.NewRequestFailure( - awserr.NewBatchError(errorCode, "ChangeBatch errors occurred", errors), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go deleted file mode 100644 index 9bd7a9a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// WaitUntilResourceRecordSetsChanged uses the Route 53 API operation -// GetChange to wait for a condition to be met before returning. -// If the condition is not met within the max attempt window, an error will -// be returned. -func (c *Route53) WaitUntilResourceRecordSetsChanged(input *GetChangeInput) error { - return c.WaitUntilResourceRecordSetsChangedWithContext(aws.BackgroundContext(), input) -} - -// WaitUntilResourceRecordSetsChangedWithContext is an extended version of WaitUntilResourceRecordSetsChanged. -// With the support for passing in a context and options to configure the -// Waiter and the underlying request options. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) WaitUntilResourceRecordSetsChangedWithContext(ctx aws.Context, input *GetChangeInput, opts ...request.WaiterOption) error { - w := request.Waiter{ - Name: "WaitUntilResourceRecordSetsChanged", - MaxAttempts: 60, - Delay: request.ConstantWaiterDelay(30 * time.Second), - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathWaiterMatch, Argument: "ChangeInfo.Status", - Expected: "INSYNC", - }, - }, - Logger: c.Config.Logger, - NewRequest: func(opts []request.Option) (*request.Request, error) { - var inCpy *GetChangeInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.GetChangeRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - w.ApplyOptions(opts...) - - return w.WaitWithContext(ctx) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/api.go deleted file mode 100644 index 6f89a79..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ /dev/null @@ -1,2398 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAssumeRole = "AssumeRole" - -// AssumeRoleRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRole operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRole for more information on using the AssumeRole -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssumeRoleRequest method. -// req, resp := client.AssumeRoleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, output *AssumeRoleOutput) { - op := &request.Operation{ - Name: opAssumeRole, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleInput{} - } - - output = &AssumeRoleOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRole API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) that you can use to access -// AWS resources that you might not normally have access to. Typically, you -// use AssumeRole for cross-account access or federation. For a comparison of -// AssumeRole with the other APIs that produce temporary credentials, see Requesting -// Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// Important: You cannot call AssumeRole by using AWS root account credentials; -// access is denied. You must use credentials for an IAM user or an IAM role -// to call AssumeRole. -// -// For cross-account access, imagine that you own multiple accounts and need -// to access resources in each account. You could create long-term credentials -// in each account to access those resources. However, managing all those credentials -// and remembering which one can access which account can be time consuming. -// Instead, you can create one set of long-term credentials in one account and -// then use temporary security credentials to access all the other accounts -// by assuming roles in those accounts. For more information about roles, see -// IAM Roles (Delegation and Federation) (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html) -// in the IAM User Guide. -// -// For federation, you can, for example, grant single sign-on access to the -// AWS Management Console. If you already have an identity and authentication -// system in your corporate network, you don't have to recreate user identities -// in AWS in order to grant those user identities access to AWS. Instead, after -// a user has been authenticated, you call AssumeRole (and specify the role -// with the appropriate permissions) to get temporary security credentials for -// that user. With those temporary security credentials, you construct a sign-in -// URL that users can use to access the console. For more information, see Common -// Scenarios for Temporary Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html#sts-introduction) -// in the IAM User Guide. -// -// By default, the temporary security credentials created by AssumeRole last -// for one hour. However, you can use the optional DurationSeconds parameter -// to specify the duration of your session. You can provide a value from 900 -// seconds (15 minutes) up to the maximum session duration setting for the role. -// This setting can have a value from 1 hour to 12 hours. To learn how to view -// the maximum value for your role, see View the Maximum Session Duration Setting -// for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you -// use the AssumeRole* API operations or the assume-role* CLI operations but -// does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// The temporary security credentials created by AssumeRole can be used to make -// API calls to any AWS service with the following exception: you cannot call -// the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by both the access policy of the role that -// is being assumed, and the policy that you pass. This gives you a way to further -// restrict the permissions for the resulting temporary security credentials. -// You cannot use the passed policy to grant permissions that are in excess -// of those allowed by the access policy of the role that is being assumed. -// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, -// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// To assume a role, your AWS account must be trusted by the role. The trust -// relationship is defined in the role's trust policy when the role is created. -// That trust policy states which accounts are allowed to delegate access to -// this account's role. -// -// The user who wants to access the role must also have permissions delegated -// from the role's administrator. If the user is in a different account than -// the role, then the user's administrator must attach a policy that allows -// the user to call AssumeRole on the ARN of the role in the other account. -// If the user is in the same account as the role, then you can either attach -// a policy to the user (identical to the previous different account user), -// or you can add the user as a principal directly in the role's trust policy. -// In this case, the trust policy acts as the only resource-based policy in -// IAM, and users in the same account as the role do not need explicit permission -// to assume the role. For more information about trust policies and resource-based -// policies, see IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// in the IAM User Guide. -// -// Using MFA with AssumeRole -// -// You can optionally include multi-factor authentication (MFA) information -// when you call AssumeRole. This is useful for cross-account scenarios in which -// you want to make sure that the user who is assuming the role has been authenticated -// using an AWS MFA device. In that scenario, the trust policy of the role being -// assumed includes a condition that tests for MFA authentication; if the caller -// does not include valid MFA information, the request to assume the role is -// denied. The condition in a trust policy that tests for MFA authentication -// might look like the following example. -// -// "Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}} -// -// For more information, see Configuring MFA-Protected API Access (http://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html) -// in the IAM User Guide guide. -// -// To use MFA with AssumeRole, you pass values for the SerialNumber and TokenCode -// parameters. The SerialNumber value identifies the user's hardware or virtual -// MFA device. The TokenCode is the time-based one-time password (TOTP) that -// the MFA devices produces. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRole for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - return out, req.Send() -} - -// AssumeRoleWithContext is the same as AssumeRole with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRole for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithContext(ctx aws.Context, input *AssumeRoleInput, opts ...request.Option) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithSAML = "AssumeRoleWithSAML" - -// AssumeRoleWithSAMLRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithSAML operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRoleWithSAML for more information on using the AssumeRoleWithSAML -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssumeRoleWithSAMLRequest method. -// req, resp := client.AssumeRoleWithSAMLRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *request.Request, output *AssumeRoleWithSAMLOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithSAML, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithSAMLInput{} - } - - output = &AssumeRoleWithSAMLOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRoleWithSAML API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// via a SAML authentication response. This operation provides a mechanism for -// tying an enterprise identity store or directory to role-based AWS access -// without user-specific credentials or configuration. For a comparison of AssumeRoleWithSAML -// with the other APIs that produce temporary credentials, see Requesting Temporary -// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The temporary security credentials returned by this operation consist of -// an access key ID, a secret access key, and a security token. Applications -// can use these temporary security credentials to sign calls to AWS services. -// -// By default, the temporary security credentials created by AssumeRoleWithSAML -// last for one hour. However, you can use the optional DurationSeconds parameter -// to specify the duration of your session. Your role session lasts for the -// duration that you specify, or until the time specified in the SAML authentication -// response's SessionNotOnOrAfter value, whichever is shorter. You can provide -// a DurationSeconds value from 900 seconds (15 minutes) up to the maximum session -// duration setting for the role. This setting can have a value from 1 hour -// to 12 hours. To learn how to view the maximum value for your role, see View -// the Maximum Session Duration Setting for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you -// use the AssumeRole* API operations or the assume-role* CLI operations but -// does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// The temporary security credentials created by AssumeRoleWithSAML can be used -// to make API calls to any AWS service with the following exception: you cannot -// call the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by the intersection of both the access policy -// of the role that is being assumed, and the policy that you pass. This means -// that both policies must grant the permission for the action to be allowed. -// This gives you a way to further restrict the permissions for the resulting -// temporary security credentials. You cannot use the passed policy to grant -// permissions that are in excess of those allowed by the access policy of the -// role that is being assumed. For more information, see Permissions for AssumeRole, -// AssumeRoleWithSAML, and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// Before your application can call AssumeRoleWithSAML, you must configure your -// SAML identity provider (IdP) to issue the claims required by AWS. Additionally, -// you must use AWS Identity and Access Management (IAM) to create a SAML provider -// entity in your AWS account that represents your identity provider, and create -// an IAM role that specifies this SAML provider in its trust policy. -// -// Calling AssumeRoleWithSAML does not require the use of AWS security credentials. -// The identity of the caller is validated by using keys in the metadata document -// that is uploaded for the SAML provider entity for your identity provider. -// -// Calling AssumeRoleWithSAML can result in an entry in your AWS CloudTrail -// logs. The entry includes the value in the NameID element of the SAML assertion. -// We recommend that you use a NameIDType that is not associated with any personally -// identifiable information (PII). For example, you could instead use the Persistent -// Identifier (urn:oasis:names:tc:SAML:2.0:nameid-format:persistent). -// -// For more information, see the following resources: -// -// * About SAML 2.0-based Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) -// in the IAM User Guide. -// -// * Creating SAML Identity Providers (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) -// in the IAM User Guide. -// -// * Configuring a Relying Party and Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html) -// in the IAM User Guide. -// -// * Creating a Role for SAML 2.0 Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithSAML for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by AWS. Get -// a new identity token from the identity provider and then retry the request. -// -// * ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - return out, req.Send() -} - -// AssumeRoleWithSAMLWithContext is the same as AssumeRoleWithSAML with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithSAML for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithSAMLWithContext(ctx aws.Context, input *AssumeRoleWithSAMLInput, opts ...request.Option) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" - -// AssumeRoleWithWebIdentityRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithWebIdentity operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRoleWithWebIdentity for more information on using the AssumeRoleWithWebIdentity -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssumeRoleWithWebIdentityRequest method. -// req, resp := client.AssumeRoleWithWebIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityInput) (req *request.Request, output *AssumeRoleWithWebIdentityOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithWebIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithWebIdentityInput{} - } - - output = &AssumeRoleWithWebIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRoleWithWebIdentity API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// in a mobile or web application with a web identity provider, such as Amazon -// Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible -// identity provider. -// -// For mobile applications, we recommend that you use Amazon Cognito. You can -// use Amazon Cognito with the AWS SDK for iOS (http://aws.amazon.com/sdkforios/) -// and the AWS SDK for Android (http://aws.amazon.com/sdkforandroid/) to uniquely -// identify a user and supply the user with a consistent identity throughout -// the lifetime of an application. -// -// To learn more about Amazon Cognito, see Amazon Cognito Overview (http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840) -// in the AWS SDK for Android Developer Guide guide and Amazon Cognito Overview -// (http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664) -// in the AWS SDK for iOS Developer Guide. -// -// Calling AssumeRoleWithWebIdentity does not require the use of AWS security -// credentials. Therefore, you can distribute an application (for example, on -// mobile devices) that requests temporary security credentials without including -// long-term AWS credentials in the application, and without deploying server-based -// proxy services that use long-term AWS credentials. Instead, the identity -// of the caller is validated by using a token from the web identity provider. -// For a comparison of AssumeRoleWithWebIdentity with the other APIs that produce -// temporary credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The temporary security credentials returned by this API consist of an access -// key ID, a secret access key, and a security token. Applications can use these -// temporary security credentials to sign calls to AWS service APIs. -// -// By default, the temporary security credentials created by AssumeRoleWithWebIdentity -// last for one hour. However, you can use the optional DurationSeconds parameter -// to specify the duration of your session. You can provide a value from 900 -// seconds (15 minutes) up to the maximum session duration setting for the role. -// This setting can have a value from 1 hour to 12 hours. To learn how to view -// the maximum value for your role, see View the Maximum Session Duration Setting -// for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you -// use the AssumeRole* API operations or the assume-role* CLI operations but -// does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// The temporary security credentials created by AssumeRoleWithWebIdentity can -// be used to make API calls to any AWS service with the following exception: -// you cannot call the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by both the access policy of the role that -// is being assumed, and the policy that you pass. This gives you a way to further -// restrict the permissions for the resulting temporary security credentials. -// You cannot use the passed policy to grant permissions that are in excess -// of those allowed by the access policy of the role that is being assumed. -// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, -// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// Before your application can call AssumeRoleWithWebIdentity, you must have -// an identity token from a supported identity provider and create a role that -// the application can assume. The role that your application assumes must trust -// the identity provider that is associated with the identity token. In other -// words, the identity provider must be specified in the role's trust policy. -// -// Calling AssumeRoleWithWebIdentity can result in an entry in your AWS CloudTrail -// logs. The entry includes the Subject (http://openid.net/specs/openid-connect-core-1_0.html#Claims) -// of the provided Web Identity Token. We recommend that you avoid using any -// personally identifiable information (PII) in this field. For example, you -// could instead use a GUID or a pairwise identifier, as suggested in the OIDC -// specification (http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes). -// -// For more information about how to use web identity federation and the AssumeRoleWithWebIdentity -// API, see the following resources: -// -// * Using Web Identity Federation APIs for Mobile Apps (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html) -// and Federation Through a Web-based Identity Provider (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// -// * Web Identity Federation Playground (https://web-identity-federation-playground.s3.amazonaws.com/index.html). -// This interactive website lets you walk through the process of authenticating -// via Login with Amazon, Facebook, or Google, getting temporary security -// credentials, and then using those credentials to make a request to AWS. -// -// -// * AWS SDK for iOS (http://aws.amazon.com/sdkforios/) and AWS SDK for Android -// (http://aws.amazon.com/sdkforandroid/). These toolkits contain sample -// apps that show how to invoke the identity providers, and then how to use -// the information from these providers to get and use temporary security -// credentials. -// -// * Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/web-identity-federation-with-mobile-applications). -// This article discusses web identity federation and shows an example of -// how to use web identity federation to get access to content in Amazon -// S3. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithWebIdentity for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// * ErrCodeIDPCommunicationErrorException "IDPCommunicationError" -// The request could not be fulfilled because the non-AWS identity provider -// (IDP) that was asked to verify the incoming identity token could not be reached. -// This is often a transient error caused by network conditions. Retry the request -// a limited number of times so that you don't exceed the request rate. If the -// error persists, the non-AWS identity provider might be down or not responding. -// -// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by AWS. Get -// a new identity token from the identity provider and then retry the request. -// -// * ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - return out, req.Send() -} - -// AssumeRoleWithWebIdentityWithContext is the same as AssumeRoleWithWebIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithWebIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithWebIdentityWithContext(ctx aws.Context, input *AssumeRoleWithWebIdentityInput, opts ...request.Option) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" - -// DecodeAuthorizationMessageRequest generates a "aws/request.Request" representing the -// client's request for the DecodeAuthorizationMessage operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DecodeAuthorizationMessage for more information on using the DecodeAuthorizationMessage -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DecodeAuthorizationMessageRequest method. -// req, resp := client.DecodeAuthorizationMessageRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessageInput) (req *request.Request, output *DecodeAuthorizationMessageOutput) { - op := &request.Operation{ - Name: opDecodeAuthorizationMessage, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DecodeAuthorizationMessageInput{} - } - - output = &DecodeAuthorizationMessageOutput{} - req = c.newRequest(op, input, output) - return -} - -// DecodeAuthorizationMessage API operation for AWS Security Token Service. -// -// Decodes additional information about the authorization status of a request -// from an encoded message returned in response to an AWS request. -// -// For example, if a user is not authorized to perform an action that he or -// she has requested, the request returns a Client.UnauthorizedOperation response -// (an HTTP 403 response). Some AWS actions additionally return an encoded message -// that can provide details about this authorization failure. -// -// Only certain AWS actions return an encoded authorization message. The documentation -// for an individual action indicates whether that action returns an encoded -// message in addition to returning an HTTP code. -// -// The message is encoded because the details of the authorization status can -// constitute privileged information that the user who requested the action -// should not see. To decode an authorization status message, a user must be -// granted permissions via an IAM policy to request the DecodeAuthorizationMessage -// (sts:DecodeAuthorizationMessage) action. -// -// The decoded message includes the following type of information: -// -// * Whether the request was denied due to an explicit deny or due to the -// absence of an explicit allow. For more information, see Determining Whether -// a Request is Allowed or Denied (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) -// in the IAM User Guide. -// -// * The principal who made the request. -// -// * The requested action. -// -// * The requested resource. -// -// * The values of condition keys in the context of the user's request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation DecodeAuthorizationMessage for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidAuthorizationMessageException "InvalidAuthorizationMessageException" -// The error returned if the message passed to DecodeAuthorizationMessage was -// invalid. This can happen if the token contains invalid characters, such as -// linebreaks. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - return out, req.Send() -} - -// DecodeAuthorizationMessageWithContext is the same as DecodeAuthorizationMessage with the addition of -// the ability to pass a context and additional request options. -// -// See DecodeAuthorizationMessage for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) DecodeAuthorizationMessageWithContext(ctx aws.Context, input *DecodeAuthorizationMessageInput, opts ...request.Option) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetCallerIdentity = "GetCallerIdentity" - -// GetCallerIdentityRequest generates a "aws/request.Request" representing the -// client's request for the GetCallerIdentity operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetCallerIdentity for more information on using the GetCallerIdentity -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetCallerIdentityRequest method. -// req, resp := client.GetCallerIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *request.Request, output *GetCallerIdentityOutput) { - op := &request.Operation{ - Name: opGetCallerIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetCallerIdentityInput{} - } - - output = &GetCallerIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetCallerIdentity API operation for AWS Security Token Service. -// -// Returns details about the IAM identity whose credentials are used to call -// the API. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetCallerIdentity for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - return out, req.Send() -} - -// GetCallerIdentityWithContext is the same as GetCallerIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See GetCallerIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetCallerIdentityWithContext(ctx aws.Context, input *GetCallerIdentityInput, opts ...request.Option) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetFederationToken = "GetFederationToken" - -// GetFederationTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetFederationToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetFederationToken for more information on using the GetFederationToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetFederationTokenRequest method. -// req, resp := client.GetFederationTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *request.Request, output *GetFederationTokenOutput) { - op := &request.Operation{ - Name: opGetFederationToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetFederationTokenInput{} - } - - output = &GetFederationTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetFederationToken API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) for a federated user. -// A typical use is in a proxy application that gets temporary security credentials -// on behalf of distributed applications inside a corporate network. Because -// you must call the GetFederationToken action using the long-term security -// credentials of an IAM user, this call is appropriate in contexts where those -// credentials can be safely stored, usually in a server-based application. -// For a comparison of GetFederationToken with the other APIs that produce temporary -// credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// If you are creating a mobile-based or browser-based app that can authenticate -// users using a web identity provider like Login with Amazon, Facebook, Google, -// or an OpenID Connect-compatible identity provider, we recommend that you -// use Amazon Cognito (http://aws.amazon.com/cognito/) or AssumeRoleWithWebIdentity. -// For more information, see Federation Through a Web-based Identity Provider -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// The GetFederationToken action must be called by using the long-term AWS security -// credentials of an IAM user. You can also call GetFederationToken using the -// security credentials of an AWS root account, but we do not recommended it. -// Instead, we recommend that you create an IAM user for the purpose of the -// proxy application and then attach a policy to the IAM user that limits federated -// users to only the actions and resources that they need access to. For more -// information, see IAM Best Practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) -// in the IAM User Guide. -// -// The temporary security credentials that are obtained by using the long-term -// credentials of an IAM user are valid for the specified duration, from 900 -// seconds (15 minutes) up to a maximium of 129600 seconds (36 hours). The default -// is 43200 seconds (12 hours). Temporary credentials that are obtained by using -// AWS root account credentials have a maximum duration of 3600 seconds (1 hour). -// -// The temporary security credentials created by GetFederationToken can be used -// to make API calls to any AWS service with the following exceptions: -// -// * You cannot use these credentials to call any IAM APIs. -// -// * You cannot call any STS APIs except GetCallerIdentity. -// -// Permissions -// -// The permissions for the temporary security credentials returned by GetFederationToken -// are determined by a combination of the following: -// -// * The policy or policies that are attached to the IAM user whose credentials -// are used to call GetFederationToken. -// -// * The policy that is passed as a parameter in the call. -// -// The passed policy is attached to the temporary security credentials that -// result from the GetFederationToken API call--that is, to the federated user. -// When the federated user makes an AWS request, AWS evaluates the policy attached -// to the federated user in combination with the policy or policies attached -// to the IAM user whose credentials were used to call GetFederationToken. AWS -// allows the federated user's request only when both the federated user and -// the IAM user are explicitly allowed to perform the requested action. The -// passed policy cannot grant more permissions than those that are defined in -// the IAM user policy. -// -// A typical use case is that the permissions of the IAM user whose credentials -// are used to call GetFederationToken are designed to allow access to all the -// actions and resources that any federated user will need. Then, for individual -// users, you pass a policy to the operation that scopes down the permissions -// to a level that's appropriate to that individual user, using a policy that -// allows only a subset of permissions that are granted to the IAM user. -// -// If you do not pass a policy, the resulting temporary security credentials -// have no effective permissions. The only exception is when the temporary security -// credentials are used to access a resource that has a resource-based policy -// that specifically allows the federated user to access the resource. -// -// For more information about how permissions work, see Permissions for GetFederationToken -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html). -// For information about using GetFederationToken to create temporary security -// credentials, see GetFederationToken—Federation Through a Custom Identity -// Broker (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetFederationToken for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - return out, req.Send() -} - -// GetFederationTokenWithContext is the same as GetFederationToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetFederationToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetFederationTokenWithContext(ctx aws.Context, input *GetFederationTokenInput, opts ...request.Option) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetSessionToken = "GetSessionToken" - -// GetSessionTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetSessionToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetSessionToken for more information on using the GetSessionToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetSessionTokenRequest method. -// req, resp := client.GetSessionTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request.Request, output *GetSessionTokenOutput) { - op := &request.Operation{ - Name: opGetSessionToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetSessionTokenInput{} - } - - output = &GetSessionTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetSessionToken API operation for AWS Security Token Service. -// -// Returns a set of temporary credentials for an AWS account or IAM user. The -// credentials consist of an access key ID, a secret access key, and a security -// token. Typically, you use GetSessionToken if you want to use MFA to protect -// programmatic calls to specific AWS APIs like Amazon EC2 StopInstances. MFA-enabled -// IAM users would need to call GetSessionToken and submit an MFA code that -// is associated with their MFA device. Using the temporary security credentials -// that are returned from the call, IAM users can then make programmatic calls -// to APIs that require MFA authentication. If you do not supply a correct MFA -// code, then the API returns an access denied error. For a comparison of GetSessionToken -// with the other APIs that produce temporary credentials, see Requesting Temporary -// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The GetSessionToken action must be called by using the long-term AWS security -// credentials of the AWS account or an IAM user. Credentials that are created -// by IAM users are valid for the duration that you specify, from 900 seconds -// (15 minutes) up to a maximum of 129600 seconds (36 hours), with a default -// of 43200 seconds (12 hours); credentials that are created by using account -// credentials can range from 900 seconds (15 minutes) up to a maximum of 3600 -// seconds (1 hour), with a default of 1 hour. -// -// The temporary security credentials created by GetSessionToken can be used -// to make API calls to any AWS service with the following exceptions: -// -// * You cannot call any IAM APIs unless MFA authentication information is -// included in the request. -// -// * You cannot call any STS API exceptAssumeRole or GetCallerIdentity. -// -// We recommend that you do not call GetSessionToken with root account credentials. -// Instead, follow our best practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users) -// by creating one or more IAM users, giving them the necessary permissions, -// and using IAM users for everyday interaction with AWS. -// -// The permissions associated with the temporary security credentials returned -// by GetSessionToken are based on the permissions associated with account or -// IAM user whose credentials are used to call the action. If GetSessionToken -// is called using root account credentials, the temporary credentials have -// root account permissions. Similarly, if GetSessionToken is called using the -// credentials of an IAM user, the temporary credentials have the same permissions -// as the IAM user. -// -// For more information about using GetSessionToken to create temporary credentials, -// go to Temporary Credentials for Users in Untrusted Environments (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetSessionToken for usage and error information. -// -// Returned Error Codes: -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - return out, req.Send() -} - -// GetSessionTokenWithContext is the same as GetSessionToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetSessionToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionTokenInput, opts ...request.Option) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type AssumeRoleInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) up to the maximum session duration setting for the role. - // This setting can have a value from 1 hour to 12 hours. If you specify a value - // higher than this setting, the operation fails. For example, if you specify - // a session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. To learn how to view the maximum - // value for your role, see View the Maximum Session Duration Setting for a - // Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. - // - // By default, the value is set to 3600 seconds. - // - // The DurationSeconds parameter is separate from the duration of a console - // session that you might request using the returned credentials. The request - // to the federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // A unique identifier that is used by third parties when assuming roles in - // their customers' accounts. For each role that the third party can assume, - // they should instruct their customers to ensure the role's trust policy checks - // for the external ID that the third party generated. Each time the third party - // assumes the role, they should pass the customer's external ID. The external - // ID is useful in order to help third parties bind a role to the customer who - // created it. For more information about the external ID, see How to Use an - // External ID When Granting Access to Your AWS Resources to a Third Party (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) - // in the IAM User Guide. - // - // The regex used to validated this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@:/- - ExternalId *string `min:"2" type:"string"` - - // An IAM policy in JSON format. - // - // This parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both (the intersection of) the access policy of the role that - // is being assumed, and the policy that you pass. This gives you a way to further - // restrict the permissions for the resulting temporary security credentials. - // You cannot use the passed policy to grant permissions that are in excess - // of those allowed by the access policy of the role that is being assumed. - // For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, - // and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the role to assume. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // An identifier for the assumed role session. - // - // Use the role session name to uniquely identify a session when the same role - // is assumed by different principals or for different reasons. In cross-account - // scenarios, the role session name is visible to, and can be logged by the - // account that owns the role. The role session name is also used in the ARN - // of the assumed role principal. This means that subsequent cross-account API - // requests using the temporary security credentials will expose the role session - // name to the external account in their CloudTrail logs. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - SerialNumber *string `min:"9" type:"string"` - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s AssumeRoleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.ExternalId != nil && len(*s.ExternalId) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ExternalId", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleInput) SetDurationSeconds(v int64) *AssumeRoleInput { - s.DurationSeconds = &v - return s -} - -// SetExternalId sets the ExternalId field's value. -func (s *AssumeRoleInput) SetExternalId(v string) *AssumeRoleInput { - s.ExternalId = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleInput) SetPolicy(v string) *AssumeRoleInput { - s.Policy = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleInput) SetRoleArn(v string) *AssumeRoleInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleInput) SetRoleSessionName(v string) *AssumeRoleInput { - s.RoleSessionName = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *AssumeRoleInput) SetSerialNumber(v string) *AssumeRoleInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *AssumeRoleInput) SetTokenCode(v string) *AssumeRoleInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful AssumeRole request, including temporary -// AWS credentials that can be used to make AWS requests. -type AssumeRoleOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. - // For example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName - // that you specified when you called AssumeRole. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation -func (s AssumeRoleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleOutput { - s.AssumedRoleUser = v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleOutput) SetCredentials(v *Credentials) *AssumeRoleOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleOutput) SetPackedPolicySize(v int64) *AssumeRoleOutput { - s.PackedPolicySize = &v - return s -} - -type AssumeRoleWithSAMLInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. Your role session lasts for - // the duration that you specify for the DurationSeconds parameter, or until - // the time specified in the SAML authentication response's SessionNotOnOrAfter - // value, whichever is shorter. You can provide a DurationSeconds value from - // 900 seconds (15 minutes) up to the maximum session duration setting for the - // role. This setting can have a value from 1 hour to 12 hours. If you specify - // a value higher than this setting, the operation fails. For example, if you - // specify a session duration of 12 hours, but your administrator set the maximum - // session duration to 6 hours, your operation fails. To learn how to view the - // maximum value for your role, see View the Maximum Session Duration Setting - // for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. - // - // By default, the value is set to 3600 seconds. - // - // The DurationSeconds parameter is separate from the duration of a console - // session that you might request using the returned credentials. The request - // to the federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format. - // - // The policy parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both the access policy of the role that is being assumed, - // and the policy that you pass. This gives you a way to further restrict the - // permissions for the resulting temporary security credentials. You cannot - // use the passed policy to grant permissions that are in excess of those allowed - // by the access policy of the role that is being assumed. For more information, - // Permissions for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity - // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes - // the IdP. - // - // PrincipalArn is a required field - PrincipalArn *string `min:"20" type:"string" required:"true"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // The base-64 encoded SAML authentication response provided by the IdP. - // - // For more information, see Configuring a Relying Party and Adding Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) - // in the Using IAM guide. - // - // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumeRoleWithSAMLInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithSAMLInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithSAMLInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithSAMLInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.PrincipalArn == nil { - invalidParams.Add(request.NewErrParamRequired("PrincipalArn")) - } - if s.PrincipalArn != nil && len(*s.PrincipalArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("PrincipalArn", 20)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.SAMLAssertion == nil { - invalidParams.Add(request.NewErrParamRequired("SAMLAssertion")) - } - if s.SAMLAssertion != nil && len(*s.SAMLAssertion) < 4 { - invalidParams.Add(request.NewErrParamMinLen("SAMLAssertion", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithSAMLInput) SetDurationSeconds(v int64) *AssumeRoleWithSAMLInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithSAMLInput) SetPolicy(v string) *AssumeRoleWithSAMLInput { - s.Policy = &v - return s -} - -// SetPrincipalArn sets the PrincipalArn field's value. -func (s *AssumeRoleWithSAMLInput) SetPrincipalArn(v string) *AssumeRoleWithSAMLInput { - s.PrincipalArn = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithSAMLInput) SetRoleArn(v string) *AssumeRoleWithSAMLInput { - s.RoleArn = &v - return s -} - -// SetSAMLAssertion sets the SAMLAssertion field's value. -func (s *AssumeRoleWithSAMLInput) SetSAMLAssertion(v string) *AssumeRoleWithSAMLInput { - s.SAMLAssertion = &v - return s -} - -// Contains the response to a successful AssumeRoleWithSAML request, including -// temporary AWS credentials that can be used to make AWS requests. -type AssumeRoleWithSAMLOutput struct { - _ struct{} `type:"structure"` - - // The identifiers for the temporary security credentials that the operation - // returns. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The value of the Recipient attribute of the SubjectConfirmationData element - // of the SAML assertion. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // The value of the Issuer element of the SAML assertion. - Issuer *string `type:"string"` - - // A hash value based on the concatenation of the Issuer response value, the - // AWS account ID, and the friendly name (the last part of the ARN) of the SAML - // provider in IAM. The combination of NameQualifier and Subject can be used - // to uniquely identify a federated user. - // - // The following pseudocode shows how the hash value is calculated: - // - // BASE64 ( SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" - // ) ) - NameQualifier *string `type:"string"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The value of the NameID element in the Subject element of the SAML assertion. - Subject *string `type:"string"` - - // The format of the name ID, as defined by the Format attribute in the NameID - // element of the SAML assertion. Typical examples of the format are transient - // or persistent. - // - // If the format includes the prefix urn:oasis:names:tc:SAML:2.0:nameid-format, - // that prefix is removed. For example, urn:oasis:names:tc:SAML:2.0:nameid-format:transient - // is returned as transient. If the format includes any other prefix, the format - // is returned with no modifications. - SubjectType *string `type:"string"` -} - -// String returns the string representation -func (s AssumeRoleWithSAMLOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithSAMLOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithSAMLOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithSAMLOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithSAMLOutput) SetAudience(v string) *AssumeRoleWithSAMLOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithSAMLOutput) SetCredentials(v *Credentials) *AssumeRoleWithSAMLOutput { - s.Credentials = v - return s -} - -// SetIssuer sets the Issuer field's value. -func (s *AssumeRoleWithSAMLOutput) SetIssuer(v string) *AssumeRoleWithSAMLOutput { - s.Issuer = &v - return s -} - -// SetNameQualifier sets the NameQualifier field's value. -func (s *AssumeRoleWithSAMLOutput) SetNameQualifier(v string) *AssumeRoleWithSAMLOutput { - s.NameQualifier = &v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithSAMLOutput) SetPackedPolicySize(v int64) *AssumeRoleWithSAMLOutput { - s.PackedPolicySize = &v - return s -} - -// SetSubject sets the Subject field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubject(v string) *AssumeRoleWithSAMLOutput { - s.Subject = &v - return s -} - -// SetSubjectType sets the SubjectType field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubjectType(v string) *AssumeRoleWithSAMLOutput { - s.SubjectType = &v - return s -} - -type AssumeRoleWithWebIdentityInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) up to the maximum session duration setting for the role. - // This setting can have a value from 1 hour to 12 hours. If you specify a value - // higher than this setting, the operation fails. For example, if you specify - // a session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. To learn how to view the maximum - // value for your role, see View the Maximum Session Duration Setting for a - // Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. - // - // By default, the value is set to 3600 seconds. - // - // The DurationSeconds parameter is separate from the duration of a console - // session that you might request using the returned credentials. The request - // to the federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format. - // - // The policy parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both the access policy of the role that is being assumed, - // and the policy that you pass. This gives you a way to further restrict the - // permissions for the resulting temporary security credentials. You cannot - // use the passed policy to grant permissions that are in excess of those allowed - // by the access policy of the role that is being assumed. For more information, - // see Permissions for AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string `min:"1" type:"string"` - - // The fully qualified host component of the domain name of the identity provider. - // - // Specify this value only for OAuth 2.0 access tokens. Currently www.amazon.com - // and graph.facebook.com are the only supported identity providers for OAuth - // 2.0 access tokens. Do not include URL schemes and port numbers. - // - // Do not specify this value for OpenID Connect ID tokens. - ProviderId *string `min:"4" type:"string"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // An identifier for the assumed role session. Typically, you pass the name - // or identifier that is associated with the user who is using your application. - // That way, the temporary security credentials that your application will use - // are associated with that user. This session name is included as part of the - // ARN and assumed role ID in the AssumedRoleUser response element. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // The OAuth 2.0 access token or OpenID Connect ID token that is provided by - // the identity provider. Your application must get this token by authenticating - // the user who is using your application with a web identity provider before - // the application makes an AssumeRoleWithWebIdentity call. - // - // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumeRoleWithWebIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithWebIdentityInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithWebIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithWebIdentityInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.ProviderId != nil && len(*s.ProviderId) < 4 { - invalidParams.Add(request.NewErrParamMinLen("ProviderId", 4)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.WebIdentityToken == nil { - invalidParams.Add(request.NewErrParamRequired("WebIdentityToken")) - } - if s.WebIdentityToken != nil && len(*s.WebIdentityToken) < 4 { - invalidParams.Add(request.NewErrParamMinLen("WebIdentityToken", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithWebIdentityInput) SetDurationSeconds(v int64) *AssumeRoleWithWebIdentityInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithWebIdentityInput) SetPolicy(v string) *AssumeRoleWithWebIdentityInput { - s.Policy = &v - return s -} - -// SetProviderId sets the ProviderId field's value. -func (s *AssumeRoleWithWebIdentityInput) SetProviderId(v string) *AssumeRoleWithWebIdentityInput { - s.ProviderId = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleArn(v string) *AssumeRoleWithWebIdentityInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleSessionName(v string) *AssumeRoleWithWebIdentityInput { - s.RoleSessionName = &v - return s -} - -// SetWebIdentityToken sets the WebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityInput) SetWebIdentityToken(v string) *AssumeRoleWithWebIdentityInput { - s.WebIdentityToken = &v - return s -} - -// Contains the response to a successful AssumeRoleWithWebIdentity request, -// including temporary AWS credentials that can be used to make AWS requests. -type AssumeRoleWithWebIdentityOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. - // For example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName - // that you specified when you called AssumeRole. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The intended audience (also known as client ID) of the web identity token. - // This is traditionally the client identifier issued to the application that - // requested the web identity token. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The issuing authority of the web identity token presented. For OpenID Connect - // ID Tokens this contains the value of the iss field. For OAuth 2.0 access - // tokens, this contains the value of the ProviderId parameter that was passed - // in the AssumeRoleWithWebIdentity request. - Provider *string `type:"string"` - - // The unique user identifier that is returned by the identity provider. This - // identifier is associated with the WebIdentityToken that was submitted with - // the AssumeRoleWithWebIdentity call. The identifier is typically unique to - // the user and the application that acquired the WebIdentityToken (pairwise - // identifier). For OpenID Connect ID tokens, this field contains the value - // returned by the identity provider as the token's sub (Subject) claim. - SubjectFromWebIdentityToken *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s AssumeRoleWithWebIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithWebIdentityOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithWebIdentityOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAudience(v string) *AssumeRoleWithWebIdentityOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetCredentials(v *Credentials) *AssumeRoleWithWebIdentityOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetPackedPolicySize(v int64) *AssumeRoleWithWebIdentityOutput { - s.PackedPolicySize = &v - return s -} - -// SetProvider sets the Provider field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetProvider(v string) *AssumeRoleWithWebIdentityOutput { - s.Provider = &v - return s -} - -// SetSubjectFromWebIdentityToken sets the SubjectFromWebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetSubjectFromWebIdentityToken(v string) *AssumeRoleWithWebIdentityOutput { - s.SubjectFromWebIdentityToken = &v - return s -} - -// The identifiers for the temporary security credentials that the operation -// returns. -type AssumedRoleUser struct { - _ struct{} `type:"structure"` - - // The ARN of the temporary security credentials that are returned from the - // AssumeRole action. For more information about ARNs and how to use them in - // policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in Using IAM. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // A unique identifier that contains the role ID and the role session name of - // the role that is being assumed. The role ID is generated by AWS when the - // role is created. - // - // AssumedRoleId is a required field - AssumedRoleId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumedRoleUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumedRoleUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *AssumedRoleUser) SetArn(v string) *AssumedRoleUser { - s.Arn = &v - return s -} - -// SetAssumedRoleId sets the AssumedRoleId field's value. -func (s *AssumedRoleUser) SetAssumedRoleId(v string) *AssumedRoleUser { - s.AssumedRoleId = &v - return s -} - -// AWS credentials for API authentication. -type Credentials struct { - _ struct{} `type:"structure"` - - // The access key ID that identifies the temporary security credentials. - // - // AccessKeyId is a required field - AccessKeyId *string `min:"16" type:"string" required:"true"` - - // The date on which the current credentials expire. - // - // Expiration is a required field - Expiration *time.Time `type:"timestamp" required:"true"` - - // The secret access key that can be used to sign requests. - // - // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true"` - - // The token that users must pass to the service API to use the temporary credentials. - // - // SessionToken is a required field - SessionToken *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s Credentials) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Credentials) GoString() string { - return s.String() -} - -// SetAccessKeyId sets the AccessKeyId field's value. -func (s *Credentials) SetAccessKeyId(v string) *Credentials { - s.AccessKeyId = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *Credentials) SetExpiration(v time.Time) *Credentials { - s.Expiration = &v - return s -} - -// SetSecretAccessKey sets the SecretAccessKey field's value. -func (s *Credentials) SetSecretAccessKey(v string) *Credentials { - s.SecretAccessKey = &v - return s -} - -// SetSessionToken sets the SessionToken field's value. -func (s *Credentials) SetSessionToken(v string) *Credentials { - s.SessionToken = &v - return s -} - -type DecodeAuthorizationMessageInput struct { - _ struct{} `type:"structure"` - - // The encoded message that was returned with the response. - // - // EncodedMessage is a required field - EncodedMessage *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DecodeAuthorizationMessageInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DecodeAuthorizationMessageInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DecodeAuthorizationMessageInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DecodeAuthorizationMessageInput"} - if s.EncodedMessage == nil { - invalidParams.Add(request.NewErrParamRequired("EncodedMessage")) - } - if s.EncodedMessage != nil && len(*s.EncodedMessage) < 1 { - invalidParams.Add(request.NewErrParamMinLen("EncodedMessage", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEncodedMessage sets the EncodedMessage field's value. -func (s *DecodeAuthorizationMessageInput) SetEncodedMessage(v string) *DecodeAuthorizationMessageInput { - s.EncodedMessage = &v - return s -} - -// A document that contains additional information about the authorization status -// of a request from an encoded message that is returned in response to an AWS -// request. -type DecodeAuthorizationMessageOutput struct { - _ struct{} `type:"structure"` - - // An XML document that contains the decoded message. - DecodedMessage *string `type:"string"` -} - -// String returns the string representation -func (s DecodeAuthorizationMessageOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DecodeAuthorizationMessageOutput) GoString() string { - return s.String() -} - -// SetDecodedMessage sets the DecodedMessage field's value. -func (s *DecodeAuthorizationMessageOutput) SetDecodedMessage(v string) *DecodeAuthorizationMessageOutput { - s.DecodedMessage = &v - return s -} - -// Identifiers for the federated user that is associated with the credentials. -type FederatedUser struct { - _ struct{} `type:"structure"` - - // The ARN that specifies the federated user that is associated with the credentials. - // For more information about ARNs and how to use them in policies, see IAM - // Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in Using IAM. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // The string that identifies the federated user associated with the credentials, - // similar to the unique ID of an IAM user. - // - // FederatedUserId is a required field - FederatedUserId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation -func (s FederatedUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s FederatedUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *FederatedUser) SetArn(v string) *FederatedUser { - s.Arn = &v - return s -} - -// SetFederatedUserId sets the FederatedUserId field's value. -func (s *FederatedUser) SetFederatedUserId(v string) *FederatedUser { - s.FederatedUserId = &v - return s -} - -type GetCallerIdentityInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetCallerIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCallerIdentityInput) GoString() string { - return s.String() -} - -// Contains the response to a successful GetCallerIdentity request, including -// information about the entity making the request. -type GetCallerIdentityOutput struct { - _ struct{} `type:"structure"` - - // The AWS account ID number of the account that owns or contains the calling - // entity. - Account *string `type:"string"` - - // The AWS ARN associated with the calling entity. - Arn *string `min:"20" type:"string"` - - // The unique identifier of the calling entity. The exact value depends on the - // type of entity making the call. The values returned are those listed in the - // aws:userid column in the Principal table (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable) - // found on the Policy Variables reference page in the IAM User Guide. - UserId *string `type:"string"` -} - -// String returns the string representation -func (s GetCallerIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCallerIdentityOutput) GoString() string { - return s.String() -} - -// SetAccount sets the Account field's value. -func (s *GetCallerIdentityOutput) SetAccount(v string) *GetCallerIdentityOutput { - s.Account = &v - return s -} - -// SetArn sets the Arn field's value. -func (s *GetCallerIdentityOutput) SetArn(v string) *GetCallerIdentityOutput { - s.Arn = &v - return s -} - -// SetUserId sets the UserId field's value. -func (s *GetCallerIdentityOutput) SetUserId(v string) *GetCallerIdentityOutput { - s.UserId = &v - return s -} - -type GetFederationTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the session should last. Acceptable durations - // for federation sessions range from 900 seconds (15 minutes) to 129600 seconds - // (36 hours), with 43200 seconds (12 hours) as the default. Sessions obtained - // using AWS account (root) credentials are restricted to a maximum of 3600 - // seconds (one hour). If the specified duration is longer than one hour, the - // session obtained by using AWS account (root) credentials defaults to one - // hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // The name of the federated user. The name is used as an identifier for the - // temporary security credentials (such as Bob). For example, you can reference - // the federated user name in a resource-based policy, such as in an Amazon - // S3 bucket policy. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // Name is a required field - Name *string `min:"2" type:"string" required:"true"` - - // An IAM policy in JSON format that is passed with the GetFederationToken call - // and evaluated along with the policy or policies that are attached to the - // IAM user whose credentials are used to call GetFederationToken. The passed - // policy is used to scope down the permissions that are available to the IAM - // user, by allowing only a subset of the permissions that are granted to the - // IAM user. The passed policy cannot grant more permissions than those granted - // to the IAM user. The final permissions for the federated user are the most - // restrictive set based on the intersection of the passed policy and the IAM - // user policy. - // - // If you do not pass a policy, the resulting temporary security credentials - // have no effective permissions. The only exception is when the temporary security - // credentials are used to access a resource that has a resource-based policy - // that specifically allows the federated user to access the resource. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - // - // For more information about how permissions work, see Permissions for GetFederationToken - // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html). - Policy *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GetFederationTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetFederationTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetFederationTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFederationTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Name", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetFederationTokenInput) SetDurationSeconds(v int64) *GetFederationTokenInput { - s.DurationSeconds = &v - return s -} - -// SetName sets the Name field's value. -func (s *GetFederationTokenInput) SetName(v string) *GetFederationTokenInput { - s.Name = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *GetFederationTokenInput) SetPolicy(v string) *GetFederationTokenInput { - s.Policy = &v - return s -} - -// Contains the response to a successful GetFederationToken request, including -// temporary AWS credentials that can be used to make AWS requests. -type GetFederationTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // Identifiers for the federated user associated with the credentials (such - // as arn:aws:sts::123456789012:federated-user/Bob or 123456789012:Bob). You - // can use the federated user's ARN in your resource-based policies, such as - // an Amazon S3 bucket policy. - FederatedUser *FederatedUser `type:"structure"` - - // A percentage value indicating the size of the policy in packed form. The - // service rejects policies for which the packed size is greater than 100 percent - // of the allowed value. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation -func (s GetFederationTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetFederationTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetFederationTokenOutput) SetCredentials(v *Credentials) *GetFederationTokenOutput { - s.Credentials = v - return s -} - -// SetFederatedUser sets the FederatedUser field's value. -func (s *GetFederationTokenOutput) SetFederatedUser(v *FederatedUser) *GetFederationTokenOutput { - s.FederatedUser = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *GetFederationTokenOutput) SetPackedPolicySize(v int64) *GetFederationTokenOutput { - s.PackedPolicySize = &v - return s -} - -type GetSessionTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the credentials should remain valid. Acceptable - // durations for IAM user sessions range from 900 seconds (15 minutes) to 129600 - // seconds (36 hours), with 43200 seconds (12 hours) as the default. Sessions - // for AWS account owners are restricted to a maximum of 3600 seconds (one hour). - // If the duration is longer than one hour, the session for AWS account owners - // defaults to one hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // The identification number of the MFA device that is associated with the IAM - // user who is making the GetSessionToken call. Specify this value if the IAM - // user has a policy that requires MFA authentication. The value is either the - // serial number for a hardware device (such as GAHT12345678) or an Amazon Resource - // Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - // You can find the device for an IAM user by going to the AWS Management Console - // and viewing the user's security credentials. - // - // The regex used to validated this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@:/- - SerialNumber *string `min:"9" type:"string"` - - // The value provided by the MFA device, if MFA is required. If any policy requires - // the IAM user to submit an MFA code, specify this value. If MFA authentication - // is required, and the user does not provide a code when requesting a set of - // temporary security credentials, the user will receive an "access denied" - // response when requesting resources that require MFA authentication. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s GetSessionTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetSessionTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetSessionTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetSessionTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetSessionTokenInput) SetDurationSeconds(v int64) *GetSessionTokenInput { - s.DurationSeconds = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *GetSessionTokenInput) SetSerialNumber(v string) *GetSessionTokenInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *GetSessionTokenInput) SetTokenCode(v string) *GetSessionTokenInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful GetSessionToken request, including -// temporary AWS credentials that can be used to make AWS requests. -type GetSessionTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` -} - -// String returns the string representation -func (s GetSessionTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetSessionTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetSessionTokenOutput) SetCredentials(v *Credentials) *GetSessionTokenOutput { - s.Credentials = v - return s -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go deleted file mode 100644 index 4010cc7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go +++ /dev/null @@ -1,12 +0,0 @@ -package sts - -import "github.com/aws/aws-sdk-go/aws/request" - -func init() { - initRequest = func(r *request.Request) { - switch r.Operation.Name { - case opAssumeRoleWithSAML, opAssumeRoleWithWebIdentity: - r.Handlers.Sign.Clear() // these operations are unsigned - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go deleted file mode 100644 index ef681ab..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package sts provides the client and types for making API -// requests to AWS Security Token Service. -// -// The AWS Security Token Service (STS) is a web service that enables you to -// request temporary, limited-privilege credentials for AWS Identity and Access -// Management (IAM) users or for users that you authenticate (federated users). -// This guide provides descriptions of the STS API. For more detailed information -// about using this service, go to Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). -// -// As an alternative to using the API, you can use one of the AWS SDKs, which -// consist of libraries and sample code for various programming languages and -// platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient -// way to create programmatic access to STS. For example, the SDKs take care -// of cryptographically signing requests, managing errors, and retrying requests -// automatically. For information about the AWS SDKs, including how to download -// and install them, see the Tools for Amazon Web Services page (http://aws.amazon.com/tools/). -// -// For information about setting up signatures and authorization through the -// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) -// in the AWS General Reference. For general information about the Query API, -// go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in Using IAM. For information about using security tokens with other AWS -// products, go to AWS Services That Work with IAM (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) -// in the IAM User Guide. -// -// If you're new to AWS and need additional technical information about a specific -// AWS product, you can find the product's technical documentation at http://aws.amazon.com/documentation/ -// (http://aws.amazon.com/documentation/). -// -// Endpoints -// -// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com -// that maps to the US East (N. Virginia) region. Additional regions are available -// and are activated by default. For more information, see Activating and Deactivating -// AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// For information about STS endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) -// in the AWS General Reference. -// -// Recording API requests -// -// STS supports AWS CloudTrail, which is a service that records AWS calls for -// your AWS account and delivers log files to an Amazon S3 bucket. By using -// information collected by CloudTrail, you can determine what requests were -// successfully made to STS, who made the request, when it was made, and so -// on. To learn more about CloudTrail, including how to turn it on and find -// your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). -// -// See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. -// -// See sts package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/ -// -// Using the Client -// -// To contact AWS Security Token Service with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the AWS Security Token Service client STS for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#New -package sts diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go deleted file mode 100644 index e24884e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -const ( - - // ErrCodeExpiredTokenException for service response error code - // "ExpiredTokenException". - // - // The web identity token that was passed is expired or is not valid. Get a - // new identity token from the identity provider and then retry the request. - ErrCodeExpiredTokenException = "ExpiredTokenException" - - // ErrCodeIDPCommunicationErrorException for service response error code - // "IDPCommunicationError". - // - // The request could not be fulfilled because the non-AWS identity provider - // (IDP) that was asked to verify the incoming identity token could not be reached. - // This is often a transient error caused by network conditions. Retry the request - // a limited number of times so that you don't exceed the request rate. If the - // error persists, the non-AWS identity provider might be down or not responding. - ErrCodeIDPCommunicationErrorException = "IDPCommunicationError" - - // ErrCodeIDPRejectedClaimException for service response error code - // "IDPRejectedClaim". - // - // The identity provider (IdP) reported that authentication failed. This might - // be because the claim is invalid. - // - // If this error is returned for the AssumeRoleWithWebIdentity operation, it - // can also mean that the claim has expired or has been explicitly revoked. - ErrCodeIDPRejectedClaimException = "IDPRejectedClaim" - - // ErrCodeInvalidAuthorizationMessageException for service response error code - // "InvalidAuthorizationMessageException". - // - // The error returned if the message passed to DecodeAuthorizationMessage was - // invalid. This can happen if the token contains invalid characters, such as - // linebreaks. - ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException" - - // ErrCodeInvalidIdentityTokenException for service response error code - // "InvalidIdentityToken". - // - // The web identity token that was passed could not be validated by AWS. Get - // a new identity token from the identity provider and then retry the request. - ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken" - - // ErrCodeMalformedPolicyDocumentException for service response error code - // "MalformedPolicyDocument". - // - // The request was rejected because the policy document was malformed. The error - // message describes the specific error. - ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument" - - // ErrCodePackedPolicyTooLargeException for service response error code - // "PackedPolicyTooLarge". - // - // The request was rejected because the policy document was too large. The error - // message describes how big the policy document is, in packed form, as a percentage - // of what the API allows. - ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge" - - // ErrCodeRegionDisabledException for service response error code - // "RegionDisabledException". - // - // STS is not activated in the requested region for the account that is being - // asked to generate credentials. The account administrator must use the IAM - // console to activate STS in that region. For more information, see Activating - // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) - // in the IAM User Guide. - ErrCodeRegionDisabledException = "RegionDisabledException" -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/service.go deleted file mode 100644 index 185c914..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/query" -) - -// STS provides the API operation methods for making requests to -// AWS Security Token Service. See this package's package overview docs -// for details on the service. -// -// STS methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type STS struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "sts" // Name of service. - EndpointsID = ServiceName // ID to lookup a service endpoint with. - ServiceID = "STS" // ServiceID is a unique identifer of a specific service. -) - -// New creates a new instance of the STS client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a STS client from just a session. -// svc := sts.New(mySession) -// -// // Create a STS client with additional configuration -// svc := sts.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *STS { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *STS { - svc := &STS{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2011-06-15", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a STS operation and runs any -// custom request initialization. -func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/LICENSE deleted file mode 100644 index 89b8179..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Cenk Altı - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/backoff.go b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/backoff.go deleted file mode 100644 index 3676ee4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/backoff.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package backoff implements backoff algorithms for retrying operations. -// -// Use Retry function for retrying operations that may fail. -// If Retry does not meet your needs, -// copy/paste the function into your project and modify as you wish. -// -// There is also Ticker type similar to time.Ticker. -// You can use it if you need to work with channels. -// -// See Examples section below for usage examples. -package backoff - -import "time" - -// BackOff is a backoff policy for retrying an operation. -type BackOff interface { - // NextBackOff returns the duration to wait before retrying the operation, - // or backoff. Stop to indicate that no more retries should be made. - // - // Example usage: - // - // duration := backoff.NextBackOff(); - // if (duration == backoff.Stop) { - // // Do not retry operation. - // } else { - // // Sleep for duration and retry operation. - // } - // - NextBackOff() time.Duration - - // Reset to initial state. - Reset() -} - -// Stop indicates that no more retries should be made for use in NextBackOff(). -const Stop time.Duration = -1 - -// ZeroBackOff is a fixed backoff policy whose backoff time is always zero, -// meaning that the operation is retried immediately without waiting, indefinitely. -type ZeroBackOff struct{} - -func (b *ZeroBackOff) Reset() {} - -func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 } - -// StopBackOff is a fixed backoff policy that always returns backoff.Stop for -// NextBackOff(), meaning that the operation should never be retried. -type StopBackOff struct{} - -func (b *StopBackOff) Reset() {} - -func (b *StopBackOff) NextBackOff() time.Duration { return Stop } - -// ConstantBackOff is a backoff policy that always returns the same backoff delay. -// This is in contrast to an exponential backoff policy, -// which returns a delay that grows longer as you call NextBackOff() over and over again. -type ConstantBackOff struct { - Interval time.Duration -} - -func (b *ConstantBackOff) Reset() {} -func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval } - -func NewConstantBackOff(d time.Duration) *ConstantBackOff { - return &ConstantBackOff{Interval: d} -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/context.go b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/context.go deleted file mode 100644 index 7706faa..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/context.go +++ /dev/null @@ -1,63 +0,0 @@ -package backoff - -import ( - "context" - "time" -) - -// BackOffContext is a backoff policy that stops retrying after the context -// is canceled. -type BackOffContext interface { - BackOff - Context() context.Context -} - -type backOffContext struct { - BackOff - ctx context.Context -} - -// WithContext returns a BackOffContext with context ctx -// -// ctx must not be nil -func WithContext(b BackOff, ctx context.Context) BackOffContext { - if ctx == nil { - panic("nil context") - } - - if b, ok := b.(*backOffContext); ok { - return &backOffContext{ - BackOff: b.BackOff, - ctx: ctx, - } - } - - return &backOffContext{ - BackOff: b, - ctx: ctx, - } -} - -func ensureContext(b BackOff) BackOffContext { - if cb, ok := b.(BackOffContext); ok { - return cb - } - return WithContext(b, context.Background()) -} - -func (b *backOffContext) Context() context.Context { - return b.ctx -} - -func (b *backOffContext) NextBackOff() time.Duration { - select { - case <-b.ctx.Done(): - return Stop - default: - } - next := b.BackOff.NextBackOff() - if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next { - return Stop - } - return next -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/exponential.go b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/exponential.go deleted file mode 100644 index a031a65..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/exponential.go +++ /dev/null @@ -1,153 +0,0 @@ -package backoff - -import ( - "math/rand" - "time" -) - -/* -ExponentialBackOff is a backoff implementation that increases the backoff -period for each retry attempt using a randomization function that grows exponentially. - -NextBackOff() is calculated using the following formula: - - randomized interval = - RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) - -In other words NextBackOff() will range between the randomization factor -percentage below and above the retry interval. - -For example, given the following parameters: - - RetryInterval = 2 - RandomizationFactor = 0.5 - Multiplier = 2 - -the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, -multiplied by the exponential, that is, between 2 and 6 seconds. - -Note: MaxInterval caps the RetryInterval and not the randomized interval. - -If the time elapsed since an ExponentialBackOff instance is created goes past the -MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. - -The elapsed time can be reset by calling Reset(). - -Example: Given the following default arguments, for 10 tries the sequence will be, -and assuming we go over the MaxElapsedTime on the 10th try: - - Request # RetryInterval (seconds) Randomized Interval (seconds) - - 1 0.5 [0.25, 0.75] - 2 0.75 [0.375, 1.125] - 3 1.125 [0.562, 1.687] - 4 1.687 [0.8435, 2.53] - 5 2.53 [1.265, 3.795] - 6 3.795 [1.897, 5.692] - 7 5.692 [2.846, 8.538] - 8 8.538 [4.269, 12.807] - 9 12.807 [6.403, 19.210] - 10 19.210 backoff.Stop - -Note: Implementation is not thread-safe. -*/ -type ExponentialBackOff struct { - InitialInterval time.Duration - RandomizationFactor float64 - Multiplier float64 - MaxInterval time.Duration - // After MaxElapsedTime the ExponentialBackOff stops. - // It never stops if MaxElapsedTime == 0. - MaxElapsedTime time.Duration - Clock Clock - - currentInterval time.Duration - startTime time.Time -} - -// Clock is an interface that returns current time for BackOff. -type Clock interface { - Now() time.Time -} - -// Default values for ExponentialBackOff. -const ( - DefaultInitialInterval = 500 * time.Millisecond - DefaultRandomizationFactor = 0.5 - DefaultMultiplier = 1.5 - DefaultMaxInterval = 60 * time.Second - DefaultMaxElapsedTime = 15 * time.Minute -) - -// NewExponentialBackOff creates an instance of ExponentialBackOff using default values. -func NewExponentialBackOff() *ExponentialBackOff { - b := &ExponentialBackOff{ - InitialInterval: DefaultInitialInterval, - RandomizationFactor: DefaultRandomizationFactor, - Multiplier: DefaultMultiplier, - MaxInterval: DefaultMaxInterval, - MaxElapsedTime: DefaultMaxElapsedTime, - Clock: SystemClock, - } - b.Reset() - return b -} - -type systemClock struct{} - -func (t systemClock) Now() time.Time { - return time.Now() -} - -// SystemClock implements Clock interface that uses time.Now(). -var SystemClock = systemClock{} - -// Reset the interval back to the initial retry interval and restarts the timer. -func (b *ExponentialBackOff) Reset() { - b.currentInterval = b.InitialInterval - b.startTime = b.Clock.Now() -} - -// NextBackOff calculates the next backoff interval using the formula: -// Randomized interval = RetryInterval +/- (RandomizationFactor * RetryInterval) -func (b *ExponentialBackOff) NextBackOff() time.Duration { - // Make sure we have not gone over the maximum elapsed time. - if b.MaxElapsedTime != 0 && b.GetElapsedTime() > b.MaxElapsedTime { - return Stop - } - defer b.incrementCurrentInterval() - return getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval) -} - -// GetElapsedTime returns the elapsed time since an ExponentialBackOff instance -// is created and is reset when Reset() is called. -// -// The elapsed time is computed using time.Now().UnixNano(). It is -// safe to call even while the backoff policy is used by a running -// ticker. -func (b *ExponentialBackOff) GetElapsedTime() time.Duration { - return b.Clock.Now().Sub(b.startTime) -} - -// Increments the current interval by multiplying it with the multiplier. -func (b *ExponentialBackOff) incrementCurrentInterval() { - // Check for overflow, if overflow is detected set the current interval to the max interval. - if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier { - b.currentInterval = b.MaxInterval - } else { - b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier) - } -} - -// Returns a random value from the following interval: -// [randomizationFactor * currentInterval, randomizationFactor * currentInterval]. -func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { - var delta = randomizationFactor * float64(currentInterval) - var minInterval = float64(currentInterval) - delta - var maxInterval = float64(currentInterval) + delta - - // Get a random value from the range [minInterval, maxInterval]. - // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then - // we want a 33% chance for selecting either 1, 2 or 3. - return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/retry.go b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/retry.go deleted file mode 100644 index e936a50..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/retry.go +++ /dev/null @@ -1,82 +0,0 @@ -package backoff - -import "time" - -// An Operation is executing by Retry() or RetryNotify(). -// The operation will be retried using a backoff policy if it returns an error. -type Operation func() error - -// Notify is a notify-on-error function. It receives an operation error and -// backoff delay if the operation failed (with an error). -// -// NOTE that if the backoff policy stated to stop retrying, -// the notify function isn't called. -type Notify func(error, time.Duration) - -// Retry the operation o until it does not return error or BackOff stops. -// o is guaranteed to be run at least once. -// -// If o returns a *PermanentError, the operation is not retried, and the -// wrapped error is returned. -// -// Retry sleeps the goroutine for the duration returned by BackOff after a -// failed operation returns. -func Retry(o Operation, b BackOff) error { return RetryNotify(o, b, nil) } - -// RetryNotify calls notify function with the error and wait duration -// for each failed attempt before sleep. -func RetryNotify(operation Operation, b BackOff, notify Notify) error { - var err error - var next time.Duration - var t *time.Timer - - cb := ensureContext(b) - - b.Reset() - for { - if err = operation(); err == nil { - return nil - } - - if permanent, ok := err.(*PermanentError); ok { - return permanent.Err - } - - if next = cb.NextBackOff(); next == Stop { - return err - } - - if notify != nil { - notify(err, next) - } - - if t == nil { - t = time.NewTimer(next) - defer t.Stop() - } else { - t.Reset(next) - } - - select { - case <-cb.Context().Done(): - return err - case <-t.C: - } - } -} - -// PermanentError signals that the operation should not be retried. -type PermanentError struct { - Err error -} - -func (e *PermanentError) Error() string { - return e.Err.Error() -} - -// Permanent wraps the given err in a *PermanentError. -func Permanent(err error) *PermanentError { - return &PermanentError{ - Err: err, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/ticker.go b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/ticker.go deleted file mode 100644 index e41084b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/ticker.go +++ /dev/null @@ -1,82 +0,0 @@ -package backoff - -import ( - "sync" - "time" -) - -// Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. -// -// Ticks will continue to arrive when the previous operation is still running, -// so operations that take a while to fail could run in quick succession. -type Ticker struct { - C <-chan time.Time - c chan time.Time - b BackOffContext - stop chan struct{} - stopOnce sync.Once -} - -// NewTicker returns a new Ticker containing a channel that will send -// the time at times specified by the BackOff argument. Ticker is -// guaranteed to tick at least once. The channel is closed when Stop -// method is called or BackOff stops. It is not safe to manipulate the -// provided backoff policy (notably calling NextBackOff or Reset) -// while the ticker is running. -func NewTicker(b BackOff) *Ticker { - c := make(chan time.Time) - t := &Ticker{ - C: c, - c: c, - b: ensureContext(b), - stop: make(chan struct{}), - } - t.b.Reset() - go t.run() - return t -} - -// Stop turns off a ticker. After Stop, no more ticks will be sent. -func (t *Ticker) Stop() { - t.stopOnce.Do(func() { close(t.stop) }) -} - -func (t *Ticker) run() { - c := t.c - defer close(c) - - // Ticker is guaranteed to tick at least once. - afterC := t.send(time.Now()) - - for { - if afterC == nil { - return - } - - select { - case tick := <-afterC: - afterC = t.send(tick) - case <-t.stop: - t.c = nil // Prevent future ticks from being sent to the channel. - return - case <-t.b.Context().Done(): - return - } - } -} - -func (t *Ticker) send(tick time.Time) <-chan time.Time { - select { - case t.c <- tick: - case <-t.stop: - return nil - } - - next := t.b.NextBackOff() - if next == Stop { - t.Stop() - return nil - } - - return time.After(next) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/tries.go b/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/tries.go deleted file mode 100644 index cfeefd9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cenkalti/backoff/tries.go +++ /dev/null @@ -1,35 +0,0 @@ -package backoff - -import "time" - -/* -WithMaxRetries creates a wrapper around another BackOff, which will -return Stop if NextBackOff() has been called too many times since -the last time Reset() was called - -Note: Implementation is not thread-safe. -*/ -func WithMaxRetries(b BackOff, max uint64) BackOff { - return &backOffTries{delegate: b, maxTries: max} -} - -type backOffTries struct { - delegate BackOff - maxTries uint64 - numTries uint64 -} - -func (b *backOffTries) NextBackOff() time.Duration { - if b.maxTries > 0 { - if b.maxTries <= b.numTries { - return Stop - } - b.numTries++ - } - return b.delegate.NextBackOff() -} - -func (b *backOffTries) Reset() { - b.numTries = 0 - b.delegate.Reset() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/LICENSE deleted file mode 100644 index c035bb4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2015-2016, Cloudflare. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors -may be used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go deleted file mode 100644 index 818cdf8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go +++ /dev/null @@ -1,318 +0,0 @@ -// Package cloudflare implements the Cloudflare v4 API. -package cloudflare - -import ( - "bytes" - "context" - "encoding/json" - "io" - "io/ioutil" - "log" - "math" - "net/http" - "strings" - "time" - - "github.com/pkg/errors" - "golang.org/x/time/rate" -) - -const apiURL = "https://api.cloudflare.com/client/v4" -const ( - // AuthKeyEmail specifies that we should authenticate with API key and email address - AuthKeyEmail = 1 << iota - // AuthUserService specifies that we should authenticate with a User-Service key - AuthUserService -) - -// API holds the configuration for the current API client. A client should not -// be modified concurrently. -type API struct { - APIKey string - APIEmail string - APIUserServiceKey string - BaseURL string - organizationID string - headers http.Header - httpClient *http.Client - authType int - rateLimiter *rate.Limiter - retryPolicy RetryPolicy - logger Logger -} - -// New creates a new Cloudflare v4 API client. -func New(key, email string, opts ...Option) (*API, error) { - if key == "" || email == "" { - return nil, errors.New(errEmptyCredentials) - } - - silentLogger := log.New(ioutil.Discard, "", log.LstdFlags) - - api := &API{ - APIKey: key, - APIEmail: email, - BaseURL: apiURL, - headers: make(http.Header), - authType: AuthKeyEmail, - rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min) - retryPolicy: RetryPolicy{ - MaxRetries: 3, - MinRetryDelay: time.Duration(1) * time.Second, - MaxRetryDelay: time.Duration(30) * time.Second, - }, - logger: silentLogger, - } - - err := api.parseOptions(opts...) - if err != nil { - return nil, errors.Wrap(err, "options parsing failed") - } - - // Fall back to http.DefaultClient if the package user does not provide - // their own. - if api.httpClient == nil { - api.httpClient = http.DefaultClient - } - - return api, nil -} - -// SetAuthType sets the authentication method (AuthyKeyEmail or AuthUserService). -func (api *API) SetAuthType(authType int) { - api.authType = authType -} - -// ZoneIDByName retrieves a zone's ID from the name. -func (api *API) ZoneIDByName(zoneName string) (string, error) { - res, err := api.ListZones(zoneName) - if err != nil { - return "", errors.Wrap(err, "ListZones command failed") - } - for _, zone := range res { - if zone.Name == zoneName { - return zone.ID, nil - } - } - return "", errors.New("Zone could not be found") -} - -// makeRequest makes a HTTP request and returns the body as a byte slice, -// closing it before returnng. params will be serialized to JSON. -func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) { - return api.makeRequestWithAuthType(method, uri, params, api.authType) -} - -func (api *API) makeRequestWithAuthType(method, uri string, params interface{}, authType int) ([]byte, error) { - // Replace nil with a JSON object if needed - var jsonBody []byte - var err error - if params != nil { - jsonBody, err = json.Marshal(params) - if err != nil { - return nil, errors.Wrap(err, "error marshalling params to JSON") - } - } else { - jsonBody = nil - } - - var resp *http.Response - var respErr error - var reqBody io.Reader - var respBody []byte - for i := 0; i <= api.retryPolicy.MaxRetries; i++ { - if jsonBody != nil { - reqBody = bytes.NewReader(jsonBody) - } - - if i > 0 { - // expect the backoff introduced here on errored requests to dominate the effect of rate limiting - // dont need a random component here as the rate limiter should do something similar - // nb time duration could truncate an arbitrary float. Since our inputs are all ints, we should be ok - sleepDuration := time.Duration(math.Pow(2, float64(i-1)) * float64(api.retryPolicy.MinRetryDelay)) - - if sleepDuration > api.retryPolicy.MaxRetryDelay { - sleepDuration = api.retryPolicy.MaxRetryDelay - } - // useful to do some simple logging here, maybe introduce levels later - api.logger.Printf("Sleeping %s before retry attempt number %d for request %s %s", sleepDuration.String(), i, method, uri) - time.Sleep(sleepDuration) - } - api.rateLimiter.Wait(context.TODO()) - if err != nil { - return nil, errors.Wrap(err, "Error caused by request rate limiting") - } - resp, respErr = api.request(method, uri, reqBody, authType) - - // retry if the server is rate limiting us or if it failed - // assumes server operations are rolled back on failure - if respErr != nil || resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { - // if we got a valid http response, try to read body so we can reuse the connection - // see https://golang.org/pkg/net/http/#Client.Do - if respErr == nil { - respBody, err = ioutil.ReadAll(resp.Body) - resp.Body.Close() - - respErr = errors.Wrap(err, "could not read response body") - - api.logger.Printf("Request: %s %s got an error response %d: %s\n", method, uri, resp.StatusCode, - strings.Replace(strings.Replace(string(respBody), "\n", "", -1), "\t", "", -1)) - } else { - api.logger.Printf("Error performing request: %s %s : %s \n", method, uri, respErr.Error()) - } - continue - } else { - respBody, err = ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - if err != nil { - return nil, errors.Wrap(err, "could not read response body") - } - break - } - } - if respErr != nil { - return nil, respErr - } - - switch { - case resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices: - case resp.StatusCode == http.StatusUnauthorized: - return nil, errors.Errorf("HTTP status %d: invalid credentials", resp.StatusCode) - case resp.StatusCode == http.StatusForbidden: - return nil, errors.Errorf("HTTP status %d: insufficient permissions", resp.StatusCode) - case resp.StatusCode == http.StatusServiceUnavailable, - resp.StatusCode == http.StatusBadGateway, - resp.StatusCode == http.StatusGatewayTimeout, - resp.StatusCode == 522, - resp.StatusCode == 523, - resp.StatusCode == 524: - return nil, errors.Errorf("HTTP status %d: service failure", resp.StatusCode) - default: - var s string - if respBody != nil { - s = string(respBody) - } - return nil, errors.Errorf("HTTP status %d: content %q", resp.StatusCode, s) - } - - return respBody, nil -} - -// request makes a HTTP request to the given API endpoint, returning the raw -// *http.Response, or an error if one occurred. The caller is responsible for -// closing the response body. -func (api *API) request(method, uri string, reqBody io.Reader, authType int) (*http.Response, error) { - req, err := http.NewRequest(method, api.BaseURL+uri, reqBody) - if err != nil { - return nil, errors.Wrap(err, "HTTP request creation failed") - } - - // Apply any user-defined headers first. - req.Header = cloneHeader(api.headers) - if authType&AuthKeyEmail != 0 { - req.Header.Set("X-Auth-Key", api.APIKey) - req.Header.Set("X-Auth-Email", api.APIEmail) - } - if authType&AuthUserService != 0 { - req.Header.Set("X-Auth-User-Service-Key", api.APIUserServiceKey) - } - - if req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "application/json") - } - - resp, err := api.httpClient.Do(req) - if err != nil { - return nil, errors.Wrap(err, "HTTP request failed") - } - - return resp, nil -} - -// Returns the base URL to use for API endpoints that exist for both accounts and organizations. -// If an Organization option was used when creating the API instance, returns the org URL. -// -// accountBase is the base URL for endpoints referring to the current user. It exists as a -// parameter because it is not consistent across APIs. -func (api *API) userBaseURL(accountBase string) string { - if api.organizationID != "" { - return "/organizations/" + api.organizationID - } - return accountBase -} - -// cloneHeader returns a shallow copy of the header. -// copied from https://godoc.org/github.com/golang/gddo/httputil/header#Copy -func cloneHeader(header http.Header) http.Header { - h := make(http.Header) - for k, vs := range header { - h[k] = vs - } - return h -} - -// ResponseInfo contains a code and message returned by the API as errors or -// informational messages inside the response. -type ResponseInfo struct { - Code int `json:"code"` - Message string `json:"message"` -} - -// Response is a template. There will also be a result struct. There will be a -// unique response type for each response, which will include this type. -type Response struct { - Success bool `json:"success"` - Errors []ResponseInfo `json:"errors"` - Messages []ResponseInfo `json:"messages"` -} - -// ResultInfo contains metadata about the Response. -type ResultInfo struct { - Page int `json:"page"` - PerPage int `json:"per_page"` - TotalPages int `json:"total_pages"` - Count int `json:"count"` - Total int `json:"total_count"` -} - -// RawResponse keeps the result as JSON form -type RawResponse struct { - Response - Result json.RawMessage `json:"result"` -} - -// Raw makes a HTTP request with user provided params and returns the -// result as untouched JSON. -func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) { - res, err := api.makeRequest(method, endpoint, data) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var r RawResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PaginationOptions can be passed to a list request to configure paging -// These values will be defaulted if omitted, and PerPage has min/max limits set by resource -type PaginationOptions struct { - Page int `json:"page,omitempty"` - PerPage int `json:"per_page,omitempty"` -} - -// RetryPolicy specifies number of retries and min/max retry delays -// This config is used when the client exponentially backs off after errored requests -type RetryPolicy struct { - MaxRetries int - MinRetryDelay time.Duration - MaxRetryDelay time.Duration -} - -// Logger defines the interface this library needs to use logging -// This is a subset of the methods implemented in the log package -type Logger interface { - Printf(format string, v ...interface{}) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/cpage.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/cpage.go deleted file mode 100644 index 87e50ce..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/cpage.go +++ /dev/null @@ -1,29 +0,0 @@ -package cloudflare - -import "time" - -// CustomPage represents a custom page configuration. -type CustomPage struct { - CreatedOn string `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - URL string `json:"url"` - State string `json:"state"` - RequiredTokens []string `json:"required_tokens"` - PreviewTarget string `json:"preview_target"` - Description string `json:"description"` -} - -// CustomPageResponse represents the response from the custom pages endpoint. -type CustomPageResponse struct { - Response - Result []CustomPage `json:"result"` -} - -// https://api.cloudflare.com/#custom-pages-for-a-zone-available-custom-pages -// GET /zones/:zone_identifier/custom_pages - -// https://api.cloudflare.com/#custom-pages-for-a-zone-custom-page-details -// GET /zones/:zone_identifier/custom_pages/:identifier - -// https://api.cloudflare.com/#custom-pages-for-a-zone-update-custom-page-url -// PUT /zones/:zone_identifier/custom_pages/:identifier diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go deleted file mode 100644 index 44dbc40..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go +++ /dev/null @@ -1,149 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// CustomHostnameSSL represents the SSL section in a given custom hostname. -type CustomHostnameSSL struct { - Status string `json:"status,omitempty"` - Method string `json:"method,omitempty"` - Type string `json:"type,omitempty"` - CnameTarget string `json:"cname_target,omitempty"` - CnameName string `json:"cname_name,omitempty"` -} - -// CustomMetadata defines custom metadata for the hostname. This requires logic to be implemented by Cloudflare to act on the data provided. -type CustomMetadata map[string]interface{} - -// CustomHostname represents a custom hostname in a zone. -type CustomHostname struct { - ID string `json:"id,omitempty"` - Hostname string `json:"hostname,omitempty"` - SSL CustomHostnameSSL `json:"ssl,omitempty"` - CustomMetadata CustomMetadata `json:"custom_metadata,omitempty"` -} - -// CustomHostNameResponse represents a response from the Custom Hostnames endpoints. -type CustomHostnameResponse struct { - Result CustomHostname `json:"result"` - Response -} - -// CustomHostnameListResponse represents a response from the Custom Hostnames endpoints. -type CustomHostnameListResponse struct { - Result []CustomHostname `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// Modify SSL configuration for the given custom hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-update-custom-hostname-configuration -func (api *API) UpdateCustomHostnameSSL(zoneID string, customHostnameID string, ssl CustomHostnameSSL) (CustomHostname, error) { - return CustomHostname{}, errors.New("Not implemented") -} - -// Delete a custom hostname (and any issued SSL certificates) -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-delete-a-custom-hostname-and-any-issued-ssl-certificates- -func (api *API) DeleteCustomHostname(zoneID string, customHostnameID string) error { - uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// CreateCustomHostname creates a new custom hostname and requests that an SSL certificate be issued for it. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-create-custom-hostname -func (api *API) CreateCustomHostname(zoneID string, ch CustomHostname) (*CustomHostnameResponse, error) { - uri := "/zones/" + zoneID + "/custom_hostnames" - res, err := api.makeRequest("POST", uri, ch) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// CustomHostnames fetches custom hostnames for the given zone, -// by applying filter.Hostname if not empty and scoping the result to page'th 50 items. -// -// The returned ResultInfo can be used to implement pagination. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-list-custom-hostnames -func (api *API) CustomHostnames(zoneID string, page int, filter CustomHostname) ([]CustomHostname, ResultInfo, error) { - v := url.Values{} - v.Set("per_page", "50") - v.Set("page", strconv.Itoa(page)) - if filter.Hostname != "" { - v.Set("hostname", filter.Hostname) - } - query := "?" + v.Encode() - - uri := "/zones/" + zoneID + "/custom_hostnames" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []CustomHostname{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - var customHostnameListResponse CustomHostnameListResponse - err = json.Unmarshal(res, &customHostnameListResponse) - if err != nil { - return []CustomHostname{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - return customHostnameListResponse.Result, customHostnameListResponse.ResultInfo, nil -} - -// CustomHostname inspects the given custom hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-custom-hostname-configuration-details -func (api *API) CustomHostname(zoneID string, customHostnameID string) (CustomHostname, error) { - uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return CustomHostname{}, errors.Wrap(err, errMakeRequestError) - } - - var response CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return CustomHostname{}, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// CustomHostnameIDByName retrieves the ID for the given hostname in the given zone. -func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) { - customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname}) - if err != nil { - return "", errors.Wrap(err, "CustomHostnames command failed") - } - for _, ch := range customHostnames { - if ch.Hostname == hostname { - return ch.ID, nil - } - } - return "", errors.New("CustomHostname could not be found") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/dns.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/dns.go deleted file mode 100644 index 3303e9d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/dns.go +++ /dev/null @@ -1,174 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// DNSRecord represents a DNS record in a zone. -type DNSRecord struct { - ID string `json:"id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Content string `json:"content,omitempty"` - Proxiable bool `json:"proxiable,omitempty"` - Proxied bool `json:"proxied,omitempty"` - TTL int `json:"ttl,omitempty"` - Locked bool `json:"locked,omitempty"` - ZoneID string `json:"zone_id,omitempty"` - ZoneName string `json:"zone_name,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` - Data interface{} `json:"data,omitempty"` // data returned by: SRV, LOC - Meta interface{} `json:"meta,omitempty"` - Priority int `json:"priority,omitempty"` -} - -// DNSRecordResponse represents the response from the DNS endpoint. -type DNSRecordResponse struct { - Result DNSRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// DNSListResponse represents the response from the list DNS records endpoint. -type DNSListResponse struct { - Result []DNSRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateDNSRecord creates a DNS record for the zone identifier. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record -func (api *API) CreateDNSRecord(zoneID string, rr DNSRecord) (*DNSRecordResponse, error) { - uri := "/zones/" + zoneID + "/dns_records" - res, err := api.makeRequest("POST", uri, rr) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var recordResp *DNSRecordResponse - err = json.Unmarshal(res, &recordResp) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return recordResp, nil -} - -// DNSRecords returns a slice of DNS records for the given zone identifier. -// -// This takes a DNSRecord to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records -func (api *API) DNSRecords(zoneID string, rr DNSRecord) ([]DNSRecord, error) { - // Construct a query string - v := url.Values{} - // Request as many records as possible per page - API max is 50 - v.Set("per_page", "50") - if rr.Name != "" { - v.Set("name", rr.Name) - } - if rr.Type != "" { - v.Set("type", rr.Type) - } - if rr.Content != "" { - v.Set("content", rr.Content) - } - - var query string - var records []DNSRecord - page := 1 - - // Loop over makeRequest until what we've fetched all records - for { - v.Set("page", strconv.Itoa(page)) - query = "?" + v.Encode() - uri := "/zones/" + zoneID + "/dns_records" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []DNSRecord{}, errors.Wrap(err, errMakeRequestError) - } - var r DNSListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []DNSRecord{}, errors.Wrap(err, errUnmarshalError) - } - records = append(records, r.Result...) - if r.ResultInfo.Page >= r.ResultInfo.TotalPages { - break - } - // Loop around and fetch the next page - page++ - } - return records, nil -} - -// DNSRecord returns a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details -func (api *API) DNSRecord(zoneID, recordID string) (DNSRecord, error) { - uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return DNSRecord{}, errors.Wrap(err, errMakeRequestError) - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return DNSRecord{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateDNSRecord updates a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record -func (api *API) UpdateDNSRecord(zoneID, recordID string, rr DNSRecord) error { - rec, err := api.DNSRecord(zoneID, recordID) - if err != nil { - return err - } - // Populate the record name from the existing one if the update didn't - // specify it. - if rr.Name == "" { - rr.Name = rec.Name - } - rr.Type = rec.Type - uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("PUT", uri, rr) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeleteDNSRecord deletes a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record -func (api *API) DeleteDNSRecord(zoneID, recordID string) error { - uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/errors.go deleted file mode 100644 index 2fff3db..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/errors.go +++ /dev/null @@ -1,48 +0,0 @@ -package cloudflare - -// Error messages -const ( - errEmptyCredentials = "invalid credentials: key & email must not be empty" - errMakeRequestError = "error from makeRequest" - errUnmarshalError = "error unmarshalling the JSON response" - errRequestNotSuccessful = "error reported by API" -) - -var _ Error = &UserError{} - -// Error represents an error returned from this library. -type Error interface { - error - // Raised when user credentials or configuration is invalid. - User() bool - // Raised when a parsing error (e.g. JSON) occurs. - Parse() bool - // Raised when a network error occurs. - Network() bool - // Contains the most recent error. -} - -// UserError represents a user-generated error. -type UserError struct { - Err error -} - -// User is a user-caused error. -func (e *UserError) User() bool { - return true -} - -// Network error. -func (e *UserError) Network() bool { - return false -} - -// Parse error. -func (e *UserError) Parse() bool { - return true -} - -// Error wraps the underlying error. -func (e *UserError) Error() string { - return e.Err.Error() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/firewall.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/firewall.go deleted file mode 100644 index 9246b7e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/firewall.go +++ /dev/null @@ -1,241 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// AccessRule represents a firewall access rule. -type AccessRule struct { - ID string `json:"id,omitempty"` - Notes string `json:"notes,omitempty"` - AllowedModes []string `json:"allowed_modes,omitempty"` - Mode string `json:"mode,omitempty"` - Configuration AccessRuleConfiguration `json:"configuration,omitempty"` - Scope AccessRuleScope `json:"scope,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` -} - -// AccessRuleConfiguration represents the configuration of a firewall -// access rule. -type AccessRuleConfiguration struct { - Target string `json:"target,omitempty"` - Value string `json:"value,omitempty"` -} - -// AccessRuleScope represents the scope of a firewall access rule. -type AccessRuleScope struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` -} - -// AccessRuleResponse represents the response from the firewall access -// rule endpoint. -type AccessRuleResponse struct { - Result AccessRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessRuleListResponse represents the response from the list access rules -// endpoint. -type AccessRuleListResponse struct { - Result []AccessRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// ListUserAccessRules returns a slice of access rules for the logged-in user. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules -func (api *API) ListUserAccessRules(accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/user", accessRule, page) -} - -// CreateUserAccessRule creates a firewall access rule for the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-create-access-rule -func (api *API) CreateUserAccessRule(accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/user", accessRule) -} - -// UpdateUserAccessRule updates a single access rule for the logged-in user & -// given access rule identifier. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) UpdateUserAccessRule(accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/user", accessRuleID, accessRule) -} - -// DeleteUserAccessRule deletes a single access rule for the logged-in user and -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) DeleteUserAccessRule(accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/user", accessRuleID) -} - -// ListZoneAccessRules returns a slice of access rules for the given zone -// identifier. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-list-access-rules -func (api *API) ListZoneAccessRules(zoneID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/zones/"+zoneID, accessRule, page) -} - -// CreateZoneAccessRule creates a firewall access rule for the given zone -// identifier. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-create-access-rule -func (api *API) CreateZoneAccessRule(zoneID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/zones/"+zoneID, accessRule) -} - -// UpdateZoneAccessRule updates a single access rule for the given zone & -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-update-access-rule -func (api *API) UpdateZoneAccessRule(zoneID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/zones/"+zoneID, accessRuleID, accessRule) -} - -// DeleteZoneAccessRule deletes a single access rule for the given zone and -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-delete-access-rule -func (api *API) DeleteZoneAccessRule(zoneID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/zones/"+zoneID, accessRuleID) -} - -// ListOrganizationAccessRules returns a slice of access rules for the given -// organization identifier. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-list-access-rules -func (api *API) ListOrganizationAccessRules(organizationID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/organizations/"+organizationID, accessRule, page) -} - -// CreateOrganizationAccessRule creates a firewall access rule for the given -// organization identifier. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-create-access-rule -func (api *API) CreateOrganizationAccessRule(organizationID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/organizations/"+organizationID, accessRule) -} - -// UpdateOrganizationAccessRule updates a single access rule for the given -// organization & access rule identifiers. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-update-access-rule -func (api *API) UpdateOrganizationAccessRule(organizationID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/organizations/"+organizationID, accessRuleID, accessRule) -} - -// DeleteOrganizationAccessRule deletes a single access rule for the given -// organization and access rule identifiers. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-delete-access-rule -func (api *API) DeleteOrganizationAccessRule(organizationID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/organizations/"+organizationID, accessRuleID) -} - -func (api *API) listAccessRules(prefix string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - // Construct a query string - v := url.Values{} - if page <= 0 { - page = 1 - } - v.Set("page", strconv.Itoa(page)) - // Request as many rules as possible per page - API max is 100 - v.Set("per_page", "100") - if accessRule.Notes != "" { - v.Set("notes", accessRule.Notes) - } - if accessRule.Mode != "" { - v.Set("mode", accessRule.Mode) - } - if accessRule.Scope.Type != "" { - v.Set("scope_type", accessRule.Scope.Type) - } - if accessRule.Configuration.Value != "" { - v.Set("configuration_value", accessRule.Configuration.Value) - } - if accessRule.Configuration.Target != "" { - v.Set("configuration_target", accessRule.Configuration.Target) - } - v.Set("page", strconv.Itoa(page)) - query := "?" + v.Encode() - - uri := prefix + "/firewall/access_rules/rules" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -func (api *API) createAccessRule(prefix string, accessRule AccessRule) (*AccessRuleResponse, error) { - uri := prefix + "/firewall/access_rules/rules" - res, err := api.makeRequest("POST", uri, accessRule) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -func (api *API) updateAccessRule(prefix, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("PATCH", uri, accessRule) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -func (api *API) deleteAccessRule(prefix, accessRuleID string) (*AccessRuleResponse, error) { - uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/ips.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/ips.go deleted file mode 100644 index 72b5fcf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/ips.go +++ /dev/null @@ -1,44 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/pkg/errors" -) - -// IPRanges contains lists of IPv4 and IPv6 CIDRs. -type IPRanges struct { - IPv4CIDRs []string `json:"ipv4_cidrs"` - IPv6CIDRs []string `json:"ipv6_cidrs"` -} - -// IPsResponse is the API response containing a list of IPs. -type IPsResponse struct { - Response - Result IPRanges `json:"result"` -} - -// IPs gets a list of Cloudflare's IP ranges. -// -// This does not require logging in to the API. -// -// API reference: https://api.cloudflare.com/#cloudflare-ips -func IPs() (IPRanges, error) { - resp, err := http.Get(apiURL + "/ips") - if err != nil { - return IPRanges{}, errors.Wrap(err, "HTTP request failed") - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return IPRanges{}, errors.Wrap(err, "Response body could not be read") - } - var r IPsResponse - err = json.Unmarshal(body, &r) - if err != nil { - return IPRanges{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/keyless.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/keyless.go deleted file mode 100644 index c5cc839..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/keyless.go +++ /dev/null @@ -1,52 +0,0 @@ -package cloudflare - -import "time" - -// KeylessSSL represents Keyless SSL configuration. -type KeylessSSL struct { - ID string `json:"id"` - Name string `json:"name"` - Host string `json:"host"` - Port int `json:"port"` - Status string `json:"success"` - Enabled bool `json:"enabled"` - Permissions []string `json:"permissions"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modifed_on"` -} - -// KeylessSSLResponse represents the response from the Keyless SSL endpoint. -type KeylessSSLResponse struct { - Response - Result []KeylessSSL `json:"result"` -} - -// CreateKeyless creates a new Keyless SSL configuration for the zone. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-create-a-keyless-ssl-configuration -func (api *API) CreateKeyless() { -} - -// ListKeyless lists Keyless SSL configurations for a zone. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-list-keyless-ssls -func (api *API) ListKeyless() { -} - -// Keyless provides the configuration for a given Keyless SSL identifier. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-keyless-ssl-details -func (api *API) Keyless() { -} - -// UpdateKeyless updates an existing Keyless SSL configuration. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-update-keyless-configuration -func (api *API) UpdateKeyless() { -} - -// DeleteKeyless deletes an existing Keyless SSL configuration. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-delete-keyless-configuration -func (api *API) DeleteKeyless() { -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go deleted file mode 100644 index e1af07b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go +++ /dev/null @@ -1,330 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// LoadBalancerPool represents a load balancer pool's properties. -type LoadBalancerPool struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Description string `json:"description"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - MinimumOrigins int `json:"minimum_origins,omitempty"` - Monitor string `json:"monitor,omitempty"` - Origins []LoadBalancerOrigin `json:"origins"` - NotificationEmail string `json:"notification_email,omitempty"` - - // CheckRegions defines the geographic region(s) from where to run health-checks from - e.g. "WNAM", "WEU", "SAF", "SAM". - // Providing a null/empty value means "all regions", which may not be available to all plan types. - CheckRegions []string `json:"check_regions"` -} - -type LoadBalancerOrigin struct { - Name string `json:"name"` - Address string `json:"address"` - Enabled bool `json:"enabled"` - Weight float64 `json:"weight"` -} - -// LoadBalancerMonitor represents a load balancer monitor's properties. -type LoadBalancerMonitor struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Type string `json:"type"` - Description string `json:"description"` - Method string `json:"method"` - Path string `json:"path"` - Header map[string][]string `json:"header"` - Timeout int `json:"timeout"` - Retries int `json:"retries"` - Interval int `json:"interval"` - ExpectedBody string `json:"expected_body"` - ExpectedCodes string `json:"expected_codes"` -} - -// LoadBalancer represents a load balancer's properties. -type LoadBalancer struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Description string `json:"description"` - Name string `json:"name"` - TTL int `json:"ttl,omitempty"` - FallbackPool string `json:"fallback_pool"` - DefaultPools []string `json:"default_pools"` - RegionPools map[string][]string `json:"region_pools"` - PopPools map[string][]string `json:"pop_pools"` - Proxied bool `json:"proxied"` - Persistence string `json:"session_affinity,omitempty"` -} - -// loadBalancerPoolResponse represents the response from the load balancer pool endpoints. -type loadBalancerPoolResponse struct { - Response - Result LoadBalancerPool `json:"result"` -} - -// loadBalancerPoolListResponse represents the response from the List Pools endpoint. -type loadBalancerPoolListResponse struct { - Response - Result []LoadBalancerPool `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerMonitorResponse represents the response from the load balancer monitor endpoints. -type loadBalancerMonitorResponse struct { - Response - Result LoadBalancerMonitor `json:"result"` -} - -// loadBalancerMonitorListResponse represents the response from the List Monitors endpoint. -type loadBalancerMonitorListResponse struct { - Response - Result []LoadBalancerMonitor `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerResponse represents the response from the load balancer endpoints. -type loadBalancerResponse struct { - Response - Result LoadBalancer `json:"result"` -} - -// loadBalancerListResponse represents the response from the List Load Balancers endpoint. -type loadBalancerListResponse struct { - Response - Result []LoadBalancer `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// CreateLoadBalancerPool creates a new load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-create-a-pool -func (api *API) CreateLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools" - res, err := api.makeRequest("POST", uri, pool) - if err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancerPools lists load balancer pools connected to an account. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-list-pools -func (api *API) ListLoadBalancerPools() ([]LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerPoolDetails returns the details for a load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-pool-details -func (api *API) LoadBalancerPoolDetails(poolID string) (LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancerPool disables and deletes a load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-delete-a-pool -func (api *API) DeleteLoadBalancerPool(poolID string) error { - uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ModifyLoadBalancerPool modifies a configured load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-modify-a-pool -func (api *API) ModifyLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools/" + pool.ID - res, err := api.makeRequest("PUT", uri, pool) - if err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateLoadBalancerMonitor creates a new load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-create-a-monitor -func (api *API) CreateLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors" - res, err := api.makeRequest("POST", uri, monitor) - if err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancerMonitors lists load balancer monitors connected to an account. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-list-monitors -func (api *API) ListLoadBalancerMonitors() ([]LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerMonitorDetails returns the details for a load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-monitor-details -func (api *API) LoadBalancerMonitorDetails(monitorID string) (LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitorID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancerMonitor disables and deletes a load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-delete-a-monitor -func (api *API) DeleteLoadBalancerMonitor(monitorID string) error { - uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitorID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ModifyLoadBalancerMonitor modifies a configured load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-modify-a-monitor -func (api *API) ModifyLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitor.ID - res, err := api.makeRequest("PUT", uri, monitor) - if err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateLoadBalancer creates a new load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-create-a-load-balancer -func (api *API) CreateLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers" - res, err := api.makeRequest("POST", uri, lb) - if err != nil { - return LoadBalancer{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancers lists load balancers configured on a zone. -// -// API reference: https://api.cloudflare.com/#load-balancers-list-load-balancers -func (api *API) ListLoadBalancers(zoneID string) ([]LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerDetails returns the details for a load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-load-balancer-details -func (api *API) LoadBalancerDetails(zoneID, lbID string) (LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers/" + lbID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return LoadBalancer{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancer disables and deletes a load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-delete-a-load-balancer -func (api *API) DeleteLoadBalancer(zoneID, lbID string) error { - uri := "/zones/" + zoneID + "/load_balancers/" + lbID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ModifyLoadBalancer modifies a configured load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-modify-a-load-balancer -func (api *API) ModifyLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers/" + lb.ID - res, err := api.makeRequest("PUT", uri, lb) - if err != nil { - return LoadBalancer{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/lockdown.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/lockdown.go deleted file mode 100644 index 3dba81c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/lockdown.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// ZoneLockdown represents a Zone Lockdown rule. A rule only permits access to -// the provided URL pattern(s) from the given IP address(es) or subnet(s). -type ZoneLockdown struct { - ID string `json:"id"` - Description string `json:"description"` - URLs []string `json:"urls"` - Configurations []ZoneLockdownConfig `json:"configurations"` - Paused bool `json:"paused"` -} - -// ZoneLockdownConfig represents a Zone Lockdown config, which comprises -// a Target ("ip" or "ip_range") and a Value (an IP address or IP+mask, -// respectively.) -type ZoneLockdownConfig struct { - Target string `json:"target"` - Value string `json:"value"` -} - -// ZoneLockdownResponse represents a response from the Zone Lockdown endpoint. -type ZoneLockdownResponse struct { - Result ZoneLockdown `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// ZoneLockdownListResponse represents a response from the List Zone Lockdown -// endpoint. -type ZoneLockdownListResponse struct { - Result []ZoneLockdown `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateZoneLockdown creates a Zone ZoneLockdown rule for the given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-create-a-ZoneLockdown-rule -func (api *API) CreateZoneLockdown(zoneID string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns" - res, err := api.makeRequest("POST", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateZoneLockdown updates a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-update-ZoneLockdown-rule -func (api *API) UpdateZoneLockdown(zoneID string, id string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns" - res, err := api.makeRequest("PUT", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// DeleteZoneLockdown deletes a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-delete-ZoneLockdown-rule -func (api *API) DeleteZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneLockdown retrieves a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-ZoneLockdown-rule-details -func (api *API) ZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ListZoneLockdowns retrieves a list of Zone ZoneLockdown rules for a given -// zone ID by page number. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-list-ZoneLockdown-rules -func (api *API) ListZoneLockdowns(zoneID string, page int) (*ZoneLockdownListResponse, error) { - v := url.Values{} - if page <= 0 { - page = 1 - } - - v.Set("page", strconv.Itoa(page)) - v.Set("per_page", strconv.Itoa(100)) - query := "?" + v.Encode() - - uri := "/zones/" + zoneID + "/firewall/lockdowns" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/options.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/options.go deleted file mode 100644 index 1a113ee..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/options.go +++ /dev/null @@ -1,90 +0,0 @@ -package cloudflare - -import ( - "net/http" - - "time" - - "golang.org/x/time/rate" -) - -// Option is a functional option for configuring the API client. -type Option func(*API) error - -// HTTPClient accepts a custom *http.Client for making API calls. -func HTTPClient(client *http.Client) Option { - return func(api *API) error { - api.httpClient = client - return nil - } -} - -// Headers allows you to set custom HTTP headers when making API calls (e.g. for -// satisfying HTTP proxies, or for debugging). -func Headers(headers http.Header) Option { - return func(api *API) error { - api.headers = headers - return nil - } -} - -// Organization allows you to apply account-level changes (Load Balancing, Railguns) -// to an organization instead. -func UsingOrganization(orgID string) Option { - return func(api *API) error { - api.organizationID = orgID - return nil - } -} - -// UsingRateLimit applies a non-default rate limit to client API requests -// If not specified the default of 4rps will be applied -func UsingRateLimit(rps float64) Option { - return func(api *API) error { - // because ratelimiter doesnt do any windowing - // setting burst makes it difficult to enforce a fixed rate - // so setting it equal to 1 this effectively disables bursting - // this doesn't check for sensible values, ultimately the api will enforce that the value is ok - api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1) - return nil - } -} - -// UsingRetryPolicy applies a non-default number of retries and min/max retry delays -// This will be used when the client exponentially backs off after errored requests -func UsingRetryPolicy(maxRetries int, minRetryDelaySecs int, maxRetryDelaySecs int) Option { - // seconds is very granular for a minimum delay - but this is only in case of failure - return func(api *API) error { - api.retryPolicy = RetryPolicy{ - MaxRetries: maxRetries, - MinRetryDelay: time.Duration(minRetryDelaySecs) * time.Second, - MaxRetryDelay: time.Duration(maxRetryDelaySecs) * time.Second, - } - return nil - } -} - -// UsingLogger can be set if you want to get log output from this API instance -// By default no log output is emitted -func UsingLogger(logger Logger) Option { - return func(api *API) error { - api.logger = logger - return nil - } -} - -// parseOptions parses the supplied options functions and returns a configured -// *API instance. -func (api *API) parseOptions(opts ...Option) error { - // Range over each options function and apply it to our API type to - // configure it. Options functions are applied in order, with any - // conflicting options overriding earlier calls. - for _, option := range opts { - err := option(api) - if err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/organizations.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/organizations.go deleted file mode 100644 index 97a67e7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/organizations.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// Organization represents a multi-user organization. -type Organization struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Status string `json:"status,omitempty"` - Permissions []string `json:"permissions,omitempty"` - Roles []string `json:"roles,omitempty"` -} - -// organizationResponse represents the response from the Organization endpoint. -type organizationResponse struct { - Response - Result []Organization `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationMember has details on a member. -type OrganizationMember struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Email string `json:"email,omitempty"` - Status string `json:"status,omitempty"` - Roles []OrganizationRole `json:"roles,omitempty"` -} - -// OrganizationInvite has details on an invite. -type OrganizationInvite struct { - ID string `json:"id,omitempty"` - InvitedMemberID string `json:"invited_member_id,omitempty"` - InvitedMemberEmail string `json:"invited_member_email,omitempty"` - OrganizationID string `json:"organization_id,omitempty"` - OrganizationName string `json:"organization_name,omitempty"` - Roles []OrganizationRole `json:"roles,omitempty"` - InvitedBy string `json:"invited_by,omitempty"` - InvitedOn *time.Time `json:"invited_on,omitempty"` - ExpiresOn *time.Time `json:"expires_on,omitempty"` - Status string `json:"status,omitempty"` -} - -// OrganizationRole has details on a role. -type OrganizationRole struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Permissions []string `json:"permissions,omitempty"` -} - -// OrganizationDetails represents details of an organization. -type OrganizationDetails struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Members []OrganizationMember `json:"members"` - Invites []OrganizationInvite `json:"invites"` - Roles []OrganizationRole `json:"roles,omitempty"` -} - -// organizationDetailsResponse represents the response from the OrganizationDetails endpoint. -type organizationDetailsResponse struct { - Response - Result OrganizationDetails `json:"result"` -} - -// ListOrganizations lists organizations of the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-s-organizations-list-organizations -func (api *API) ListOrganizations() ([]Organization, ResultInfo, error) { - var r organizationResponse - res, err := api.makeRequest("GET", "/user/organizations", nil) - if err != nil { - return []Organization{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []Organization{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} - -// OrganizationDetails returns details for the specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organizations-organization-details -func (api *API) OrganizationDetails(organizationID string) (OrganizationDetails, error) { - var r organizationDetailsResponse - uri := "/organizations/" + organizationID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return OrganizationDetails{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return OrganizationDetails{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// organizationMembersResponse represents the response from the Organization members endpoint. -type organizationMembersResponse struct { - Response - Result []OrganizationMember `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationMembers returns list of members for specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organization-members-list-members -func (api *API) OrganizationMembers(organizationID string) ([]OrganizationMember, ResultInfo, error) { - var r organizationMembersResponse - uri := "/organizations/" + organizationID + "/members" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []OrganizationMember{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []OrganizationMember{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} - -// organizationInvitesResponse represents the response from the Organization invites endpoint. -type organizationInvitesResponse struct { - Response - Result []OrganizationInvite `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationMembers returns list of invites for specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organization-invites -func (api *API) OrganizationInvites(organizationID string) ([]OrganizationInvite, ResultInfo, error) { - var r organizationInvitesResponse - uri := "/organizations/" + organizationID + "/invites" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []OrganizationInvite{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []OrganizationInvite{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} - -// organizationRolesResponse represents the response from the Organization roles endpoint. -type organizationRolesResponse struct { - Response - Result []OrganizationRole `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationRoles returns list of roles for specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organization-roles-list-roles -func (api *API) OrganizationRoles(organizationID string) ([]OrganizationRole, ResultInfo, error) { - var r organizationRolesResponse - uri := "/organizations/" + organizationID + "/roles" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []OrganizationRole{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []OrganizationRole{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go deleted file mode 100644 index 486033a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go +++ /dev/null @@ -1,168 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// OriginCACertificate represents a Cloudflare-issued certificate. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca -type OriginCACertificate struct { - ID string `json:"id"` - Certificate string `json:"certificate"` - Hostnames []string `json:"hostnames"` - ExpiresOn time.Time `json:"expires_on"` - RequestType string `json:"request_type"` - RequestValidity int `json:"requested_validity"` - CSR string `json:"csr"` -} - -// OriginCACertificateListOptions represents the parameters used to list Cloudflare-issued certificates. -type OriginCACertificateListOptions struct { - ZoneID string -} - -// OriginCACertificateID represents the ID of the revoked certificate from the Revoke Certificate endpoint. -type OriginCACertificateID struct { - ID string `json:"id"` -} - -// originCACertificateResponse represents the response from the Create Certificate and the Certificate Details endpoints. -type originCACertificateResponse struct { - Response - Result OriginCACertificate `json:"result"` -} - -// originCACertificateResponseList represents the response from the List Certificates endpoint. -type originCACertificateResponseList struct { - Response - Result []OriginCACertificate `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// originCACertificateResponseRevoke represents the response from the Revoke Certificate endpoint. -type originCACertificateResponseRevoke struct { - Response - Result OriginCACertificateID `json:"result"` -} - -// CreateOriginCertificate creates a Cloudflare-signed certificate. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-create-certificate -func (api *API) CreateOriginCertificate(certificate OriginCACertificate) (*OriginCACertificate, error) { - uri := "/certificates" - res, err := api.makeRequestWithAuthType("POST", uri, certificate, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponse - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// OriginCertificates lists all Cloudflare-issued certificates. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-list-certificates -func (api *API) OriginCertificates(options OriginCACertificateListOptions) ([]OriginCACertificate, error) { - v := url.Values{} - if options.ZoneID != "" { - v.Set("zone_id", options.ZoneID) - } - uri := "/certificates" + "?" + v.Encode() - res, err := api.makeRequestWithAuthType("GET", uri, nil, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponseList - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return originResponse.Result, nil -} - -// OriginCertificate returns the details for a Cloudflare-issued certificate. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-certificate-details -func (api *API) OriginCertificate(certificateID string) (*OriginCACertificate, error) { - uri := "/certificates/" + certificateID - res, err := api.makeRequestWithAuthType("GET", uri, nil, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponse - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// RevokeOriginCertificate revokes a created certificate for a zone. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-revoke-certificate -func (api *API) RevokeOriginCertificate(certificateID string) (*OriginCACertificateID, error) { - uri := "/certificates/" + certificateID - res, err := api.makeRequestWithAuthType("DELETE", uri, nil, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponseRevoke - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/page_rules.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/page_rules.go deleted file mode 100644 index 8749b2c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/page_rules.go +++ /dev/null @@ -1,206 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// PageRuleTarget is the target to evaluate on a request. -// -// Currently Target must always be "url" and Operator must be "matches". Value -// is the URL pattern to match against. -type PageRuleTarget struct { - Target string `json:"target"` - Constraint struct { - Operator string `json:"operator"` - Value string `json:"value"` - } `json:"constraint"` -} - -/* -PageRuleAction is the action to take when the target is matched. - -Valid IDs are: - - always_online - always_use_https - browser_cache_ttl - browser_check - cache_level - disable_apps - disable_performance - disable_railgun - disable_security - edge_cache_ttl - email_obfuscation - forwarding_url - ip_geolocation - mirage - rocket_loader - security_level - server_side_exclude - smart_errors - ssl - waf -*/ -type PageRuleAction struct { - ID string `json:"id"` - Value interface{} `json:"value"` -} - -// PageRuleActions maps API action IDs to human-readable strings. -var PageRuleActions = map[string]string{ - "always_online": "Always Online", // Value of type string - "always_use_https": "Always Use HTTPS", // Value of type interface{} - "browser_cache_ttl": "Browser Cache TTL", // Value of type int - "browser_check": "Browser Integrity Check", // Value of type string - "cache_level": "Cache Level", // Value of type string - "disable_apps": "Disable Apps", // Value of type interface{} - "disable_performance": "Disable Performance", // Value of type interface{} - "disable_railgun": "Disable Railgun", // Value of type string - "disable_security": "Disable Security", // Value of type interface{} - "edge_cache_ttl": "Edge Cache TTL", // Value of type int - "email_obfuscation": "Email Obfuscation", // Value of type string - "forwarding_url": "Forwarding URL", // Value of type map[string]interface - "ip_geolocation": "IP Geolocation Header", // Value of type string - "mirage": "Mirage", // Value of type string - "rocket_loader": "Rocker Loader", // Value of type string - "security_level": "Security Level", // Value of type string - "server_side_exclude": "Server Side Excludes", // Value of type string - "smart_errors": "Smart Errors", // Value of type string - "ssl": "SSL", // Value of type string - "waf": "Web Application Firewall", // Value of type string -} - -// PageRule describes a Page Rule. -type PageRule struct { - ID string `json:"id,omitempty"` - Targets []PageRuleTarget `json:"targets"` - Actions []PageRuleAction `json:"actions"` - Priority int `json:"priority"` - Status string `json:"status"` // can be: active, paused - ModifiedOn time.Time `json:"modified_on,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` -} - -// PageRuleDetailResponse is the API response, containing a single PageRule. -type PageRuleDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result PageRule `json:"result"` -} - -// PageRulesResponse is the API response, containing an array of PageRules. -type PageRulesResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result []PageRule `json:"result"` -} - -// CreatePageRule creates a new Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-create-a-page-rule -func (api *API) CreatePageRule(zoneID string, rule PageRule) (*PageRule, error) { - uri := "/zones/" + zoneID + "/pagerules" - res, err := api.makeRequest("POST", uri, rule) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return &r.Result, nil -} - -// ListPageRules returns all Page Rules for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-list-page-rules -func (api *API) ListPageRules(zoneID string) ([]PageRule, error) { - uri := "/zones/" + zoneID + "/pagerules" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []PageRule{}, errors.Wrap(err, errMakeRequestError) - } - var r PageRulesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []PageRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PageRule fetches detail about one Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-page-rule-details -func (api *API) PageRule(zoneID, ruleID string) (PageRule, error) { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return PageRule{}, errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PageRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ChangePageRule lets you change individual settings for a Page Rule. This is -// in contrast to UpdatePageRule which replaces the entire Page Rule. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-change-a-page-rule -func (api *API) ChangePageRule(zoneID, ruleID string, rule PageRule) error { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("PATCH", uri, rule) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// UpdatePageRule lets you replace a Page Rule. This is in contrast to -// ChangePageRule which lets you change individual settings. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-update-a-page-rule -func (api *API) UpdatePageRule(zoneID, ruleID string, rule PageRule) error { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("PUT", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeletePageRule deletes a Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-delete-a-page-rule -func (api *API) DeletePageRule(zoneID, ruleID string) error { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/railgun.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/railgun.go deleted file mode 100644 index 72d2286..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/railgun.go +++ /dev/null @@ -1,297 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// Railgun represents a Railgun's properties. -type Railgun struct { - ID string `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - Enabled bool `json:"enabled"` - ZonesConnected int `json:"zones_connected"` - Build string `json:"build"` - Version string `json:"version"` - Revision string `json:"revision"` - ActivationKey string `json:"activation_key"` - ActivatedOn time.Time `json:"activated_on"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - UpgradeInfo struct { - LatestVersion string `json:"latest_version"` - DownloadLink string `json:"download_link"` - } `json:"upgrade_info"` -} - -// RailgunListOptions represents the parameters used to list railguns. -type RailgunListOptions struct { - Direction string -} - -// railgunResponse represents the response from the Create Railgun and the Railgun Details endpoints. -type railgunResponse struct { - Response - Result Railgun `json:"result"` -} - -// railgunsResponse represents the response from the List Railguns endpoint. -type railgunsResponse struct { - Response - Result []Railgun `json:"result"` -} - -// CreateRailgun creates a new Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-create-railgun -func (api *API) CreateRailgun(name string) (Railgun, error) { - uri := api.userBaseURL("") + "/railguns" - params := struct { - Name string `json:"name"` - }{ - Name: name, - } - res, err := api.makeRequest("POST", uri, params) - if err != nil { - return Railgun{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListRailguns lists Railguns connected to an account. -// -// API reference: https://api.cloudflare.com/#railgun-list-railguns -func (api *API) ListRailguns(options RailgunListOptions) ([]Railgun, error) { - v := url.Values{} - if options.Direction != "" { - v.Set("direction", options.Direction) - } - uri := api.userBaseURL("") + "/railguns" + "?" + v.Encode() - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r railgunsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RailgunDetails returns the details for a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-railgun-details -func (api *API) RailgunDetails(railgunID string) (Railgun, error) { - uri := api.userBaseURL("") + "/railguns/" + railgunID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return Railgun{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RailgunZones returns the zones that are currently using a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-get-zones-connected-to-a-railgun -func (api *API) RailgunZones(railgunID string) ([]Zone, error) { - uri := api.userBaseURL("") + "/railguns/" + railgunID + "/zones" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r ZonesResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// enableRailgun enables (true) or disables (false) a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) enableRailgun(railgunID string, enable bool) (Railgun, error) { - uri := api.userBaseURL("") + "/railguns/" + railgunID - params := struct { - Enabled bool `json:"enabled"` - }{ - Enabled: enable, - } - res, err := api.makeRequest("PATCH", uri, params) - if err != nil { - return Railgun{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// EnableRailgun enables a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) EnableRailgun(railgunID string) (Railgun, error) { - return api.enableRailgun(railgunID, true) -} - -// DisableRailgun enables a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) DisableRailgun(railgunID string) (Railgun, error) { - return api.enableRailgun(railgunID, false) -} - -// DeleteRailgun disables and deletes a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-delete-railgun -func (api *API) DeleteRailgun(railgunID string) error { - uri := api.userBaseURL("") + "/railguns/" + railgunID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ZoneRailgun represents the status of a Railgun on a zone. -type ZoneRailgun struct { - ID string `json:"id"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - Connected bool `json:"connected"` -} - -// zoneRailgunResponse represents the response from the Zone Railgun Details endpoint. -type zoneRailgunResponse struct { - Response - Result ZoneRailgun `json:"result"` -} - -// zoneRailgunsResponse represents the response from the Zone Railgun endpoint. -type zoneRailgunsResponse struct { - Response - Result []ZoneRailgun `json:"result"` -} - -// RailgunDiagnosis represents the test results from testing railgun connections -// to a zone. -type RailgunDiagnosis struct { - Method string `json:"method"` - HostName string `json:"host_name"` - HTTPStatus int `json:"http_status"` - Railgun string `json:"railgun"` - URL string `json:"url"` - ResponseStatus string `json:"response_status"` - Protocol string `json:"protocol"` - ElapsedTime string `json:"elapsed_time"` - BodySize string `json:"body_size"` - BodyHash string `json:"body_hash"` - MissingHeaders string `json:"missing_headers"` - ConnectionClose bool `json:"connection_close"` - Cloudflare string `json:"cloudflare"` - CFRay string `json:"cf-ray"` - // NOTE: Cloudflare's online API documentation does not yet have definitions - // for the following fields. See: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection/ - CFWANError string `json:"cf-wan-error"` - CFCacheStatus string `json:"cf-cache-status"` -} - -// railgunDiagnosisResponse represents the response from the Test Railgun Connection enpoint. -type railgunDiagnosisResponse struct { - Response - Result RailgunDiagnosis `json:"result"` -} - -// ZoneRailguns returns the available Railguns for a zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-available-railguns -func (api *API) ZoneRailguns(zoneID string) ([]ZoneRailgun, error) { - uri := "/zones/" + zoneID + "/railguns" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneRailgunsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneRailgunDetails returns the configuration for a given Railgun. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-railgun-details -func (api *API) ZoneRailgunDetails(zoneID, railgunID string) (ZoneRailgun, error) { - uri := "/zones/" + zoneID + "/railguns/" + railgunID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneRailgun{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneRailgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// TestRailgunConnection tests a Railgun connection for a given zone. -// -// API reference: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection -func (api *API) TestRailgunConnection(zoneID, railgunID string) (RailgunDiagnosis, error) { - uri := "/zones/" + zoneID + "/railguns/" + railgunID + "/diagnose" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return RailgunDiagnosis{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunDiagnosisResponse - if err := json.Unmarshal(res, &r); err != nil { - return RailgunDiagnosis{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// connectZoneRailgun connects (true) or disconnects (false) a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) connectZoneRailgun(zoneID, railgunID string, connect bool) (ZoneRailgun, error) { - uri := "/zones/" + zoneID + "/railguns/" + railgunID - params := struct { - Connected bool `json:"connected"` - }{ - Connected: connect, - } - res, err := api.makeRequest("PATCH", uri, params) - if err != nil { - return ZoneRailgun{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneRailgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ConnectZoneRailgun connects a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) ConnectZoneRailgun(zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(zoneID, railgunID, true) -} - -// DisconnectZoneRailgun disconnects a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) DisconnectZoneRailgun(zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(zoneID, railgunID, false) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go deleted file mode 100644 index 96ad70e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go +++ /dev/null @@ -1,195 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// RateLimit is a policy than can be applied to limit traffic within a customer domain -type RateLimit struct { - ID string `json:"id,omitempty"` - Disabled bool `json:"disabled,omitempty"` - Description string `json:"description,omitempty"` - Match RateLimitTrafficMatcher `json:"match"` - Bypass []RateLimitKeyValue `json:"bypass,omitempty"` - Threshold int `json:"threshold"` - Period int `json:"period"` - Action RateLimitAction `json:"action"` -} - -// RateLimitTrafficMatcher contains the rules that will be used to apply a rate limit to traffic -type RateLimitTrafficMatcher struct { - Request RateLimitRequestMatcher `json:"request"` - Response RateLimitResponseMatcher `json:"response"` -} - -// RateLimitRequestMatcher contains the matching rules pertaining to requests -type RateLimitRequestMatcher struct { - Methods []string `json:"methods,omitempty"` - Schemes []string `json:"schemes,omitempty"` - URLPattern string `json:"url,omitempty"` -} - -// RateLimitResponseMatcher contains the matching rules pertaining to responses -type RateLimitResponseMatcher struct { - Statuses []int `json:"status,omitempty"` - OriginTraffic *bool `json:"origin_traffic,omitempty"` // api defaults to true so we need an explicit empty value -} - -// RateLimitKeyValue is k-v formatted as expected in the rate limit description -type RateLimitKeyValue struct { - Name string `json:"name"` - Value string `json:"value"` -} - -// RateLimitAction is the action that will be taken when the rate limit threshold is reached -type RateLimitAction struct { - Mode string `json:"mode"` - Timeout int `json:"timeout"` - Response *RateLimitActionResponse `json:"response"` -} - -// RateLimitActionResponse is the response that will be returned when rate limit action is triggered -type RateLimitActionResponse struct { - ContentType string `json:"content_type"` - Body string `json:"body"` -} - -type rateLimitResponse struct { - Response - Result RateLimit `json:"result"` -} - -type rateLimitListResponse struct { - Response - Result []RateLimit `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// CreateRateLimit creates a new rate limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-create-a-ratelimit -func (api *API) CreateRateLimit(zoneID string, limit RateLimit) (RateLimit, error) { - uri := "/zones/" + zoneID + "/rate_limits" - res, err := api.makeRequest("POST", uri, limit) - if err != nil { - return RateLimit{}, errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - if err := json.Unmarshal(res, &r); err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListRateLimits returns Rate Limits for a zone, paginated according to the provided options -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := "/zones/" + zoneID + "/rate_limits" - if len(v) > 0 { - uri = uri + "?" + v.Encode() - } - - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - var r rateLimitListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, r.ResultInfo, nil -} - -// ListAllRateLimits returns all Rate Limits for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) { - pageOpts := PaginationOptions{ - PerPage: 100, // this is the max page size allowed - Page: 1, - } - - allRateLimits := make([]RateLimit, 0) - for { - rateLimits, resultInfo, err := api.ListRateLimits(zoneID, pageOpts) - if err != nil { - return []RateLimit{}, err - } - allRateLimits = append(allRateLimits, rateLimits...) - // total pages is not returned on this call - // if number of records is less than the max, this must be the last page - // in case TotalCount % PerPage = 0, the last request will return an empty list - if resultInfo.Count < resultInfo.PerPage { - break - } - // continue with the next page - pageOpts.Page = pageOpts.Page + 1 - } - - return allRateLimits, nil -} - -// RateLimit fetches detail about one Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-rate-limit-details -func (api *API) RateLimit(zoneID, limitID string) (RateLimit, error) { - uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return RateLimit{}, errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - err = json.Unmarshal(res, &r) - if err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateRateLimit lets you replace a Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-update-rate-limit -func (api *API) UpdateRateLimit(zoneID, limitID string, limit RateLimit) (RateLimit, error) { - uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("PUT", uri, limit) - if err != nil { - return RateLimit{}, errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - if err := json.Unmarshal(res, &r); err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteRateLimit deletes a Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-delete-rate-limit -func (api *API) DeleteRateLimit(zoneID, limitID string) error { - uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/ssl.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/ssl.go deleted file mode 100644 index def81ea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/ssl.go +++ /dev/null @@ -1,148 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// ZoneCustomSSL represents custom SSL certificate metadata. -type ZoneCustomSSL struct { - ID string `json:"id"` - Hosts []string `json:"hosts"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - Status string `json:"status"` - BundleMethod string `json:"bundle_method"` - ZoneID string `json:"zone_id"` - UploadedOn time.Time `json:"uploaded_on"` - ModifiedOn time.Time `json:"modified_on"` - ExpiresOn time.Time `json:"expires_on"` - Priority int `json:"priority"` - KeylessServer KeylessSSL `json:"keyless_server"` -} - -// zoneCustomSSLResponse represents the response from the zone SSL details endpoint. -type zoneCustomSSLResponse struct { - Response - Result ZoneCustomSSL `json:"result"` -} - -// zoneCustomSSLsResponse represents the response from the zone SSL list endpoint. -type zoneCustomSSLsResponse struct { - Response - Result []ZoneCustomSSL `json:"result"` -} - -// ZoneCustomSSLOptions represents the parameters to create or update an existing -// custom SSL configuration. -type ZoneCustomSSLOptions struct { - Certificate string `json:"certificate"` - PrivateKey string `json:"private_key"` - BundleMethod string `json:"bundle_method,omitempty"` -} - -// ZoneCustomSSLPriority represents a certificate's ID and priority. It is a -// subset of ZoneCustomSSL used for patch requests. -type ZoneCustomSSLPriority struct { - ID string `json:"ID"` - Priority int `json:"priority"` -} - -// CreateSSL allows you to add a custom SSL certificate to the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-create-ssl-configuration -func (api *API) CreateSSL(zoneID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates" - res, err := api.makeRequest("POST", uri, options) - if err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListSSL lists the custom certificates for the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-list-ssl-configurations -func (api *API) ListSSL(zoneID string) ([]ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// SSLDetails returns the configuration details for a custom SSL certificate. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-ssl-configuration-details -func (api *API) SSLDetails(zoneID, certificateID string) (ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateSSL updates (replaces) a custom SSL certificate. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-update-ssl-configuration -func (api *API) UpdateSSL(zoneID, certificateID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - res, err := api.makeRequest("PATCH", uri, options) - if err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ReprioritizeSSL allows you to change the priority (which is served for a given -// request) of custom SSL certificates associated with the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-re-prioritize-ssl-certificates -func (api *API) ReprioritizeSSL(zoneID string, p []ZoneCustomSSLPriority) ([]ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates/prioritize" - params := struct { - Certificates []ZoneCustomSSLPriority `json:"certificates"` - }{ - Certificates: p, - } - res, err := api.makeRequest("PUT", uri, params) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteSSL deletes a custom SSL certificate from the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-delete-an-ssl-certificate -func (api *API) DeleteSSL(zoneID, certificateID string) error { - uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/user.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/user.go deleted file mode 100644 index b42641e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/user.go +++ /dev/null @@ -1,113 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// User describes a user account. -type User struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Username string `json:"username,omitempty"` - Telephone string `json:"telephone,omitempty"` - Country string `json:"country,omitempty"` - Zipcode string `json:"zipcode,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - APIKey string `json:"api_key,omitempty"` - TwoFA bool `json:"two_factor_authentication_enabled,omitempty"` - Betas []string `json:"betas,omitempty"` - Organizations []Organization `json:"organizations,omitempty"` -} - -// UserResponse wraps a response containing User accounts. -type UserResponse struct { - Response - Result User `json:"result"` -} - -// userBillingProfileResponse wraps a response containing Billing Profile information. -type userBillingProfileResponse struct { - Response - Result UserBillingProfile -} - -// UserBillingProfile contains Billing Profile information. -type UserBillingProfile struct { - ID string `json:"id,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Address string `json:"address,omitempty"` - Address2 string `json:"address2,omitempty"` - Company string `json:"company,omitempty"` - City string `json:"city,omitempty"` - State string `json:"state,omitempty"` - ZipCode string `json:"zipcode,omitempty"` - Country string `json:"country,omitempty"` - Telephone string `json:"telephone,omitempty"` - CardNumber string `json:"card_number,omitempty"` - CardExpiryYear int `json:"card_expiry_year,omitempty"` - CardExpiryMonth int `json:"card_expiry_month,omitempty"` - VAT string `json:"vat,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - EditedOn *time.Time `json:"edited_on,omitempty"` -} - -// UserDetails provides information about the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-user-details -func (api *API) UserDetails() (User, error) { - var r UserResponse - res, err := api.makeRequest("GET", "/user", nil) - if err != nil { - return User{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return User{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateUser updates the properties of the given user. -// -// API reference: https://api.cloudflare.com/#user-update-user -func (api *API) UpdateUser(user *User) (User, error) { - var r UserResponse - res, err := api.makeRequest("PATCH", "/user", user) - if err != nil { - return User{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return User{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UserBillingProfile returns the billing profile of the user. -// -// API reference: https://api.cloudflare.com/#user-billing-profile -func (api *API) UserBillingProfile() (UserBillingProfile, error) { - var r userBillingProfileResponse - res, err := api.makeRequest("GET", "/user/billing/profile", nil) - if err != nil { - return UserBillingProfile{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return UserBillingProfile{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/user_agent.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/user_agent.go deleted file mode 100644 index 6d75f3a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/user_agent.go +++ /dev/null @@ -1,149 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// UserAgentRule represents a User-Agent Block. These rules can be used to -// challenge, block or whitelist specific User-Agents for a given zone. -type UserAgentRule struct { - ID string `json:"id"` - Description string `json:"description"` - Mode string `json:"mode"` - Configuration UserAgentRuleConfig `json:"configuration"` - Paused bool `json:"paused"` -} - -// UserAgentRuleConfig represents a Zone Lockdown config, which comprises -// a Target ("ip" or "ip_range") and a Value (an IP address or IP+mask, -// respectively.) -type UserAgentRuleConfig ZoneLockdownConfig - -// UserAgentRuleResponse represents a response from the Zone Lockdown endpoint. -type UserAgentRuleResponse struct { - Result UserAgentRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// UserAgentRuleListResponse represents a response from the List Zone Lockdown endpoint. -type UserAgentRuleListResponse struct { - Result []UserAgentRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateUserAgentRule creates a User-Agent Block rule for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-create-a-useragent-rule -func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) { - switch ld.Mode { - case "block", "challenge", "js_challenge", "whitelist": - break - default: - return nil, errors.New(`the User-Agent Block rule mode must be one of "block", "challenge", "js_challenge", "whitelist"`) - } - - uri := "/zones/" + zoneID + "/firewall/ua_rules" - res, err := api.makeRequest("POST", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateUserAgentRule updates a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-update-useragent-rule -func (api *API) UpdateUserAgentRule(zoneID string, id string, ld UserAgentRule) (*UserAgentRuleResponse, error) { - uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("PUT", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// DeleteUserAgentRule deletes a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-delete-useragent-rule -func (api *API) DeleteUserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, error) { - uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UserAgentRule retrieves a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-useragent-rule-details -func (api *API) UserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, error) { - uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ListUserAgentRules retrieves a list of User-Agent Block rules for a given zone ID by page number. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-list-useragent-rules -func (api *API) ListUserAgentRules(zoneID string, page int) (*UserAgentRuleListResponse, error) { - v := url.Values{} - if page <= 0 { - page = 1 - } - - v.Set("page", strconv.Itoa(page)) - v.Set("per_page", strconv.Itoa(100)) - query := "?" + v.Encode() - - uri := "/zones/" + zoneID + "/firewall/ua_rules" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go deleted file mode 100644 index 6eb7629..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - - "github.com/pkg/errors" -) - -// VirtualDNS represents a Virtual DNS configuration. -type VirtualDNS struct { - ID string `json:"id"` - Name string `json:"name"` - OriginIPs []string `json:"origin_ips"` - VirtualDNSIPs []string `json:"virtual_dns_ips"` - MinimumCacheTTL uint `json:"minimum_cache_ttl"` - MaximumCacheTTL uint `json:"maximum_cache_ttl"` - DeprecateAnyRequests bool `json:"deprecate_any_requests"` - ModifiedOn string `json:"modified_on"` -} - -// VirtualDNSResponse represents a Virtual DNS response. -type VirtualDNSResponse struct { - Response - Result *VirtualDNS `json:"result"` -} - -// VirtualDNSListResponse represents an array of Virtual DNS responses. -type VirtualDNSListResponse struct { - Response - Result []*VirtualDNS `json:"result"` -} - -// CreateVirtualDNS creates a new Virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--create-a-virtual-dns-cluster -func (api *API) CreateVirtualDNS(v *VirtualDNS) (*VirtualDNS, error) { - res, err := api.makeRequest("POST", "/user/virtual_dns", v) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// VirtualDNS fetches a single virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--get-a-virtual-dns-cluster -func (api *API) VirtualDNS(virtualDNSID string) (*VirtualDNS, error) { - uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// ListVirtualDNS lists the virtual DNS clusters associated with an account. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--get-virtual-dns-clusters -func (api *API) ListVirtualDNS() ([]*VirtualDNS, error) { - res, err := api.makeRequest("GET", "/user/virtual_dns", nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// UpdateVirtualDNS updates a Virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--modify-a-virtual-dns-cluster -func (api *API) UpdateVirtualDNS(virtualDNSID string, vv VirtualDNS) error { - uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("PUT", uri, vv) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// DeleteVirtualDNS deletes a Virtual DNS cluster. Note that this cannot be -// undone, and will stop all traffic to that cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--delete-a-virtual-dns-cluster -func (api *API) DeleteVirtualDNS(virtualDNSID string) error { - uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/waf.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/waf.go deleted file mode 100644 index 4ed1562..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/waf.go +++ /dev/null @@ -1,97 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - - "github.com/pkg/errors" -) - -// WAFPackage represents a WAF package configuration. -type WAFPackage struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - ZoneID string `json:"zone_id"` - DetectionMode string `json:"detection_mode"` - Sensitivity string `json:"sensitivity"` - ActionMode string `json:"action_mode"` -} - -// WAFPackagesResponse represents the response from the WAF packages endpoint. -type WAFPackagesResponse struct { - Response - Result []WAFPackage `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFRule represents a WAF rule. -type WAFRule struct { - ID string `json:"id"` - Description string `json:"description"` - Priority string `json:"priority"` - PackageID string `json:"package_id"` - Group struct { - ID string `json:"id"` - Name string `json:"name"` - } `json:"group"` - Mode string `json:"mode"` - DefaultMode string `json:"default_mode"` - AllowedModes []string `json:"allowed_modes"` -} - -// WAFRulesResponse represents the response from the WAF rule endpoint. -type WAFRulesResponse struct { - Response - Result []WAFRule `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// ListWAFPackages returns a slice of the WAF packages for the given zone. -func (api *API) ListWAFPackages(zoneID string) ([]WAFPackage, error) { - var p WAFPackagesResponse - var packages []WAFPackage - var res []byte - var err error - uri := "/zones/" + zoneID + "/firewall/waf/packages" - res, err = api.makeRequest("GET", uri, nil) - if err != nil { - return []WAFPackage{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &p) - if err != nil { - return []WAFPackage{}, errors.Wrap(err, errUnmarshalError) - } - if !p.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFPackage{}, err - } - for pi := range p.Result { - packages = append(packages, p.Result[pi]) - } - return packages, nil -} - -// ListWAFRules returns a slice of the WAF rules for the given WAF package. -func (api *API) ListWAFRules(zoneID, packageID string) ([]WAFRule, error) { - var r WAFRulesResponse - var rules []WAFRule - var res []byte - var err error - uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/rules" - res, err = api.makeRequest("GET", uri, nil) - if err != nil { - return []WAFRule{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &r) - if err != nil { - return []WAFRule{}, errors.Wrap(err, errUnmarshalError) - } - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFRule{}, err - } - for ri := range r.Result { - rules = append(rules, r.Result[ri]) - } - return rules, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/zone.go b/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/zone.go deleted file mode 100644 index fe222d3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cloudflare/cloudflare-go/zone.go +++ /dev/null @@ -1,587 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "fmt" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// Owner describes the resource owner. -type Owner struct { - ID string `json:"id"` - Email string `json:"email"` - OwnerType string `json:"owner_type"` -} - -// Zone describes a Cloudflare zone. -type Zone struct { - ID string `json:"id"` - Name string `json:"name"` - // DevMode contains the time in seconds until development expires (if - // positive) or since it expired (if negative). It will be 0 if never used. - DevMode int `json:"development_mode"` - OriginalNS []string `json:"original_name_servers"` - OriginalRegistrar string `json:"original_registrar"` - OriginalDNSHost string `json:"original_dnshost"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - NameServers []string `json:"name_servers"` - Owner Owner `json:"owner"` - Permissions []string `json:"permissions"` - Plan ZoneRatePlan `json:"plan"` - PlanPending ZoneRatePlan `json:"plan_pending,omitempty"` - Status string `json:"status"` - Paused bool `json:"paused"` - Type string `json:"type"` - Host struct { - Name string - Website string - } `json:"host"` - VanityNS []string `json:"vanity_name_servers"` - Betas []string `json:"betas"` - DeactReason string `json:"deactivation_reason"` - Meta ZoneMeta `json:"meta"` -} - -// ZoneMeta describes metadata about a zone. -type ZoneMeta struct { - // custom_certificate_quota is broken - sometimes it's a string, sometimes a number! - // CustCertQuota int `json:"custom_certificate_quota"` - PageRuleQuota int `json:"page_rule_quota"` - WildcardProxiable bool `json:"wildcard_proxiable"` - PhishingDetected bool `json:"phishing_detected"` -} - -// ZoneRatePlan contains the plan information for a zone. -type ZoneRatePlan struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Price int `json:"price,omitempty"` - Currency string `json:"currency,omitempty"` - Duration int `json:"duration,omitempty"` - Frequency string `json:"frequency,omitempty"` - Components []zoneRatePlanComponents `json:"components,omitempty"` -} - -type zoneRatePlanComponents struct { - Name string `json:"name"` - Default int `json:"Default"` - UnitPrice int `json:"unit_price"` -} - -// ZoneID contains only the zone ID. -type ZoneID struct { - ID string `json:"id"` -} - -// ZoneResponse represents the response from the Zone endpoint containing a single zone. -type ZoneResponse struct { - Response - Result Zone `json:"result"` -} - -// ZonesResponse represents the response from the Zone endpoint containing an array of zones. -type ZonesResponse struct { - Response - Result []Zone `json:"result"` -} - -// ZoneIDResponse represents the response from the Zone endpoint, containing only a zone ID. -type ZoneIDResponse struct { - Response - Result ZoneID `json:"result"` -} - -// AvailableZoneRatePlansResponse represents the response from the Available Rate Plans endpoint. -type AvailableZoneRatePlansResponse struct { - Response - Result []ZoneRatePlan `json:"result"` - ResultInfo -} - -// ZoneRatePlanResponse represents the response from the Plan Details endpoint. -type ZoneRatePlanResponse struct { - Response - Result ZoneRatePlan `json:"result"` -} - -// ZoneSetting contains settings for a zone. -type ZoneSetting struct { - ID string `json:"id"` - Editable bool `json:"editable"` - ModifiedOn string `json:"modified_on"` - Value interface{} `json:"value"` - TimeRemaining int `json:"time_remaining"` -} - -// ZoneSettingResponse represents the response from the Zone Setting endpoint. -type ZoneSettingResponse struct { - Response - Result []ZoneSetting `json:"result"` -} - -// ZoneSSLSetting contains ssl setting for a zone. -type ZoneSSLSetting struct { - ID string `json:"id"` - Editable bool `json:"editable"` - ModifiedOn string `json:"modified_on"` - Value string `json:"value"` - CertificateStatus string `json:"certificate_status"` -} - -// ZoneSettingResponse represents the response from the Zone SSL Setting endpoint. -type ZoneSSLSettingResponse struct { - Response - Result ZoneSSLSetting `json:"result"` -} - -// ZoneAnalyticsData contains totals and timeseries analytics data for a zone. -type ZoneAnalyticsData struct { - Totals ZoneAnalytics `json:"totals"` - Timeseries []ZoneAnalytics `json:"timeseries"` -} - -// zoneAnalyticsDataResponse represents the response from the Zone Analytics Dashboard endpoint. -type zoneAnalyticsDataResponse struct { - Response - Result ZoneAnalyticsData `json:"result"` -} - -// ZoneAnalyticsColocation contains analytics data by datacenter. -type ZoneAnalyticsColocation struct { - ColocationID string `json:"colo_id"` - Timeseries []ZoneAnalytics `json:"timeseries"` -} - -// zoneAnalyticsColocationResponse represents the response from the Zone Analytics By Co-location endpoint. -type zoneAnalyticsColocationResponse struct { - Response - Result []ZoneAnalyticsColocation `json:"result"` -} - -// ZoneAnalytics contains analytics data for a zone. -type ZoneAnalytics struct { - Since time.Time `json:"since"` - Until time.Time `json:"until"` - Requests struct { - All int `json:"all"` - Cached int `json:"cached"` - Uncached int `json:"uncached"` - ContentType map[string]int `json:"content_type"` - Country map[string]int `json:"country"` - SSL struct { - Encrypted int `json:"encrypted"` - Unencrypted int `json:"unencrypted"` - } `json:"ssl"` - HTTPStatus map[string]int `json:"http_status"` - } `json:"requests"` - Bandwidth struct { - All int `json:"all"` - Cached int `json:"cached"` - Uncached int `json:"uncached"` - ContentType map[string]int `json:"content_type"` - Country map[string]int `json:"country"` - SSL struct { - Encrypted int `json:"encrypted"` - Unencrypted int `json:"unencrypted"` - } `json:"ssl"` - } `json:"bandwidth"` - Threats struct { - All int `json:"all"` - Country map[string]int `json:"country"` - Type map[string]int `json:"type"` - } `json:"threats"` - Pageviews struct { - All int `json:"all"` - SearchEngines map[string]int `json:"search_engines"` - } `json:"pageviews"` - Uniques struct { - All int `json:"all"` - } -} - -// ZoneAnalyticsOptions represents the optional parameters in Zone Analytics -// endpoint requests. -type ZoneAnalyticsOptions struct { - Since *time.Time - Until *time.Time - Continuous *bool -} - -// PurgeCacheRequest represents the request format made to the purge endpoint. -type PurgeCacheRequest struct { - Everything bool `json:"purge_everything,omitempty"` - // Purge by filepath (exact match). Limit of 30 - Files []string `json:"files,omitempty"` - // Purge by Tag (Enterprise only): - // https://support.cloudflare.com/hc/en-us/articles/206596608-How-to-Purge-Cache-Using-Cache-Tags-Enterprise-only- - Tags []string `json:"tags,omitempty"` - // Purge by hostname - e.g. "assets.example.com" - Hosts []string `json:"hosts,omitempty"` -} - -// PurgeCacheResponse represents the response from the purge endpoint. -type PurgeCacheResponse struct { - Response - Result struct { - ID string `json:"id"` - } `json:"result"` -} - -// newZone describes a new zone. -type newZone struct { - Name string `json:"name"` - JumpStart bool `json:"jump_start"` - // We use a pointer to get a nil type when the field is empty. - // This allows us to completely omit this with json.Marshal(). - Organization *Organization `json:"organization,omitempty"` -} - -// CreateZone creates a zone on an account. -// -// Setting jumpstart to true will attempt to automatically scan for existing -// DNS records. Setting this to false will create the zone with no DNS records. -// -// If Organization is non-empty, it must have at least the ID field populated. -// This will add the new zone to the specified multi-user organization. -// -// API reference: https://api.cloudflare.com/#zone-create-a-zone -func (api *API) CreateZone(name string, jumpstart bool, org Organization) (Zone, error) { - var newzone newZone - newzone.Name = name - newzone.JumpStart = jumpstart - if org.ID != "" { - newzone.Organization = &org - } - - res, err := api.makeRequest("POST", "/zones", newzone) - if err != nil { - return Zone{}, errors.Wrap(err, errMakeRequestError) - } - - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneActivationCheck initiates another zone activation check for newly-created zones. -// -// API reference: https://api.cloudflare.com/#zone-initiate-another-zone-activation-check -func (api *API) ZoneActivationCheck(zoneID string) (Response, error) { - res, err := api.makeRequest("PUT", "/zones/"+zoneID+"/activation_check", nil) - if err != nil { - return Response{}, errors.Wrap(err, errMakeRequestError) - } - var r Response - err = json.Unmarshal(res, &r) - if err != nil { - return Response{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// ListZones lists zones on an account. Optionally takes a list of zone names -// to filter against. -// -// API reference: https://api.cloudflare.com/#zone-list-zones -func (api *API) ListZones(z ...string) ([]Zone, error) { - v := url.Values{} - var res []byte - var r ZonesResponse - var zones []Zone - var err error - if len(z) > 0 { - for _, zone := range z { - v.Set("name", zone) - res, err = api.makeRequest("GET", "/zones?"+v.Encode(), nil) - if err != nil { - return []Zone{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &r) - if err != nil { - return []Zone{}, errors.Wrap(err, errUnmarshalError) - } - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []Zone{}, err - } - for zi := range r.Result { - zones = append(zones, r.Result[zi]) - } - } - } else { - // TODO: Paginate here. We only grab the first page of results. - // Could do this concurrently after the first request by creating a - // sync.WaitGroup or just a channel + workers. - res, err = api.makeRequest("GET", "/zones", nil) - if err != nil { - return []Zone{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &r) - if err != nil { - return []Zone{}, errors.Wrap(err, errUnmarshalError) - } - zones = r.Result - } - - return zones, nil -} - -// ZoneDetails fetches information about a zone. -// -// API reference: https://api.cloudflare.com/#zone-zone-details -func (api *API) ZoneDetails(zoneID string) (Zone, error) { - res, err := api.makeRequest("GET", "/zones/"+zoneID, nil) - if err != nil { - return Zone{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneOptions is a subset of Zone, for editable options. -type ZoneOptions struct { - Paused *bool `json:"paused,omitempty"` - VanityNS []string `json:"vanity_name_servers,omitempty"` - Plan *ZoneRatePlan `json:"plan,omitempty"` -} - -// ZoneSetPaused pauses Cloudflare service for the entire zone, sending all -// traffic direct to the origin. -func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) { - zoneopts := ZoneOptions{Paused: &paused} - zone, err := api.EditZone(zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// ZoneSetVanityNS sets custom nameservers for the zone. -// These names must be within the same zone. -func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) { - zoneopts := ZoneOptions{VanityNS: ns} - zone, err := api.EditZone(zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// ZoneSetRatePlan changes the zone plan. -func (api *API) ZoneSetRatePlan(zoneID string, plan ZoneRatePlan) (Zone, error) { - zoneopts := ZoneOptions{Plan: &plan} - zone, err := api.EditZone(zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// EditZone edits the given zone. -// -// This is usually called by ZoneSetPaused, ZoneSetVanityNS or ZoneSetPlan. -// -// API reference: https://api.cloudflare.com/#zone-edit-zone-properties -func (api *API) EditZone(zoneID string, zoneOpts ZoneOptions) (Zone, error) { - res, err := api.makeRequest("PATCH", "/zones/"+zoneID, zoneOpts) - if err != nil { - return Zone{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// PurgeEverything purges the cache for the given zone. -// -// Note: this will substantially increase load on the origin server for that -// zone if there is a high cached vs. uncached request ratio. -// -// API reference: https://api.cloudflare.com/#zone-purge-all-files -func (api *API) PurgeEverything(zoneID string) (PurgeCacheResponse, error) { - uri := "/zones/" + zoneID + "/purge_cache" - res, err := api.makeRequest("DELETE", uri, PurgeCacheRequest{true, nil, nil, nil}) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errMakeRequestError) - } - var r PurgeCacheResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// PurgeCache purges the cache using the given PurgeCacheRequest (zone/url/tag). -// -// API reference: https://api.cloudflare.com/#zone-purge-individual-files-by-url-and-cache-tags -func (api *API) PurgeCache(zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { - uri := "/zones/" + zoneID + "/purge_cache" - res, err := api.makeRequest("DELETE", uri, pcr) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errMakeRequestError) - } - var r PurgeCacheResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// DeleteZone deletes the given zone. -// -// API reference: https://api.cloudflare.com/#zone-delete-a-zone -func (api *API) DeleteZone(zoneID string) (ZoneID, error) { - res, err := api.makeRequest("DELETE", "/zones/"+zoneID, nil) - if err != nil { - return ZoneID{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneIDResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneID{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// AvailableZoneRatePlans returns information about all plans available to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-plan-available-plans -func (api *API) AvailableZoneRatePlans(zoneID string) ([]ZoneRatePlan, error) { - uri := "/zones/" + zoneID + "/available_rate_plans" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []ZoneRatePlan{}, errors.Wrap(err, errMakeRequestError) - } - var r AvailableZoneRatePlansResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []ZoneRatePlan{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// encode encodes non-nil fields into URL encoded form. -func (o ZoneAnalyticsOptions) encode() string { - v := url.Values{} - if o.Since != nil { - v.Set("since", (*o.Since).Format(time.RFC3339)) - } - if o.Until != nil { - v.Set("until", (*o.Until).Format(time.RFC3339)) - } - if o.Continuous != nil { - v.Set("continuous", fmt.Sprintf("%t", *o.Continuous)) - } - return v.Encode() -} - -// ZoneAnalyticsDashboard returns zone analytics information. -// -// API reference: https://api.cloudflare.com/#zone-analytics-dashboard -func (api *API) ZoneAnalyticsDashboard(zoneID string, options ZoneAnalyticsOptions) (ZoneAnalyticsData, error) { - uri := "/zones/" + zoneID + "/analytics/dashboard" + "?" + options.encode() - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneAnalyticsData{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneAnalyticsDataResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneAnalyticsData{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneAnalyticsByColocation returns zone analytics information by datacenter. -// -// API reference: https://api.cloudflare.com/#zone-analytics-analytics-by-co-locations -func (api *API) ZoneAnalyticsByColocation(zoneID string, options ZoneAnalyticsOptions) ([]ZoneAnalyticsColocation, error) { - uri := "/zones/" + zoneID + "/analytics/colos" + "?" + options.encode() - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneAnalyticsColocationResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneSettings returns all of the settings for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-all-zone-settings -func (api *API) ZoneSettings(zoneID string) (*ZoneSettingResponse, error) { - uri := "/zones/" + zoneID + "/settings" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneSettingResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateZoneSettings updates the settings for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-edit-zone-settings-info -func (api *API) UpdateZoneSettings(zoneID string, settings []ZoneSetting) (*ZoneSettingResponse, error) { - uri := "/zones/" + zoneID + "/settings" - res, err := api.makeRequest("PATCH", uri, struct { - Items []ZoneSetting `json:"items"` - }{settings}) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneSettingResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneSSLSettings returns information about SSL setting to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-ssl-setting -func (api *API) ZoneSSLSettings(zoneID string) (ZoneSSLSetting, error) { - uri := "/zones/" + zoneID + "/settings/ssl" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneSSLSetting{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneSSLSettingResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneSSLSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/LICENSE deleted file mode 100644 index 3215897..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Daniel McCarney - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/account.go b/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/account.go deleted file mode 100644 index 9a1d9c8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/account.go +++ /dev/null @@ -1,11 +0,0 @@ -package goacmedns - -// Account is a struct that holds the registration response from an ACME-DNS -// server. It represents an API username/key that can be used to update TXT -// records for the account's subdomain. -type Account struct { - FullDomain string - SubDomain string - Username string - Password string -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/client.go deleted file mode 100644 index 8be7030..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/client.go +++ /dev/null @@ -1,191 +0,0 @@ -package goacmedns - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "runtime" - "time" -) - -const ( - // ua is a custom user-agent identifier - ua = "goacmedns" -) - -// userAgent returns a string that can be used as a HTTP request `User-Agent` -// header. It includes the `ua` string alongside the OS and architecture of the -// system. -func userAgent() string { - return fmt.Sprintf("%s (%s; %s)", ua, runtime.GOOS, runtime.GOARCH) -} - -var ( - // defaultTimeout is used for the httpClient Timeout settings - defaultTimeout = 30 * time.Second - // httpClient is a `http.Client` that is customized with the `defaultTimeout` - httpClient = http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: defaultTimeout, - KeepAlive: defaultTimeout, - }).Dial, - TLSHandshakeTimeout: defaultTimeout, - ResponseHeaderTimeout: defaultTimeout, - ExpectContinueTimeout: 1 * time.Second, - }, - } -) - -// postAPI makes an HTTP POST request to the given URL, sending the given body -// and attaching the requested custom headers to the request. If there is no -// error the HTTP response body and HTTP response object are returned, otherwise -// an error is returned.. All POST requests include a `User-Agent` header -// populated with the `userAgent` function and a `Content-Type` header of -// `application/json`. -func postAPI(url string, body []byte, headers map[string]string) ([]byte, *http.Response, error) { - req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(body)) - if err != nil { - fmt.Printf("Failed to make req: %s\n", err.Error()) - return nil, nil, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", userAgent()) - for h, v := range headers { - req.Header.Set(h, v) - } - - resp, err := httpClient.Do(req) - if err != nil { - fmt.Printf("Failed to do req: %s\n", err.Error()) - return nil, resp, err - } - defer func() { _ = resp.Body.Close() }() - - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Printf("Failed to read body: %s\n", err.Error()) - return nil, resp, err - } - return respBody, resp, nil -} - -// ClientError represents an error from the ACME-DNS server. It holds -// a `Message` describing the operation the client was doing, a `HTTPStatus` -// code returned by the server, and the `Body` of the HTTP Response from the -// server. -type ClientError struct { - // Message is a string describing the client operation that failed - Message string - // HTTPStatus is the HTTP status code the ACME DNS server returned - HTTPStatus int - // Body is the response body the ACME DNS server returned - Body []byte -} - -// Error collects all of the ClientError fields into a single string -func (e ClientError) Error() string { - return fmt.Sprintf("%s : status code %d response: %s", - e.Message, e.HTTPStatus, string(e.Body)) -} - -// newClientError creates a ClientError instance populated with the given -// arguments -func newClientError(msg string, respCode int, respBody []byte) ClientError { - return ClientError{ - Message: msg, - HTTPStatus: respCode, - Body: respBody, - } -} - -// Client is a struct that can be used to interact with an ACME DNS server to -// register accounts and update TXT records. -type Client struct { - // baseURL is the address of the ACME DNS server - baseURL string -} - -// NewClient returns a Client configured to interact with the ACME DNS server at -// the given URL. -func NewClient(url string) Client { - return Client{ - baseURL: url, - } -} - -// RegisterAccount creates an Account with the ACME DNS server. The optional -// `allowFrom` argument is used to constrain which CIDR ranges can use the -// created Account. -func (c Client) RegisterAccount(allowFrom []string) (Account, error) { - var body []byte - if len(allowFrom) > 0 { - req := struct { - AllowFrom []string - }{ - AllowFrom: allowFrom, - } - reqBody, err := json.Marshal(req) - if err != nil { - return Account{}, err - } - body = reqBody - } - - url := fmt.Sprintf("%s/register", c.baseURL) - respBody, resp, err := postAPI(url, body, nil) - if err != nil { - return Account{}, err - } - - if resp.StatusCode != http.StatusCreated { - return Account{}, newClientError( - "failed to register account", resp.StatusCode, respBody) - } - - var acct Account - err = json.Unmarshal(respBody, &acct) - if err != nil { - return Account{}, err - } - - return acct, nil -} - -// UpdateTXTRecord updates a TXT record with the ACME DNS server to the `value` -// provided using the `account` specified. -func (c Client) UpdateTXTRecord(account Account, value string) error { - update := struct { - SubDomain string - Txt string - }{ - SubDomain: account.SubDomain, - Txt: value, - } - updateBody, err := json.Marshal(update) - if err != nil { - fmt.Printf("Failed to marshal update: %s\n", update) - return err - } - - headers := map[string]string{ - "X-Api-User": account.Username, - "X-Api-Key": account.Password, - } - - url := fmt.Sprintf("%s/update", c.baseURL) - respBody, resp, err := postAPI(url, updateBody, headers) - if err != nil { - return err - } - - if resp.StatusCode != http.StatusOK { - return newClientError( - "failed to update txt record", resp.StatusCode, respBody) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/storage.go b/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/storage.go deleted file mode 100644 index 6e0186b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/cpu/goacmedns/storage.go +++ /dev/null @@ -1,89 +0,0 @@ -package goacmedns - -import ( - "encoding/json" - "errors" - "io/ioutil" - "os" -) - -// Storage is an interface describing the required functions for an ACME DNS -// Account storage mechanism. -type Storage interface { - // Save will persist the `Account` data that has been `Put` so far - Save() error - // Put will add an `Account` for the given domain to the storage. It may not - // be persisted until `Save` is called. - Put(string, Account) error - // Fetch will retrieve an `Account` for the given domain from the storage. If - // the provided domain does not have an `Account` saved in the storage - // `ErrDomainNotFound` will be returned - Fetch(string) (Account, error) -} - -var ( - // ErrDomainNotFound is returned from `Fetch` when the provided domain is not - // present in the storage. - ErrDomainNotFound = errors.New("requested domain is not present in storage") -) - -// fileStorage implements the `Storage` interface and persists `Accounts` to -// a JSON file on disk. -type fileStorage struct { - // path is the filepath that the `accounts` are persisted to when the `Save` - // function is called. - path string - // mode is the file mode used when the `path` JSON file must be created - mode os.FileMode - // accounts holds the `Account` data that has been `Put` into the storage - accounts map[string]Account -} - -// NewFileStorage returns a `Storage` implementation backed by JSON content -// saved into the provided `path` on disk. The file at `path` will be created if -// required. When creating a new file the provided `mode` is used to set the -// permissions. -func NewFileStorage(path string, mode os.FileMode) Storage { - fs := fileStorage{ - path: path, - mode: mode, - accounts: make(map[string]Account), - } - // Opportunistically try to load the account data. Return an empty account if - // any errors occur. - if jsonData, err := ioutil.ReadFile(path); err == nil { - if err := json.Unmarshal(jsonData, &fs.accounts); err != nil { - return fs - } - } - return fs -} - -// Save persists the `Account` data to the fileStorage's configured path. The -// file at that path will be created with the fileStorage's mode if required. -func (f fileStorage) Save() error { - if serialized, err := json.Marshal(f.accounts); err != nil { - return err - } else if err = ioutil.WriteFile(f.path, serialized, f.mode); err != nil { - return err - } - return nil -} - -// Put saves an `Account` for the given `Domain` into the in-memory accounts of -// the fileStorage instance. The `Account` data will not be written to disk -// until the `Save` function is called -func (f fileStorage) Put(domain string, acct Account) error { - f.accounts[domain] = acct - return nil -} - -// Fetch retrieves the `Account` object for the given `domain` from the -// fileStorage in-memory accounts. If the `domain` provided does not have an -// `Account` in the storage an `ErrDomainNotFound` error is returned. -func (f fileStorage) Fetch(domain string) (Account, error) { - if acct, exists := f.accounts[domain]; exists { - return acct, nil - } - return Account{}, ErrDomainNotFound -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/LICENSE deleted file mode 100644 index bc52e96..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2012-2016 Dave Collins - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/bypass.go deleted file mode 100644 index 7929947..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2015-2016 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 the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// Go versions prior to 1.4 are disabled because they use a different layout -// for interfaces which make the implementation of unsafeReflectValue more complex. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -package spew - -import ( - "reflect" - "unsafe" -) - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = false - - // ptrSize is the size of a pointer on the current arch. - ptrSize = unsafe.Sizeof((*byte)(nil)) -) - -type flag uintptr - -var ( - // flagRO indicates whether the value field of a reflect.Value - // is read-only. - flagRO flag - - // flagAddr indicates whether the address of the reflect.Value's - // value may be taken. - flagAddr flag -) - -// flagKindMask holds the bits that make up the kind -// part of the flags field. In all the supported versions, -// it is in the lower 5 bits. -const flagKindMask = flag(0x1f) - -// Different versions of Go have used different -// bit layouts for the flags type. This table -// records the known combinations. -var okFlags = []struct { - ro, addr flag -}{{ - // From Go 1.4 to 1.5 - ro: 1 << 5, - addr: 1 << 7, -}, { - // Up to Go tip. - ro: 1<<5 | 1<<6, - addr: 1 << 8, -}} - -var flagValOffset = func() uintptr { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - return field.Offset -}() - -// flagField returns a pointer to the flag field of a reflect.Value. -func flagField(v *reflect.Value) *flag { - return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) -} - -// 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) reflect.Value { - if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { - return v - } - flagFieldPtr := flagField(&v) - *flagFieldPtr &^= flagRO - *flagFieldPtr |= flagAddr - return v -} - -// Sanity checks against future reflect package changes -// to the type or semantics of the Value.flag field. -func init() { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { - panic("reflect.Value flag field has changed kind") - } - type t0 int - var t struct { - A t0 - // t0 will have flagEmbedRO set. - t0 - // a will have flagStickyRO set - a t0 - } - vA := reflect.ValueOf(t).FieldByName("A") - va := reflect.ValueOf(t).FieldByName("a") - vt0 := reflect.ValueOf(t).FieldByName("t0") - - // Infer flagRO from the difference between the flags - // for the (otherwise identical) fields in t. - flagPublic := *flagField(&vA) - flagWithRO := *flagField(&va) | *flagField(&vt0) - flagRO = flagPublic ^ flagWithRO - - // Infer flagAddr from the difference between a value - // taken from a pointer and not. - vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") - flagNoPtr := *flagField(&vA) - flagPtr := *flagField(&vPtrA) - flagAddr = flagNoPtr ^ flagPtr - - // Check that the inferred flags tally with one of the known versions. - for _, f := range okFlags { - if flagRO == f.ro && flagAddr == f.addr { - return - } - } - panic("reflect.Value read-only flag has changed semantics") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go deleted file mode 100644 index 205c28d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2015-2016 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 the code is running on Google App Engine, compiled by GopherJS, or -// "-tags safe" is added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build js appengine safe disableunsafe !go1.4 - -package spew - -import "reflect" - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = true -) - -// unsafeReflectValue typically converts the passed reflect.Value into a one -// that bypasses the typical safety restrictions preventing access to -// unaddressable and unexported data. However, doing this relies on access to -// the unsafe package. This is a stub version which simply returns the passed -// reflect.Value when the unsafe package is not available. -func unsafeReflectValue(v reflect.Value) reflect.Value { - return v -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/common.go deleted file mode 100644 index 1be8ce9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/common.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright (c) 2013-2016 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" -) - -// 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, when it's available, - // to bypass these restrictions since this package does not mutate the - // values. - if !v.CanInterface() { - if UnsafeDisabled { - return false - } - - v = unsafeReflectValue(v) - } - - // Choose whether or not to do error and Stringer interface lookups against - // the base type or a pointer to the base type depending on settings. - // Technically calling one of these methods with a pointer receiver can - // mutate the value, however, types which choose to satisify an error or - // Stringer interface with a pointer receiver should not be mutating their - // state inside these interface methods. - if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { - v = unsafeReflectValue(v) - } - if v.CanAddr() { - v = v.Addr() - } - - // Is it an error or Stringer? - switch iface := v.Interface().(type) { - case error: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.Error())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - - w.Write([]byte(iface.Error())) - return true - - case fmt.Stringer: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.String())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - w.Write([]byte(iface.String())) - return true - } - return false -} - -// printBool outputs a boolean value as true or false to Writer w. -func printBool(w io.Writer, val bool) { - if val { - w.Write(trueBytes) - } else { - w.Write(falseBytes) - } -} - -// printInt outputs a signed integer value to Writer w. -func printInt(w io.Writer, val int64, base int) { - w.Write([]byte(strconv.FormatInt(val, base))) -} - -// printUint outputs an unsigned integer value to Writer w. -func printUint(w io.Writer, val uint64, base int) { - w.Write([]byte(strconv.FormatUint(val, base))) -} - -// printFloat outputs a floating point value using the specified precision, -// which is expected to be 32 or 64bit, to Writer w. -func printFloat(w io.Writer, val float64, precision int) { - w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) -} - -// printComplex outputs a complex value using the specified float precision -// for the real and imaginary parts to Writer w. -func printComplex(w io.Writer, c complex128, floatPrecision int) { - r := real(c) - w.Write(openParenBytes) - w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) - i := imag(c) - if i >= 0 { - w.Write(plusBytes) - } - w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) - w.Write(iBytes) - w.Write(closeParenBytes) -} - -// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' -// prefix to Writer w. -func printHexPtr(w io.Writer, p uintptr) { - // Null pointer. - num := uint64(p) - if num == 0 { - w.Write(nilAngleBytes) - return - } - - // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix - buf := make([]byte, 18) - - // It's simpler to construct the hex string right to left. - base := uint64(16) - i := len(buf) - 1 - for num >= base { - buf[i] = hexDigits[num%base] - num /= base - i-- - } - buf[i] = hexDigits[num] - - // Add '0x' prefix. - i-- - buf[i] = 'x' - i-- - buf[i] = '0' - - // Strip unused leading bytes. - buf = buf[i:] - w.Write(buf) -} - -// valuesSorter implements sort.Interface to allow a slice of reflect.Value -// elements to be sorted. -type valuesSorter struct { - values []reflect.Value - strings []string // either nil or same len and values - cs *ConfigState -} - -// newValuesSorter initializes a valuesSorter instance, which holds a set of -// surrogate keys on which the data should be sorted. It uses flags in -// ConfigState to decide if and how to populate those surrogate keys. -func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { - vs := &valuesSorter{values: values, cs: cs} - if canSortSimply(vs.values[0].Kind()) { - return vs - } - if !cs.DisableMethods { - vs.strings = make([]string, len(values)) - for i := range vs.values { - b := bytes.Buffer{} - if !handleMethods(cs, &b, vs.values[i]) { - vs.strings = nil - break - } - vs.strings[i] = b.String() - } - } - if vs.strings == nil && cs.SpewKeys { - vs.strings = make([]string, len(values)) - for i := range vs.values { - vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) - } - } - return vs -} - -// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted -// directly, or whether it should be considered for sorting by surrogate keys -// (if the ConfigState allows it). -func canSortSimply(kind reflect.Kind) bool { - // This switch parallels valueSortLess, except for the default case. - switch kind { - case reflect.Bool: - return true - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return true - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return true - case reflect.Float32, reflect.Float64: - return true - case reflect.String: - return true - case reflect.Uintptr: - return true - case reflect.Array: - return true - } - return false -} - -// Len returns the number of values in the slice. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Len() int { - return len(s.values) -} - -// Swap swaps the values at the passed indices. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Swap(i, j int) { - s.values[i], s.values[j] = s.values[j], s.values[i] - if s.strings != nil { - s.strings[i], s.strings[j] = s.strings[j], s.strings[i] - } -} - -// valueSortLess returns whether the first value should sort before the second -// value. It is used by valueSorter.Less as part of the sort.Interface -// implementation. -func valueSortLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Bool: - return !a.Bool() && b.Bool() - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return a.Int() < b.Int() - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return a.Uint() < b.Uint() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.String: - return a.String() < b.String() - case reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Array: - // Compare the contents of both arrays. - l := a.Len() - for i := 0; i < l; i++ { - av := a.Index(i) - bv := b.Index(i) - if av.Interface() == bv.Interface() { - continue - } - return valueSortLess(av, bv) - } - } - return a.String() < b.String() -} - -// Less returns whether the value at index i should sort before the -// value at index j. It is part of the sort.Interface implementation. -func (s *valuesSorter) Less(i, j int) bool { - if s.strings == nil { - return valueSortLess(s.values[i], s.values[j]) - } - return s.strings[i] < s.strings[j] -} - -// sortValues is a sort function that handles both native types and any type that -// can be converted to error or Stringer. Other inputs are sorted according to -// their Value.String() value to ensure display stability. -func sortValues(values []reflect.Value, cs *ConfigState) { - if len(values) == 0 { - return - } - sort.Sort(newValuesSorter(values, cs)) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/config.go deleted file mode 100644 index 2e3d22f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/config.go +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2013-2016 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. As a result, this option relies on - // access to the unsafe package, so it will not have any effect when - // running in environments without access to the unsafe package such as - // Google App Engine or with the "safe" build tag specified. - DisablePointerMethods bool - - // DisablePointerAddresses specifies whether to disable the printing of - // pointer addresses. This is useful when diffing data structures in tests. - DisablePointerAddresses bool - - // DisableCapacities specifies whether to disable the printing of capacities - // for arrays, slices, maps and channels. This is useful when diffing - // data structures in tests. - DisableCapacities bool - - // ContinueOnMethod specifies whether or not recursion should continue once - // a custom error or Stringer interface is invoked. The default, false, - // means it will print the results of invoking the custom error or Stringer - // interface and return immediately instead of continuing to recurse into - // the internals of the data type. - // - // NOTE: This flag does not have any effect if method invocation is disabled - // via the DisableMethods or DisablePointerMethods options. - ContinueOnMethod bool - - // SortKeys specifies map keys should be sorted before being printed. Use - // this to have a more deterministic, diffable output. Note that only - // native types (bool, int, uint, floats, uintptr and string) and types - // that support the error or Stringer interfaces (if methods are - // enabled) are supported, with other types sorted according to the - // reflect.Value.String() output which guarantees display stability. - SortKeys bool - - // SpewKeys specifies that, as a last resort attempt, map keys should - // be spewed to strings and sorted by those strings. This is only - // considered if SortKeys is true. - SpewKeys bool -} - -// Config is the active configuration of the top-level functions. -// The configuration can be changed by modifying the contents of spew.Config. -var Config = ConfigState{Indent: " "} - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the formatted string as a value that satisfies error. See NewFormatter -// for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, c.convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, c.convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, c.convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a Formatter interface returned by c.NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, c.convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Print(a ...interface{}) (n int, err error) { - return fmt.Print(c.convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, c.convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Println(a ...interface{}) (n int, err error) { - return fmt.Println(c.convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprint(a ...interface{}) string { - return fmt.Sprint(c.convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, c.convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a Formatter interface returned by c.NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintln(a ...interface{}) string { - return fmt.Sprintln(c.convertArgs(a)...) -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -c.Printf, c.Println, or c.Printf. -*/ -func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(c, v) -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { - fdump(c, w, a...) -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by modifying the public members -of c. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func (c *ConfigState) Dump(a ...interface{}) { - fdump(c, os.Stdout, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func (c *ConfigState) Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(c, &buf, a...) - return buf.String() -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a spew Formatter interface using -// the ConfigState associated with s. -func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = newFormatter(c, arg) - } - return formatters -} - -// NewDefaultConfig returns a ConfigState with the following default settings. -// -// Indent: " " -// MaxDepth: 0 -// DisableMethods: false -// DisablePointerMethods: false -// ContinueOnMethod: false -// SortKeys: false -func NewDefaultConfig() *ConfigState { - return &ConfigState{Indent: " "} -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/doc.go deleted file mode 100644 index aacaac6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/doc.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2013-2016 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. - - * DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - - * DisableCapacities - DisableCapacities specifies whether to disable the printing of - capacities for arrays, slices, maps and channels. This is useful when - diffing data structures in tests. - - * ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - - * SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are - supported with other types sorted according to the - reflect.Value.String() output which guarantees display - stability. Natural map order is used by default. - - * SpewKeys - Specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only - considered if SortKeys is true. - -Dump Usage - -Simply call spew.Dump with a list of variables you want to dump: - - spew.Dump(myVar1, myVar2, ...) - -You may also call spew.Fdump if you would prefer to output to an arbitrary -io.Writer. For example, to dump to standard error: - - spew.Fdump(os.Stderr, myVar1, myVar2, ...) - -A third option is to call spew.Sdump to get the formatted output as a string: - - str := spew.Sdump(myVar1, myVar2, ...) - -Sample Dump Output - -See the Dump example for details on the setup of the types and variables being -shown here. - - (main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - 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 diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/dump.go deleted file mode 100644 index f78d89f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/dump.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2013-2016 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 !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { - d.w.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - d.w.Write(pointerChainBytes) - } - printHexPtr(d.w, addr) - } - d.w.Write(closeParenBytes) - } - - // Display dereferenced value. - d.w.Write(openParenBytes) - switch { - case nilFound: - d.w.Write(nilAngleBytes) - - case cycleFound: - d.w.Write(circularBytes) - - default: - d.ignoreNextType = true - d.dump(ve) - } - d.w.Write(closeParenBytes) -} - -// dumpSlice handles formatting of arrays and slices. Byte (uint8 under -// reflection) arrays and slices are dumped in hexdump -C fashion. -func (d *dumpState) dumpSlice(v reflect.Value) { - // Determine whether this type should be hex dumped or not. Also, - // for types which should be hexdumped, try to use the underlying data - // first, then fall back to trying to convert them to a uint8 slice. - var buf []uint8 - doConvert := false - doHexDump := false - numEntries := v.Len() - if numEntries > 0 { - vt := v.Index(0).Type() - vts := vt.String() - switch { - // C types that need to be converted. - case cCharRE.MatchString(vts): - fallthrough - case cUnsignedCharRE.MatchString(vts): - fallthrough - case cUint8tCharRE.MatchString(vts): - doConvert = true - - // Try to use existing uint8 slices and fall back to converting - // and copying if that fails. - case vt.Kind() == reflect.Uint8: - // We need an addressable interface to convert the type - // to a byte slice. However, the reflect package won't - // give us an interface on certain things like - // unexported struct fields in order to enforce - // visibility rules. We use unsafe, when available, to - // bypass these restrictions since this package does not - // mutate the values. - vs := v - if !vs.CanInterface() || !vs.CanAddr() { - vs = unsafeReflectValue(vs) - } - if !UnsafeDisabled { - vs = vs.Slice(0, numEntries) - - // Use the existing uint8 slice if it can be - // type asserted. - iface := vs.Interface() - if slice, ok := iface.([]uint8); ok { - buf = slice - doHexDump = true - break - } - } - - // The underlying data needs to be converted if it can't - // be type asserted to a uint8 slice. - doConvert = true - } - - // Copy and convert the underlying type if needed. - if doConvert && vt.ConvertibleTo(uint8Type) { - // Convert and copy each element into a uint8 byte - // slice. - buf = make([]uint8, numEntries) - for i := 0; i < numEntries; i++ { - vv := v.Index(i) - buf[i] = uint8(vv.Convert(uint8Type).Uint()) - } - doHexDump = true - } - } - - // Hexdump the entire slice as needed. - if doHexDump { - indent := strings.Repeat(d.cs.Indent, d.depth) - str := indent + hex.Dump(buf) - str = strings.Replace(str, "\n", "\n"+indent, -1) - str = strings.TrimRight(str, d.cs.Indent) - d.w.Write([]byte(str)) - return - } - - // Recursively call dump for each item. - for i := 0; i < numEntries; i++ { - d.dump(d.unpackValue(v.Index(i))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } -} - -// dump is the main workhorse for dumping a value. It uses the passed reflect -// value to figure out what kind of object we are dealing with and formats it -// appropriately. It is a recursive function, however circular data structures -// are detected and handled properly. -func (d *dumpState) dump(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - d.w.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - d.indent() - d.dumpPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !d.ignoreNextType { - d.indent() - d.w.Write(openParenBytes) - d.w.Write([]byte(v.Type().String())) - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - d.ignoreNextType = false - - // Display length and capacity if the built-in len and cap functions - // work with the value's kind and the len/cap itself is non-zero. - valueLen, valueCap := 0, 0 - switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - valueLen, valueCap = v.Len(), v.Cap() - case reflect.Map, reflect.String: - valueLen = v.Len() - } - if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { - d.w.Write(openParenBytes) - if valueLen != 0 { - d.w.Write(lenEqualsBytes) - printInt(d.w, int64(valueLen), 10) - } - if !d.cs.DisableCapacities && valueCap != 0 { - if valueLen != 0 { - d.w.Write(spaceBytes) - } - d.w.Write(capEqualsBytes) - printInt(d.w, int64(valueCap), 10) - } - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - - // Call Stringer/error interfaces if they exist and the handle methods flag - // is enabled - if !d.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(d.cs, d.w, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(d.w, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(d.w, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(d.w, v.Uint(), 10) - - case reflect.Float32: - printFloat(d.w, v.Float(), 32) - - case reflect.Float64: - printFloat(d.w, v.Float(), 64) - - case reflect.Complex64: - printComplex(d.w, v.Complex(), 32) - - case reflect.Complex128: - printComplex(d.w, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - d.dumpSlice(v) - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.String: - d.w.Write([]byte(strconv.Quote(v.String()))) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - d.w.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - numEntries := v.Len() - keys := v.MapKeys() - if d.cs.SortKeys { - sortValues(keys, d.cs) - } - for i, key := range keys { - d.dump(d.unpackValue(key)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.MapIndex(key))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Struct: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - vt := v.Type() - numFields := v.NumField() - for i := 0; i < numFields; i++ { - d.indent() - vtf := vt.Field(i) - d.w.Write([]byte(vtf.Name)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.Field(i))) - if i < (numFields - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(d.w, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(d.w, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it in case any new - // types are added. - default: - if v.CanInterface() { - fmt.Fprintf(d.w, "%v", v.Interface()) - } else { - fmt.Fprintf(d.w, "%v", v.String()) - } - } -} - -// fdump is a helper function to consolidate the logic from the various public -// methods which take varying writers and config states. -func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { - for _, arg := range a { - if arg == nil { - w.Write(interfaceBytes) - w.Write(spaceBytes) - w.Write(nilAngleBytes) - w.Write(newlineBytes) - continue - } - - d := dumpState{w: w, cs: cs} - d.pointers = make(map[uintptr]int) - d.dump(reflect.ValueOf(arg)) - d.w.Write(newlineBytes) - } -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func Fdump(w io.Writer, a ...interface{}) { - fdump(&Config, w, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(&Config, &buf, a...) - return buf.String() -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by an exported package global, -spew.Config. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func Dump(a ...interface{}) { - fdump(&Config, os.Stdout, a...) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/format.go deleted file mode 100644 index b04edb7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/format.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (c) 2013-2016 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: - f.fs.Write(nilAngleBytes) - - case cycleFound: - f.fs.Write(circularShortBytes) - - default: - f.ignoreNextType = true - f.format(ve) - } -} - -// format is the main workhorse for providing the Formatter interface. It -// uses the passed reflect value to figure out what kind of object we are -// dealing with and formats it appropriately. It is a recursive function, -// however circular data structures are detected and handled properly. -func (f *formatState) format(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - f.fs.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - f.formatPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !f.ignoreNextType && f.fs.Flag('#') { - f.fs.Write(openParenBytes) - f.fs.Write([]byte(v.Type().String())) - f.fs.Write(closeParenBytes) - } - f.ignoreNextType = false - - // Call Stringer/error interfaces if they exist and the handle methods - // flag is enabled. - if !f.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(f.cs, f.fs, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(f.fs, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(f.fs, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(f.fs, v.Uint(), 10) - - case reflect.Float32: - printFloat(f.fs, v.Float(), 32) - - case reflect.Float64: - printFloat(f.fs, v.Float(), 64) - - case reflect.Complex64: - printComplex(f.fs, v.Complex(), 32) - - case reflect.Complex128: - printComplex(f.fs, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - f.fs.Write(openBracketBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - numEntries := v.Len() - for i := 0; i < numEntries; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(v.Index(i))) - } - } - f.depth-- - f.fs.Write(closeBracketBytes) - - case reflect.String: - f.fs.Write([]byte(v.String())) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - f.fs.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - - f.fs.Write(openMapBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - keys := v.MapKeys() - if f.cs.SortKeys { - sortValues(keys, f.cs) - } - for i, key := range keys { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(key)) - f.fs.Write(colonBytes) - f.ignoreNextType = true - f.format(f.unpackValue(v.MapIndex(key))) - } - } - f.depth-- - f.fs.Write(closeMapBytes) - - case reflect.Struct: - numFields := v.NumField() - f.fs.Write(openBraceBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - vt := v.Type() - for i := 0; i < numFields; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - vtf := vt.Field(i) - if f.fs.Flag('+') || f.fs.Flag('#') { - f.fs.Write([]byte(vtf.Name)) - f.fs.Write(colonBytes) - } - f.format(f.unpackValue(v.Field(i))) - } - } - f.depth-- - f.fs.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(f.fs, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(f.fs, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it if any get added. - default: - format := f.buildDefaultFormat() - if v.CanInterface() { - fmt.Fprintf(f.fs, format, v.Interface()) - } else { - fmt.Fprintf(f.fs, format, v.String()) - } - } -} - -// Format satisfies the fmt.Formatter interface. See NewFormatter for usage -// details. -func (f *formatState) Format(fs fmt.State, verb rune) { - f.fs = fs - - // Use standard formatting for verbs that are not v. - if verb != 'v' { - format := f.constructOrigFormat(verb) - fmt.Fprintf(fs, format, f.value) - return - } - - if f.value == nil { - if fs.Flag('#') { - fs.Write(interfaceBytes) - } - fs.Write(nilAngleBytes) - return - } - - f.format(reflect.ValueOf(f.value)) -} - -// newFormatter is a helper function to consolidate the logic from the various -// public methods which take varying config states. -func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { - fs := &formatState{value: v, cs: cs} - fs.pointers = make(map[uintptr]int) - return fs -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -Printf, Println, or Fprintf. -*/ -func NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(&Config, v) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/spew.go deleted file mode 100644 index 32c0e33..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/davecgh/go-spew/spew/spew.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2013-2016 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 ( - "fmt" - "io" -) - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the formatted string as a value that satisfies error. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a default Formatter interface returned by NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) -func Print(a ...interface{}) (n int, err error) { - return fmt.Print(convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) -func Println(a ...interface{}) (n int, err error) { - return fmt.Println(convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprint(a ...interface{}) string { - return fmt.Sprint(convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintln(a ...interface{}) string { - return fmt.Sprintln(convertArgs(a)...) -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a default spew Formatter interface. -func convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = NewFormatter(arg) - } - return formatters -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/LICENSE deleted file mode 100644 index c5c9a4e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 decker - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/dnspod.go b/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/dnspod.go deleted file mode 100644 index 43fe667..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/dnspod.go +++ /dev/null @@ -1,219 +0,0 @@ -// Package dnspod implements a client for the dnspod API. -// -// In order to use this package you will need a dnspod account and your API Token. -package dnspod - -import ( - // "bytes" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "time" - "unsafe" - - "github.com/json-iterator/go" -) - -var json = jsoniter.ConfigCompatibleWithStandardLibrary - -func init() { - jsoniter.RegisterFieldDecoderFunc("dnspod.Domain", "GroupID", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - *((*string)(ptr)) = iter.ReadAny().ToString() - }) -} - -const ( - libraryVersion = "0.1" - baseURL = "https://dnsapi.cn/" - userAgent = "dnspod-go/" + libraryVersion - - apiVersion = "v1" -) - -// dnspod API docs: https://www.dnspod.cn/docs/info.html - -type CommonParams struct { - LoginToken string - Format string - Lang string - ErrorOnEmpty string - UserID string -} - -func newPayLoad(params CommonParams) url.Values { - p := url.Values{} - - if params.LoginToken != "" { - p.Set("login_token", params.LoginToken) - } - if params.Format != "" { - p.Set("format", params.Format) - } - if params.Lang != "" { - p.Set("lang", params.Lang) - } - if params.ErrorOnEmpty != "" { - p.Set("error_on_empty", params.ErrorOnEmpty) - } - if params.UserID != "" { - p.Set("user_id", params.UserID) - - } - - return p -} - -type Status struct { - Code string `json:"code,omitempty"` - Message string `json:"message,omitempty"` - CreatedAt string `json:"created_at,omitempty"` -} - -type Client struct { - // HTTP client used to communicate with the API. - HttpClient *http.Client - - // CommonParams used communicating with the dnspod API. - CommonParams CommonParams - - // Base URL for API requests. - // Defaults to the public dnspod API, but can be set to a different endpoint (e.g. the sandbox). - // BaseURL should always be specified with a trailing slash. - BaseURL string - - // User agent used when communicating with the dnspod API. - UserAgent string - - // Services used for talking to different parts of the dnspod API. - Domains *DomainsService -} - -// NewClient returns a new dnspod API client. -func NewClient(CommonParams CommonParams) *Client { - c := &Client{HttpClient: &http.Client{}, CommonParams: CommonParams, BaseURL: baseURL, UserAgent: userAgent} - c.Domains = &DomainsService{client: c} - return c - -} - -// NewRequest creates an API request. -// The path is expected to be a relative path and will be resolved -// according to the BaseURL of the Client. Paths should always be specified without a preceding slash. -func (client *Client) NewRequest(method, path string, payload url.Values) (*http.Request, error) { - url := client.BaseURL + fmt.Sprintf("%s", path) - - req, err := http.NewRequest(method, url, strings.NewReader(payload.Encode())) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - req.Header.Add("Accept", "application/json") - req.Header.Add("User-Agent", client.UserAgent) - - return req, nil -} - -func (c *Client) get(path string, v interface{}) (*Response, error) { - return c.Do("GET", path, nil, v) -} - -func (c *Client) post(path string, payload url.Values, v interface{}) (*Response, error) { - return c.Do("POST", path, payload, v) -} - -func (c *Client) put(path string, payload url.Values, v interface{}) (*Response, error) { - return c.Do("PUT", path, payload, v) -} - -func (c *Client) delete(path string, payload url.Values) (*Response, error) { - return c.Do("DELETE", path, payload, nil) -} - -// Do sends an API request and returns the API response. -// The API response is JSON decoded and stored in the value pointed by v, -// or returned as an error if an API error has occurred. -// If v implements the io.Writer interface, the raw response body will be written to v, -// without attempting to decode it. -func (c *Client) Do(method, path string, payload url.Values, v interface{}) (*Response, error) { - req, err := c.NewRequest(method, path, payload) - if err != nil { - return nil, err - } - - res, err := c.HttpClient.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - response := &Response{Response: res} - err = CheckResponse(res) - if err != nil { - return response, err - } - if v != nil { - if w, ok := v.(io.Writer); ok { - io.Copy(w, res.Body) - } else { - err = json.NewDecoder(res.Body).Decode(v) - } - } - - return response, err -} - -// A Response represents an API response. -type Response struct { - *http.Response -} - -// An ErrorResponse represents an error caused by an API request. -type ErrorResponse struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // human-readable message -} - -// Error implements the error interface. -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %d %v", - r.Response.Request.Method, r.Response.Request.URL, - r.Response.StatusCode, r.Message) -} - -// CheckResponse checks the API response for errors, and returns them if present. -// A response is considered an error if the status code is different than 2xx. Specific requests -// may have additional requirements, but this is sufficient in most of the cases. -func CheckResponse(r *http.Response) error { - if code := r.StatusCode; 200 <= code && code <= 299 { - return nil - } - - errorResponse := &ErrorResponse{Response: r} - err := json.NewDecoder(r.Body).Decode(errorResponse) - if err != nil { - return err - } - - return errorResponse -} - -// Date custom type. -type Date struct { - time.Time -} - -// UnmarshalJSON handles the deserialization of the custom Date type. -func (d *Date) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("date should be a string, got %s", data) - } - t, err := time.Parse("2006-01-02", s) - if err != nil { - return fmt.Errorf("invalid date: %v", err) - } - d.Time = t - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/domain_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/domain_records.go deleted file mode 100644 index dea4ad9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/domain_records.go +++ /dev/null @@ -1,237 +0,0 @@ -package dnspod - -import ( - "fmt" -) - -type Record struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Line string `json:"line,omitempty"` - LineID string `json:"line_id,omitempty"` - Type string `json:"type,omitempty"` - TTL string `json:"ttl,omitempty"` - Value string `json:"value,omitempty"` - MX string `json:"mx,omitempty"` - Enabled string `json:"enabled,omitempty"` - Status string `json:"status,omitempty"` - MonitorStatus string `json:"monitor_status,omitempty"` - Remark string `json:"remark,omitempty"` - UpdateOn string `json:"updated_on,omitempty"` - UseAQB string `json:"use_aqb,omitempty"` -} - -type recordsWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Records []Record `json:"records"` -} - -type recordWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Record Record `json:"record"` -} - -// recordAction generates the resource path for given record that belongs to a domain. -func recordAction(action string) string { - if len(action) > 0 { - return fmt.Sprintf("Record.%s", action) - } - return "Record.List" -} - -// List the domain records. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-list -func (s *DomainsService) ListRecords(domainID string, recordName string) ([]Record, *Response, error) { - path := recordAction("List") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domainID) - - if recordName != "" { - payload.Add("sub_domain", recordName) - } - - wrappedRecords := recordsWrapper{} - - res, err := s.client.post(path, payload, &wrappedRecords) - if err != nil { - return []Record{}, res, err - } - - if wrappedRecords.Status.Code != "1" { - return wrappedRecords.Records, nil, fmt.Errorf("Could not get domains: %s", wrappedRecords.Status.Message) - } - - records := []Record{} - for _, record := range wrappedRecords.Records { - records = append(records, record) - } - - return records, res, nil -} - -// CreateRecord creates a domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-create -func (s *DomainsService) CreateRecord(domain string, recordAttributes Record) (Record, *Response, error) { - path := recordAction("Create") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - - if recordAttributes.Name != "" { - payload.Add("sub_domain", recordAttributes.Name) - } - - if recordAttributes.Type != "" { - payload.Add("record_type", recordAttributes.Type) - } - - if recordAttributes.Line != "" { - payload.Add("record_line", recordAttributes.Line) - } - - if recordAttributes.LineID != "" { - payload.Add("record_line_id", recordAttributes.LineID) - } - - if recordAttributes.Value != "" { - payload.Add("value", recordAttributes.Value) - } - - if recordAttributes.MX != "" { - payload.Add("mx", recordAttributes.MX) - } - - if recordAttributes.TTL != "" { - payload.Add("ttl", recordAttributes.TTL) - } - - if recordAttributes.Status != "" { - payload.Add("status", recordAttributes.Status) - } - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return Record{}, res, err - } - - if returnedRecord.Status.Code != "1" { - return returnedRecord.Record, nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return returnedRecord.Record, res, nil -} - -// GetRecord fetches the domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-info -func (s *DomainsService) GetRecord(domain string, recordID string) (Record, *Response, error) { - path := recordAction("Info") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - payload.Add("record_id", recordID) - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return Record{}, res, err - } - - if returnedRecord.Status.Code != "1" { - return returnedRecord.Record, nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return returnedRecord.Record, res, nil -} - -// UpdateRecord updates a domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-modify -func (s *DomainsService) UpdateRecord(domain string, recordID string, recordAttributes Record) (Record, *Response, error) { - path := recordAction("Modify") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - - if recordAttributes.Name != "" { - payload.Add("sub_domain", recordAttributes.Name) - } - - if recordAttributes.Type != "" { - payload.Add("record_type", recordAttributes.Type) - } - - if recordAttributes.Line != "" { - payload.Add("record_line", recordAttributes.Line) - } - - if recordAttributes.LineID != "" { - payload.Add("record_line_id", recordAttributes.LineID) - } - - if recordAttributes.Value != "" { - payload.Add("value", recordAttributes.Value) - } - - if recordAttributes.MX != "" { - payload.Add("mx", recordAttributes.MX) - } - - if recordAttributes.TTL != "" { - payload.Add("ttl", recordAttributes.TTL) - } - - if recordAttributes.Status != "" { - payload.Add("status", recordAttributes.Status) - } - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return Record{}, res, err - } - - if returnedRecord.Status.Code != "1" { - return returnedRecord.Record, nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return returnedRecord.Record, res, nil -} - -// DeleteRecord deletes a domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-remove -func (s *DomainsService) DeleteRecord(domain string, recordID string) (*Response, error) { - path := recordAction("Remove") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - payload.Add("record_id", recordID) - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return res, err - } - - if returnedRecord.Status.Code != "1" { - return nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return res, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/domains.go deleted file mode 100644 index 8cd5246..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/decker502/dnspod-go/domains.go +++ /dev/null @@ -1,161 +0,0 @@ -package dnspod - -import ( - "fmt" - "strconv" - // "time" -) - -// DomainsService handles communication with the domain related -// methods of the dnspod API. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html -type DomainsService struct { - client *Client -} - -type DomainInfo struct { - DomainTotal int `json:"domain_total,omitempty"` - AllTotal int `json:"all_total,omitempty"` - MineTotal int `json:"mine_total,omitempty"` - ShareTotal string `json:"share_total,omitempty"` - VipTotal int `json:"vip_total,omitempty"` - IsMarkTotal int `json:"ismark_total,omitempty"` - PauseTotal int `json:"pause_total,omitempty"` - ErrorTotal int `json:"error_total,omitempty"` - LockTotal int `json:"lock_total,omitempty"` - SpamTotal int `json:"spam_total,omitempty"` - VipExpire int `json:"vip_expire,omitempty"` - ShareOutTotal int `json:"share_out_total,omitempty"` -} - -type Domain struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` - PunyCode string `json:"punycode,omitempty"` - Grade string `json:"grade,omitempty"` - GradeTitle string `json:"grade_title,omitempty"` - Status string `json:"status,omitempty"` - ExtStatus string `json:"ext_status,omitempty"` - Records string `json:"records,omitempty"` - GroupID string `json:"group_id,omitempty"` - IsMark string `json:"is_mark,omitempty"` - Remark string `json:"remark,omitempty"` - IsVIP string `json:"is_vip,omitempty"` - SearchenginePush string `json:"searchengine_push,omitempty"` - UserID string `json:"user_id,omitempty"` - CreatedOn string `json:"created_on,omitempty"` - UpdatedOn string `json:"updated_on,omitempty"` - TTL string `json:"ttl,omitempty"` - CNameSpeedUp string `json:"cname_speedup,omitempty"` - Owner string `json:"owner,omitempty"` - AuthToAnquanBao bool `json:"auth_to_anquanbao,omitempty"` -} - -type domainListWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Domains []Domain `json:"domains"` -} - -type domainWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Domain Domain `json:"domain"` -} - -// domainRequest represents a generic wrapper for a domain request, -// when domainWrapper cannot be used because of type constraint on Domain. -type domainRequest struct { - Domain interface{} `json:"domain"` -} - -// domainAction generates the resource path for given domain. -func domainAction(action string) string { - if len(action) > 0 { - return fmt.Sprintf("Domain.%s", action) - } - return "Domain.List" -} - -// List the domains. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html#domain-list -func (s *DomainsService) List() ([]Domain, *Response, error) { - path := domainAction("List") - returnedDomains := domainListWrapper{} - - payload := newPayLoad(s.client.CommonParams) - res, err := s.client.post(path, payload, &returnedDomains) - if err != nil { - return []Domain{}, res, err - } - - domains := []Domain{} - - if returnedDomains.Status.Code != "1" { - return domains, nil, fmt.Errorf("Could not get domains: %s", returnedDomains.Status.Message) - } - - for _, domain := range returnedDomains.Domains { - domains = append(domains, domain) - } - - return domains, res, nil -} - -// Create a new domain. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html#domain-create -func (s *DomainsService) Create(domainAttributes Domain) (Domain, *Response, error) { - path := domainAction("Create") - returnedDomain := domainWrapper{} - - payload := newPayLoad(s.client.CommonParams) - payload.Set("domain", domainAttributes.Name) - payload.Set("group_id", domainAttributes.GroupID) - payload.Set("is_mark", domainAttributes.IsMark) - - res, err := s.client.post(path, payload, &returnedDomain) - if err != nil { - return Domain{}, res, err - } - - return returnedDomain.Domain, res, nil -} - -// Get fetches a domain. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html#domain-info -func (s *DomainsService) Get(ID int) (Domain, *Response, error) { - path := domainAction("Info") - returnedDomain := domainWrapper{} - - payload := newPayLoad(s.client.CommonParams) - payload.Set("domain_id", strconv.FormatInt(int64(ID), 10)) - - res, err := s.client.post(path, payload, &returnedDomain) - if err != nil { - return Domain{}, res, err - } - - return returnedDomain.Domain, res, nil -} - -// Delete a domain. -// -// dnspod API docs: https://dnsapi.cn/Domain.Remove -func (s *DomainsService) Delete(ID int) (*Response, error) { - path := domainAction("Remove") - returnedDomain := domainWrapper{} - - payload := newPayLoad(s.client.CommonParams) - payload.Set("domain_id", strconv.FormatInt(int64(ID), 10)) - - res, err := s.client.post(path, payload, &returnedDomain) - if err != nil { - return res, err - } - - return res, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/LICENSE deleted file mode 100644 index df83a9c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2012 Dave Grijalva - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/claims.go deleted file mode 100644 index f0228f0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/claims.go +++ /dev/null @@ -1,134 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// For a type to be a Claims object, it must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// Structured version of Claims Section, as referenced at -// https://tools.ietf.org/html/rfc7519#section-4.1 -// See examples for how to use this with your own claim types -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if c.VerifyExpiresAt(now, false) == false { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("token is expired by %v", delta) - vErr.Errors |= ValidationErrorExpired - } - - if c.VerifyIssuedAt(now, false) == false { - vErr.Inner = fmt.Errorf("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if c.VerifyNotBefore(now, false) == false { - vErr.Inner = fmt.Errorf("token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - return verifyExp(c.ExpiresAt, cmp, req) -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - return verifyIat(c.IssuedAt, cmp, req) -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - return verifyNbf(c.NotBefore, cmp, req) -} - -// ----- helpers - -func verifyAud(aud string, cmp string, required bool) bool { - if aud == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyExp(exp int64, now int64, required bool) bool { - if exp == 0 { - return !required - } - return now <= exp -} - -func verifyIat(iat int64, now int64, required bool) bool { - if iat == 0 { - return !required - } - return now >= iat -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyNbf(nbf int64, now int64, required bool) bool { - if nbf == 0 { - return !required - } - return now >= nbf -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/doc.go deleted file mode 100644 index a86dc1a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html -// -// See README.md for more info. -package jwt diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/ecdsa.go deleted file mode 100644 index f977381..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/ecdsa.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "errors" - "math/big" -) - -var ( - // Sadly this is missing from crypto/ecdsa compared to crypto/rsa - ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") -) - -// Implements the ECDSA family of signing methods signing methods -// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int - CurveBits int -} - -// Specific instances for EC256 and company -var ( - SigningMethodES256 *SigningMethodECDSA - SigningMethodES384 *SigningMethodECDSA - SigningMethodES512 *SigningMethodECDSA -) - -func init() { - // ES256 - SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} - RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { - return SigningMethodES256 - }) - - // ES384 - SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} - RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { - return SigningMethodES384 - }) - - // ES512 - SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} - RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { - return SigningMethodES512 - }) -} - -func (m *SigningMethodECDSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - // Get the key - var ecdsaKey *ecdsa.PublicKey - switch k := key.(type) { - case *ecdsa.PublicKey: - ecdsaKey = k - default: - return ErrInvalidKeyType - } - - if len(sig) != 2*m.KeySize { - return ErrECDSAVerification - } - - r := big.NewInt(0).SetBytes(sig[:m.KeySize]) - s := big.NewInt(0).SetBytes(sig[m.KeySize:]) - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { - return nil - } else { - return ErrECDSAVerification - } -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { - // Get the key - var ecdsaKey *ecdsa.PrivateKey - switch k := key.(type) { - case *ecdsa.PrivateKey: - ecdsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return r, s - if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { - curveBits := ecdsaKey.Curve.Params().BitSize - - if m.CurveBits != curveBits { - return "", ErrInvalidKey - } - - keyBytes := curveBits / 8 - if curveBits%8 > 0 { - keyBytes += 1 - } - - // We serialize the outpus (r and s) into big-endian byte arrays and pad - // them with zeros on the left to make sure the sizes work out. Both arrays - // must be keyBytes long, and the output must be 2*keyBytes long. - rBytes := r.Bytes() - rBytesPadded := make([]byte, keyBytes) - copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) - - sBytes := s.Bytes() - sBytesPadded := make([]byte, keyBytes) - copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) - - out := append(rBytesPadded, sBytesPadded...) - - return EncodeSegment(out), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go deleted file mode 100644 index d19624b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go +++ /dev/null @@ -1,67 +0,0 @@ -package jwt - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// Parse PEM encoded Elliptic Curve Private Key Structure -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { - return nil, err - } - - var pkey *ecdsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { - return nil, ErrNotECPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *ecdsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { - return nil, ErrNotECPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/errors.go deleted file mode 100644 index 1c93024..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// Helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// The error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Validation error is an error type -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/hmac.go deleted file mode 100644 index addbe5d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/hmac.go +++ /dev/null @@ -1,95 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/hmac" - "errors" -) - -// Implements the HMAC-SHA family of signing methods signing methods -// Expects key type of []byte for both signing and validation -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash -} - -// Specific instances for HS256 and company -var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC - ErrSignatureInvalid = errors.New("signature is invalid") -) - -func init() { - // HS256 - SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { - return SigningMethodHS256 - }) - - // HS384 - SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { - return SigningMethodHS384 - }) - - // HS512 - SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { - return SigningMethodHS512 - }) -} - -func (m *SigningMethodHMAC) Alg() string { - return m.Name -} - -// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { - // Verify the key is the right type - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKeyType - } - - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err - } - - // Can we use the specified hashing method? - if !m.Hash.Available() { - return ErrHashUnavailable - } - - // This signing method is symmetric, so we validate the signature - // by reproducing the signature from the signing string and key, then - // comparing that against the provided signature. - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - if !hmac.Equal(sig, hasher.Sum(nil)) { - return ErrSignatureInvalid - } - - // No validation errors. Signature is good. - return nil -} - -// Implements the Sign method from SigningMethod for this signing method. -// Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { - if keyBytes, ok := key.([]byte); ok { - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - return EncodeSegment(hasher.Sum(nil)), nil - } - - return "", ErrInvalidKeyType -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/map_claims.go deleted file mode 100644 index 291213c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/map_claims.go +++ /dev/null @@ -1,94 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - // "fmt" -) - -// Claims type that uses the map[string]interface{} for JSON decoding -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - aud, _ := m["aud"].(string) - return verifyAud(aud, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - switch exp := m["exp"].(type) { - case float64: - return verifyExp(int64(exp), cmp, req) - case json.Number: - v, _ := exp.Int64() - return verifyExp(v, cmp, req) - } - return req == false -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - switch iat := m["iat"].(type) { - case float64: - return verifyIat(int64(iat), cmp, req) - case json.Number: - v, _ := iat.Int64() - return verifyIat(v, cmp, req) - } - return req == false -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - switch nbf := m["nbf"].(type) { - case float64: - return verifyNbf(int64(nbf), cmp, req) - case json.Number: - v, _ := nbf.Int64() - return verifyNbf(v, cmp, req) - } - return req == false -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if m.VerifyExpiresAt(now, false) == false { - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if m.VerifyIssuedAt(now, false) == false { - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if m.VerifyNotBefore(now, false) == false { - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/none.go deleted file mode 100644 index f04d189..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/none.go +++ /dev/null @@ -1,52 +0,0 @@ -package jwt - -// Implements the none signing method. This is required by the spec -// but you probably should never use it. -var SigningMethodNone *signingMethodNone - -const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" - -var NoneSignatureTypeDisallowedError error - -type signingMethodNone struct{} -type unsafeNoneMagicConstant string - -func init() { - SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) - - RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { - return SigningMethodNone - }) -} - -func (m *signingMethodNone) Alg() string { - return "none" -} - -// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { - // Key must be UnsafeAllowNoneSignatureType to prevent accidentally - // accepting 'none' signing method - if _, ok := key.(unsafeNoneMagicConstant); !ok { - return NoneSignatureTypeDisallowedError - } - // If signing method is none, signature must be an empty string - if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) - } - - // Accept 'none' signing method. - return nil -} - -// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { - if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil - } - return "", NoneSignatureTypeDisallowedError -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/parser.go deleted file mode 100644 index d6901d9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/parser.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - ValidMethods []string // If populated, only these methods will be considered valid - UseJSONNumber bool // Use JSON Number format in JSON decoder - SkipClaimsValidation bool // Skip claims validation during token parsing -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.ValidMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.ValidMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) - } - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} - } - - vErr := &ValidationError{} - - // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } - } - } - - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// WARNING: Don't use this method unless you know what you're doing -// -// This method parses the token but doesn't validate the signature. It's only -// ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from -// it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error - if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) - } - - return token, parts, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa.go deleted file mode 100644 index e4caf1c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSA family of signing methods signing methods -// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation -type SigningMethodRSA struct { - Name string - Hash crypto.Hash -} - -// Specific instances for RS256 and company -var ( - SigningMethodRS256 *SigningMethodRSA - SigningMethodRS384 *SigningMethodRSA - SigningMethodRS512 *SigningMethodRSA -) - -func init() { - // RS256 - SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { - return SigningMethodRS256 - }) - - // RS384 - SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { - return SigningMethodRS384 - }) - - // RS512 - SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { - return SigningMethodRS512 - }) -} - -func (m *SigningMethodRSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - var ok bool - - if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) -} - -// Implements the Sign method from SigningMethod -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - var ok bool - - // Validate type of key - if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go deleted file mode 100644 index 10ee9db..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go +++ /dev/null @@ -1,126 +0,0 @@ -// +build go1.4 - -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSAPSS family of signing methods signing methods -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions -} - -// Specific instances for RS/PS and company -var ( - SigningMethodPS256 *SigningMethodRSAPSS - SigningMethodPS384 *SigningMethodRSAPSS - SigningMethodPS512 *SigningMethodRSAPSS -) - -func init() { - // PS256 - SigningMethodPS256 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA256, - }, - } - RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { - return SigningMethodPS256 - }) - - // PS384 - SigningMethodPS384 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA384, - }, - } - RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { - return SigningMethodPS384 - }) - - // PS512 - SigningMethodPS512 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA512, - }, - } - RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { - return SigningMethodPS512 - }) -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - switch k := key.(type) { - case *rsa.PublicKey: - rsaKey = k - default: - return ErrInvalidKey - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - - switch k := key.(type) { - case *rsa.PrivateKey: - rsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go deleted file mode 100644 index a5ababf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") - ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") -) - -// Parse PEM encoded PKCS1 or PKCS8 private key -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 private key protected with password -func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - - var blockDecrypted []byte - if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { - return nil, err - } - - if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/signing_method.go deleted file mode 100644 index ed1f212..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/signing_method.go +++ /dev/null @@ -1,35 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// Implement SigningMethod to add new methods for signing or verifying tokens. -type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// Register the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// Get a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/token.go deleted file mode 100644 index d637e08..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dgrijalva/jwt-go/token.go +++ /dev/null @@ -1,108 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Parse methods use this callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// A JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// Create a new Token. Takes a signing method -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// Get the complete, signed token -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// Generate the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - parts := make([]string, 2) - for i, _ := range parts { - var jsonValue []byte - if i == 0 { - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - } else { - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - } - - parts[i] = EncodeSegment(jsonValue) - } - return strings.Join(parts, "."), nil -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return new(Parser).Parse(tokenString, keyFunc) -} - -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) -} - -// Encode JWT specific base64url encoding with padding stripped -func EncodeSegment(seg []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") -} - -// Decode JWT specific base64url encoding with padding stripped -func DecodeSegment(seg string) ([]byte, error) { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - - return base64.URLEncoding.DecodeString(seg) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dimchansky/utfbom/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/dimchansky/utfbom/LICENSE deleted file mode 100644 index 8dada3e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dimchansky/utfbom/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dimchansky/utfbom/utfbom.go b/vendor/github.com/go-acme/lego/vendor/github.com/dimchansky/utfbom/utfbom.go deleted file mode 100644 index 648184a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dimchansky/utfbom/utfbom.go +++ /dev/null @@ -1,174 +0,0 @@ -// Package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. -// It wraps an io.Reader object, creating another object (Reader) that also implements the io.Reader -// interface but provides automatic BOM checking and removing as necessary. -package utfbom - -import ( - "errors" - "io" -) - -// Encoding is type alias for detected UTF encoding. -type Encoding int - -// Constants to identify detected UTF encodings. -const ( - // Unknown encoding, returned when no BOM was detected - Unknown Encoding = iota - - // UTF8, BOM bytes: EF BB BF - UTF8 - - // UTF-16, big-endian, BOM bytes: FE FF - UTF16BigEndian - - // UTF-16, little-endian, BOM bytes: FF FE - UTF16LittleEndian - - // UTF-32, big-endian, BOM bytes: 00 00 FE FF - UTF32BigEndian - - // UTF-32, little-endian, BOM bytes: FF FE 00 00 - UTF32LittleEndian -) - -const maxConsecutiveEmptyReads = 100 - -// Skip creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -// It also returns the encoding detected by the BOM. -// If the detected encoding is not needed, you can call the SkipOnly function. -func Skip(rd io.Reader) (*Reader, Encoding) { - // Is it already a Reader? - b, ok := rd.(*Reader) - if ok { - return b, Unknown - } - - enc, left, err := detectUtf(rd) - return &Reader{ - rd: rd, - buf: left, - err: err, - }, enc -} - -// SkipOnly creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -func SkipOnly(rd io.Reader) *Reader { - r, _ := Skip(rd) - return r -} - -// Reader implements automatic BOM (Unicode Byte Order Mark) checking and -// removing as necessary for an io.Reader object. -type Reader struct { - rd io.Reader // reader provided by the client - buf []byte // buffered data - err error // last error -} - -// Read is an implementation of io.Reader interface. -// The bytes are taken from the underlying Reader, but it checks for BOMs, removing them as necessary. -func (r *Reader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - - if r.buf == nil { - if r.err != nil { - return 0, r.readErr() - } - - return r.rd.Read(p) - } - - // copy as much as we can - n = copy(p, r.buf) - r.buf = nilIfEmpty(r.buf[n:]) - return n, nil -} - -func (r *Reader) readErr() error { - err := r.err - r.err = nil - return err -} - -var errNegativeRead = errors.New("utfbom: reader returned negative count from Read") - -func detectUtf(rd io.Reader) (enc Encoding, buf []byte, err error) { - buf, err = readBOM(rd) - - if len(buf) >= 4 { - if isUTF32BigEndianBOM4(buf) { - return UTF32BigEndian, nilIfEmpty(buf[4:]), err - } - if isUTF32LittleEndianBOM4(buf) { - return UTF32LittleEndian, nilIfEmpty(buf[4:]), err - } - } - - if len(buf) > 2 && isUTF8BOM3(buf) { - return UTF8, nilIfEmpty(buf[3:]), err - } - - if (err != nil && err != io.EOF) || (len(buf) < 2) { - return Unknown, nilIfEmpty(buf), err - } - - if isUTF16BigEndianBOM2(buf) { - return UTF16BigEndian, nilIfEmpty(buf[2:]), err - } - if isUTF16LittleEndianBOM2(buf) { - return UTF16LittleEndian, nilIfEmpty(buf[2:]), err - } - - return Unknown, nilIfEmpty(buf), err -} - -func readBOM(rd io.Reader) (buf []byte, err error) { - const maxBOMSize = 4 - var bom [maxBOMSize]byte // used to read BOM - - // read as many bytes as possible - for nEmpty, n := 0, 0; err == nil && len(buf) < maxBOMSize; buf = bom[:len(buf)+n] { - if n, err = rd.Read(bom[len(buf):]); n < 0 { - panic(errNegativeRead) - } - if n > 0 { - nEmpty = 0 - } else { - nEmpty++ - if nEmpty >= maxConsecutiveEmptyReads { - err = io.ErrNoProgress - } - } - } - return -} - -func isUTF32BigEndianBOM4(buf []byte) bool { - return buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0xFE && buf[3] == 0xFF -} - -func isUTF32LittleEndianBOM4(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE && buf[2] == 0x00 && buf[3] == 0x00 -} - -func isUTF8BOM3(buf []byte) bool { - return buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF -} - -func isUTF16BigEndianBOM2(buf []byte) bool { - return buf[0] == 0xFE && buf[1] == 0xFF -} - -func isUTF16LittleEndianBOM2(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE -} - -func nilIfEmpty(buf []byte) (res []byte) { - if len(buf) > 0 { - res = buf - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt deleted file mode 100644 index 3c2f300..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2018 Aetrion LLC dba DNSimple - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/accounts.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/accounts.go deleted file mode 100644 index 2f86ed3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/accounts.go +++ /dev/null @@ -1,41 +0,0 @@ -package dnsimple - -type AccountsService struct { - client *Client -} - -// Account represents a DNSimple account. -type Account struct { - ID int64 `json:"id,omitempty"` - Email string `json:"email,omitempty"` - PlanIdentifier string `json:"plan_identifier,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// accountsResponse represents a response from an API method that returns a collection of Account struct. -type accountsResponse struct { - Response - Data []Account `json:"data"` -} - -// ListAccounts list the accounts for an user. -// -// See https://developer.dnsimple.com/v2/accounts/#list -func (s *AccountsService) ListAccounts(options *ListOptions) (*accountsResponse, error) { - path := versioned("/accounts") - accountsResponse := &accountsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, accountsResponse) - if err != nil { - return accountsResponse, err - } - - accountsResponse.HttpResponse = resp - return accountsResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/authentication.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/authentication.go deleted file mode 100644 index dac6f51..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/authentication.go +++ /dev/null @@ -1,52 +0,0 @@ -package dnsimple - -import ( - "net/http" -) - -// BasicAuthTransport is an http.RoundTripper that authenticates all requests -// using HTTP Basic Authentication with the provided username and password. -type BasicAuthTransport struct { - Username string - Password string - - // Transport is the transport RoundTripper used to make HTTP requests. - // If nil, http.DefaultTransport is used. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. We just add the -// basic auth and return the RoundTripper for this transport type. -func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { - req2 := cloneRequest(req) // per RoundTripper contract - - req2.SetBasicAuth(t.Username, t.Password) - return t.transport().RoundTrip(req2) -} - -// Client returns an *http.Client that uses the BasicAuthTransport transport -// to authenticate the request via HTTP Basic Auth. -func (t *BasicAuthTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *BasicAuthTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// 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 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/certificates.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/certificates.go deleted file mode 100644 index 84ddba0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/certificates.go +++ /dev/null @@ -1,249 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// CertificatesService handles communication with the certificate related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/certificates -type CertificatesService struct { - client *Client -} - -// Certificate represents a Certificate in DNSimple. -type Certificate struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - ContactID int64 `json:"contact_id,omitempty"` - CommonName string `json:"common_name,omitempty"` - AlternateNames []string `json:"alternate_names,omitempty"` - Years int `json:"years,omitempty"` - State string `json:"state,omitempty"` - AuthorityIdentifier string `json:"authority_identifier,omitempty"` - AutoRenew bool `json:"auto_renew"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - ExpiresOn string `json:"expires_on,omitempty"` - CertificateRequest string `json:"csr,omitempty"` -} - -// CertificateBundle represents a container for all the PEM-encoded X509 certificate entities, -// such as the private key, the server certificate and the intermediate chain. -type CertificateBundle struct { - // CertificateRequest string `json:"csr,omitempty"` - PrivateKey string `json:"private_key,omitempty"` - ServerCertificate string `json:"server,omitempty"` - RootCertificate string `json:"root,omitempty"` - IntermediateCertificates []string `json:"chain,omitempty"` -} - -// CertificatePurchase represents a Certificate Purchase in DNSimple. -type CertificatePurchase struct { - ID int64 `json:"id,omitempty"` - CertificateID int64 `json:"new_certificate_id,omitempty"` - State string `json:"state,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// CertificateRenewal represents a Certificate Renewal in DNSimple. -type CertificateRenewal struct { - ID int64 `json:"id,omitempty"` - OldCertificateID int64 `json:"old_certificate_id,omitempty"` - NewCertificateID int64 `json:"new_certificate_id,omitempty"` - State string `json:"state,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// LetsencryptCertificateAttributes is a set of attributes to purchase a Let's Encrypt certificate. -type LetsencryptCertificateAttributes struct { - ContactID int64 `json:"contact_id,omitempty"` - Name string `json:"name,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - AlternateNames []string `json:"alternate_names,omitempty"` -} - -func certificatePath(accountID, domainIdentifier string, certificateID int64) (path string) { - path = fmt.Sprintf("%v/certificates", domainPath(accountID, domainIdentifier)) - if certificateID != 0 { - path += fmt.Sprintf("/%v", certificateID) - } - return -} - -func letsencryptCertificatePath(accountID, domainIdentifier string, certificateID int64) (path string) { - path = fmt.Sprintf("%v/certificates/letsencrypt", domainPath(accountID, domainIdentifier)) - if certificateID != 0 { - path += fmt.Sprintf("/%v", certificateID) - } - return -} - -// certificateResponse represents a response from an API method that returns a Certificate struct. -type certificateResponse struct { - Response - Data *Certificate `json:"data"` -} - -// certificateBundleResponse represents a response from an API method that returns a CertificatBundle struct. -type certificateBundleResponse struct { - Response - Data *CertificateBundle `json:"data"` -} - -// certificatesResponse represents a response from an API method that returns a collection of Certificate struct. -type certificatesResponse struct { - Response - Data []Certificate `json:"data"` -} - -// certificatePurchaseResponse represents a response from an API method that returns a CertificatePurchase struct. -type certificatePurchaseResponse struct { - Response - Data *CertificatePurchase `json:"data"` -} - -// certificateRenewalResponse represents a response from an API method that returns a CertificateRenewal struct. -type certificateRenewalResponse struct { - Response - Data *CertificateRenewal `json:"data"` -} - -// ListCertificates lists the certificates for a domain in the account. -// -// See https://developer.dnsimple.com/v2/certificates#listCertificates -func (s *CertificatesService) ListCertificates(accountID, domainIdentifier string, options *ListOptions) (*certificatesResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, 0)) - certificatesResponse := &certificatesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, certificatesResponse) - if err != nil { - return certificatesResponse, err - } - - certificatesResponse.HttpResponse = resp - return certificatesResponse, nil -} - -// GetCertificate gets the details of a certificate. -// -// See https://developer.dnsimple.com/v2/certificates#getCertificate -func (s *CertificatesService) GetCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, certificateID)) - certificateResponse := &certificateResponse{} - - resp, err := s.client.get(path, certificateResponse) - if err != nil { - return nil, err - } - - certificateResponse.HttpResponse = resp - return certificateResponse, nil -} - -// DownloadCertificate gets the PEM-encoded certificate, -// along with the root certificate and intermediate chain. -// -// See https://developer.dnsimple.com/v2/certificates#downloadCertificate -func (s *CertificatesService) DownloadCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateBundleResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, certificateID) + "/download") - certificateBundleResponse := &certificateBundleResponse{} - - resp, err := s.client.get(path, certificateBundleResponse) - if err != nil { - return nil, err - } - - certificateBundleResponse.HttpResponse = resp - return certificateBundleResponse, nil -} - -// GetCertificatePrivateKey gets the PEM-encoded certificate private key. -// -// See https://developer.dnsimple.com/v2/certificates#getCertificatePrivateKey -func (s *CertificatesService) GetCertificatePrivateKey(accountID, domainIdentifier string, certificateID int64) (*certificateBundleResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, certificateID) + "/private_key") - certificateBundleResponse := &certificateBundleResponse{} - - resp, err := s.client.get(path, certificateBundleResponse) - if err != nil { - return nil, err - } - - certificateBundleResponse.HttpResponse = resp - return certificateBundleResponse, nil -} - -// PurchaseLetsencryptCertificate purchases a Let's Encrypt certificate. -// -// See https://developer.dnsimple.com/v2/certificates/#purchaseLetsencryptCertificate -func (s *CertificatesService) PurchaseLetsencryptCertificate(accountID, domainIdentifier string, certificateAttributes LetsencryptCertificateAttributes) (*certificatePurchaseResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, 0)) - certificatePurchaseResponse := &certificatePurchaseResponse{} - - resp, err := s.client.post(path, certificateAttributes, certificatePurchaseResponse) - if err != nil { - return nil, err - } - - certificatePurchaseResponse.HttpResponse = resp - return certificatePurchaseResponse, nil -} - -// IssueLetsencryptCertificate issues a pending Let's Encrypt certificate purchase order. -// -// See https://developer.dnsimple.com/v2/certificates/#issueLetsencryptCertificate -func (s *CertificatesService) IssueLetsencryptCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, certificateID) + "/issue") - certificateResponse := &certificateResponse{} - - resp, err := s.client.post(path, nil, certificateResponse) - if err != nil { - return nil, err - } - - certificateResponse.HttpResponse = resp - return certificateResponse, nil -} - -// PurchaseLetsencryptCertificateRenewal purchases a Let's Encrypt certificate renewal. -// -// See https://developer.dnsimple.com/v2/certificates/#purchaseRenewalLetsencryptCertificate -func (s *CertificatesService) PurchaseLetsencryptCertificateRenewal(accountID, domainIdentifier string, certificateID int64, certificateAttributes LetsencryptCertificateAttributes) (*certificateRenewalResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, certificateID) + "/renewals") - certificateRenewalResponse := &certificateRenewalResponse{} - - resp, err := s.client.post(path, certificateAttributes, certificateRenewalResponse) - if err != nil { - return nil, err - } - - certificateRenewalResponse.HttpResponse = resp - return certificateRenewalResponse, nil -} - -// IssueLetsencryptCertificateRenewal issues a pending Let's Encrypt certificate renewal order. -// -// See https://developer.dnsimple.com/v2/certificates/#issueRenewalLetsencryptCertificate -func (s *CertificatesService) IssueLetsencryptCertificateRenewal(accountID, domainIdentifier string, certificateID, certificateRenewalID int64) (*certificateResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, certificateID) + fmt.Sprintf("/renewals/%d/issue", certificateRenewalID)) - certificateResponse := &certificateResponse{} - - resp, err := s.client.post(path, nil, certificateResponse) - if err != nil { - return nil, err - } - - certificateResponse.HttpResponse = resp - return certificateResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/contacts.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/contacts.go deleted file mode 100644 index d35cffe..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/contacts.go +++ /dev/null @@ -1,140 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ContactsService handles communication with the contact related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/contacts/ -type ContactsService struct { - client *Client -} - -// Contact represents a Contact in DNSimple. -type Contact struct { - ID int64 `json:"id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - Label string `json:"label,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - JobTitle string `json:"job_title,omitempty"` - Organization string `json:"organization_name,omitempty"` - Address1 string `json:"address1,omitempty"` - Address2 string `json:"address2,omitempty"` - City string `json:"city,omitempty"` - StateProvince string `json:"state_province,omitempty"` - PostalCode string `json:"postal_code,omitempty"` - Country string `json:"country,omitempty"` - Phone string `json:"phone,omitempty"` - Fax string `json:"fax,omitempty"` - Email string `json:"email,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func contactPath(accountID string, contactID int64) (path string) { - path = fmt.Sprintf("/%v/contacts", accountID) - if contactID != 0 { - path += fmt.Sprintf("/%v", contactID) - } - return -} - -// contactResponse represents a response from an API method that returns a Contact struct. -type contactResponse struct { - Response - Data *Contact `json:"data"` -} - -// contactsResponse represents a response from an API method that returns a collection of Contact struct. -type contactsResponse struct { - Response - Data []Contact `json:"data"` -} - -// ListContacts list the contacts for an account. -// -// See https://developer.dnsimple.com/v2/contacts/#list -func (s *ContactsService) ListContacts(accountID string, options *ListOptions) (*contactsResponse, error) { - path := versioned(contactPath(accountID, 0)) - contactsResponse := &contactsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, contactsResponse) - if err != nil { - return contactsResponse, err - } - - contactsResponse.HttpResponse = resp - return contactsResponse, nil -} - -// CreateContact creates a new contact. -// -// See https://developer.dnsimple.com/v2/contacts/#create -func (s *ContactsService) CreateContact(accountID string, contactAttributes Contact) (*contactResponse, error) { - path := versioned(contactPath(accountID, 0)) - contactResponse := &contactResponse{} - - resp, err := s.client.post(path, contactAttributes, contactResponse) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} - -// GetContact fetches a contact. -// -// See https://developer.dnsimple.com/v2/contacts/#get -func (s *ContactsService) GetContact(accountID string, contactID int64) (*contactResponse, error) { - path := versioned(contactPath(accountID, contactID)) - contactResponse := &contactResponse{} - - resp, err := s.client.get(path, contactResponse) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} - -// UpdateContact updates a contact. -// -// See https://developer.dnsimple.com/v2/contacts/#update -func (s *ContactsService) UpdateContact(accountID string, contactID int64, contactAttributes Contact) (*contactResponse, error) { - path := versioned(contactPath(accountID, contactID)) - contactResponse := &contactResponse{} - - resp, err := s.client.patch(path, contactAttributes, contactResponse) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} - -// DeleteContact PERMANENTLY deletes a contact from the account. -// -// See https://developer.dnsimple.com/v2/contacts/#delete -func (s *ContactsService) DeleteContact(accountID string, contactID int64) (*contactResponse, error) { - path := versioned(contactPath(accountID, contactID)) - contactResponse := &contactResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/dnsimple.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/dnsimple.go deleted file mode 100644 index 6c32e16..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/dnsimple.go +++ /dev/null @@ -1,338 +0,0 @@ -// Package dnsimple provides a client for the DNSimple API. -// In order to use this package you will need a DNSimple account. -package dnsimple - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "log" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "time" - - "github.com/google/go-querystring/query" -) - -const ( - // Version identifies the current library version. - // This is a pro-forma convention given that Go dependencies - // tends to be fetched directly from the repo. - // It is also used in the user-agent identify the client. - Version = "0.21.0" - - // defaultBaseURL to the DNSimple production API. - defaultBaseURL = "https://api.dnsimple.com" - - // userAgent represents the default user agent used - // when no other user agent is set. - defaultUserAgent = "dnsimple-go/" + Version - - apiVersion = "v2" -) - -// Client represents a client to the DNSimple API. -type Client struct { - // httpClient is the underlying HTTP client - // used to communicate with the API. - httpClient *http.Client - - // BaseURL for API requests. - // Defaults to the public DNSimple API, but can be set to a different endpoint (e.g. the sandbox). - BaseURL string - - // UserAgent used when communicating with the DNSimple API. - UserAgent string - - // Services used for talking to different parts of the DNSimple API. - Identity *IdentityService - Accounts *AccountsService - Certificates *CertificatesService - Contacts *ContactsService - Domains *DomainsService - Oauth *OauthService - Registrar *RegistrarService - Services *ServicesService - Templates *TemplatesService - Tlds *TldsService - VanityNameServers *VanityNameServersService - Webhooks *WebhooksService - Zones *ZonesService - - // Set to true to output debugging logs during API calls - Debug bool -} - -// ListOptions contains the common options you can pass to a List method -// in order to control parameters such as paginations and page number. -type ListOptions struct { - // The page to return - Page int `url:"page,omitempty"` - - // The number of entries to return per page - PerPage int `url:"per_page,omitempty"` - - // The order criteria to sort the results. - // The value is a comma-separated list of field[:direction], - // eg. name | name:desc | name:desc,expiration:desc - Sort string `url:"sort,omitempty"` -} - -// NewClient returns a new DNSimple API client. -// -// To authenticate you must provide an http.Client that will perform authentication -// for you with one of the currently supported mechanisms: OAuth or HTTP Basic. -func NewClient(httpClient *http.Client) *Client { - c := &Client{httpClient: httpClient, BaseURL: defaultBaseURL} - c.Identity = &IdentityService{client: c} - c.Accounts = &AccountsService{client: c} - c.Certificates = &CertificatesService{client: c} - c.Contacts = &ContactsService{client: c} - c.Domains = &DomainsService{client: c} - c.Oauth = &OauthService{client: c} - c.Registrar = &RegistrarService{client: c} - c.Services = &ServicesService{client: c} - c.Templates = &TemplatesService{client: c} - c.Tlds = &TldsService{client: c} - c.VanityNameServers = &VanityNameServersService{client: c} - c.Webhooks = &WebhooksService{client: c} - c.Zones = &ZonesService{client: c} - return c -} - -// NewRequest creates an API request. -// The path is expected to be a relative path and will be resolved -// according to the BaseURL of the Client. Paths should always be specified without a preceding slash. -func (c *Client) NewRequest(method, path string, payload interface{}) (*http.Request, error) { - url := c.BaseURL + path - - body := new(bytes.Buffer) - if payload != nil { - err := json.NewEncoder(body).Encode(payload) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - req.Header.Add("User-Agent", formatUserAgent(c.UserAgent)) - - return req, nil -} - -// formatUserAgent builds the final user agent to use for HTTP requests. -// -// If no custom user agent is provided, the default user agent is used. -// -// dnsimple-go/1.0 -// -// If a custom user agent is provided, the final user agent is the combination of the custom user agent -// prepended by the default user agent. -// -// dnsimple-go/1.0 customAgentFlag -// -func formatUserAgent(customUserAgent string) string { - if customUserAgent == "" { - return defaultUserAgent - } - - return fmt.Sprintf("%s %s", defaultUserAgent, customUserAgent) -} - -func versioned(path string) string { - return fmt.Sprintf("/%s/%s", apiVersion, strings.Trim(path, "/")) -} - -func (c *Client) get(path string, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("GET", path, nil) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) post(path string, payload, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("POST", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) put(path string, payload, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("PUT", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) patch(path string, payload, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("PATCH", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) delete(path string, payload interface{}, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("DELETE", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -// Do sends an API request and returns the API response. -// -// The API response is JSON decoded and stored in the value pointed by obj, -// or returned as an error if an API error has occurred. -// If obj implements the io.Writer interface, the raw response body will be written to obj, -// without attempting to decode it. -func (c *Client) Do(req *http.Request, obj interface{}) (*http.Response, error) { - if c.Debug { - log.Printf("Executing request (%v): %#v", req.URL, req) - } - - resp, err := c.httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if c.Debug { - log.Printf("Response received: %#v", resp) - } - - err = CheckResponse(resp) - if err != nil { - return resp, err - } - - // If obj implements the io.Writer, - // the response body is decoded into v. - if obj != nil { - if w, ok := obj.(io.Writer); ok { - _, err = io.Copy(w, resp.Body) - } else { - err = json.NewDecoder(resp.Body).Decode(obj) - } - } - - return resp, err -} - -// A Response represents an API response. -type Response struct { - // HTTP response - HttpResponse *http.Response - - // If the response is paginated, the Pagination will store them. - Pagination *Pagination `json:"pagination"` -} - -// RateLimit returns the maximum amount of requests this account can send in an hour. -func (r *Response) RateLimit() int { - value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Limit")) - return value -} - -// RateLimitRemaining returns the remaining amount of requests this account can send within this hour window. -func (r *Response) RateLimitRemaining() int { - value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Remaining")) - return value -} - -// RateLimitReset returns when the throttling window will be reset for this account. -func (r *Response) RateLimitReset() time.Time { - value, _ := strconv.ParseInt(r.HttpResponse.Header.Get("X-RateLimit-Reset"), 10, 64) - return time.Unix(value, 0) -} - -// If the response is paginated, Pagination represents the pagination information. -type Pagination struct { - CurrentPage int `json:"current_page"` - PerPage int `json:"per_page"` - TotalPages int `json:"total_pages"` - TotalEntries int `json:"total_entries"` -} - -// An ErrorResponse represents an API response that generated an error. -type ErrorResponse struct { - Response - - // human-readable message - Message string `json:"message"` -} - -// Error implements the error interface. -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %v %v", - r.HttpResponse.Request.Method, r.HttpResponse.Request.URL, - r.HttpResponse.StatusCode, r.Message) -} - -// CheckResponse checks the API response for errors, and returns them if present. -// A response is considered an error if the status code is different than 2xx. Specific requests -// may have additional requirements, but this is sufficient in most of the cases. -func CheckResponse(resp *http.Response) error { - if code := resp.StatusCode; 200 <= code && code <= 299 { - return nil - } - - errorResponse := &ErrorResponse{} - errorResponse.HttpResponse = resp - - err := json.NewDecoder(resp.Body).Decode(errorResponse) - if err != nil { - return err - } - - return errorResponse -} - -// addOptions adds the parameters in opt as URL query parameters to s. opt -// must be a struct whose fields may contain "url" tags. -func addURLQueryOptions(path string, options interface{}) (string, error) { - opt := reflect.ValueOf(options) - - // options is a pointer - // return if the value of the pointer is nil, - if opt.Kind() == reflect.Ptr && opt.IsNil() { - return path, nil - } - - // append the options to the URL - u, err := url.Parse(path) - if err != nil { - return path, err - } - - qs, err := query.Values(options) - if err != nil { - return path, err - } - - uqs := u.Query() - for k, _ := range qs { - uqs.Set(k, qs.Get(k)) - } - u.RawQuery = uqs.Encode() - - return u.String(), nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains.go deleted file mode 100644 index 6cd8fd7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains.go +++ /dev/null @@ -1,146 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// DomainsService handles communication with the domain related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/domains/ -type DomainsService struct { - client *Client -} - -// Domain represents a domain in DNSimple. -type Domain struct { - ID int64 `json:"id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - RegistrantID int64 `json:"registrant_id,omitempty"` - Name string `json:"name,omitempty"` - UnicodeName string `json:"unicode_name,omitempty"` - Token string `json:"token,omitempty"` - State string `json:"state,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - PrivateWhois bool `json:"private_whois,omitempty"` - ExpiresOn string `json:"expires_on,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func domainPath(accountID string, domainIdentifier string) (path string) { - path = fmt.Sprintf("/%v/domains", accountID) - if domainIdentifier != "" { - path += fmt.Sprintf("/%v", domainIdentifier) - } - return -} - -// domainResponse represents a response from an API method that returns a Domain struct. -type domainResponse struct { - Response - Data *Domain `json:"data"` -} - -// domainsResponse represents a response from an API method that returns a collection of Domain struct. -type domainsResponse struct { - Response - Data []Domain `json:"data"` -} - -// DomainListOptions specifies the optional parameters you can provide -// to customize the DomainsService.ListDomains method. -type DomainListOptions struct { - // Select domains where the name contains given string. - NameLike string `url:"name_like,omitempty"` - - // Select domains where the registrant matches given ID. - RegistrantID int `url:"registrant_id,omitempty"` - - ListOptions -} - -// ListDomains lists the domains for an account. -// -// See https://developer.dnsimple.com/v2/domains/#list -func (s *DomainsService) ListDomains(accountID string, options *DomainListOptions) (*domainsResponse, error) { - path := versioned(domainPath(accountID, "")) - domainsResponse := &domainsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, domainsResponse) - if err != nil { - return nil, err - } - - domainsResponse.HttpResponse = resp - return domainsResponse, nil -} - -// CreateDomain creates a new domain in the account. -// -// See https://developer.dnsimple.com/v2/domains/#create -func (s *DomainsService) CreateDomain(accountID string, domainAttributes Domain) (*domainResponse, error) { - path := versioned(domainPath(accountID, "")) - domainResponse := &domainResponse{} - - resp, err := s.client.post(path, domainAttributes, domainResponse) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// GetDomain fetches a domain. -// -// See https://developer.dnsimple.com/v2/domains/#get -func (s *DomainsService) GetDomain(accountID string, domainIdentifier string) (*domainResponse, error) { - path := versioned(domainPath(accountID, domainIdentifier)) - domainResponse := &domainResponse{} - - resp, err := s.client.get(path, domainResponse) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// DeleteDomain PERMANENTLY deletes a domain from the account. -// -// See https://developer.dnsimple.com/v2/domains/#delete -func (s *DomainsService) DeleteDomain(accountID string, domainIdentifier string) (*domainResponse, error) { - path := versioned(domainPath(accountID, domainIdentifier)) - domainResponse := &domainResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// ResetDomainToken resets the domain token. -// -// See https://developer.dnsimple.com/v2/domains/#reset-token -func (s *DomainsService) ResetDomainToken(accountID string, domainIdentifier string) (*domainResponse, error) { - path := versioned(domainPath(accountID, domainIdentifier) + "/token") - domainResponse := &domainResponse{} - - resp, err := s.client.post(path, nil, domainResponse) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go deleted file mode 100644 index da05139..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go +++ /dev/null @@ -1,96 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// Collaborator represents a Collaborator in DNSimple. -type Collaborator struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - DomainName string `json:"domain_name,omitempty"` - UserID int64 `json:"user_id,omitempty"` - UserEmail string `json:"user_email,omitempty"` - Invitation bool `json:"invitation,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - AcceptedAt string `json:"accepted_at,omitempty"` -} - -func collaboratorPath(accountID, domainIdentifier string, collaboratorID int64) (path string) { - path = fmt.Sprintf("%v/collaborators", domainPath(accountID, domainIdentifier)) - if collaboratorID != 0 { - path += fmt.Sprintf("/%v", collaboratorID) - } - return -} - -// CollaboratorAttributes represents Collaborator attributes for AddCollaborator operation. -type CollaboratorAttributes struct { - Email string `json:"email,omitempty"` -} - -// collaboratorResponse represents a response from an API method that returns a Collaborator struct. -type collaboratorResponse struct { - Response - Data *Collaborator `json:"data"` -} - -// collaboratorsResponse represents a response from an API method that returns a collection of Collaborator struct. -type collaboratorsResponse struct { - Response - Data []Collaborator `json:"data"` -} - -// ListCollaborators list the collaborators for a domain. -// -// See https://developer.dnsimple.com/v2/domains/collaborators#list -func (s *DomainsService) ListCollaborators(accountID, domainIdentifier string, options *ListOptions) (*collaboratorsResponse, error) { - path := versioned(collaboratorPath(accountID, domainIdentifier, 0)) - collaboratorsResponse := &collaboratorsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, collaboratorsResponse) - if err != nil { - return collaboratorsResponse, err - } - - collaboratorsResponse.HttpResponse = resp - return collaboratorsResponse, nil -} - -// AddCollaborator adds a new collaborator to the domain in the account. -// -// See https://developer.dnsimple.com/v2/domains/collaborators#add -func (s *DomainsService) AddCollaborator(accountID string, domainIdentifier string, attributes CollaboratorAttributes) (*collaboratorResponse, error) { - path := versioned(collaboratorPath(accountID, domainIdentifier, 0)) - collaboratorResponse := &collaboratorResponse{} - - resp, err := s.client.post(path, attributes, collaboratorResponse) - if err != nil { - return nil, err - } - - collaboratorResponse.HttpResponse = resp - return collaboratorResponse, nil -} - -// RemoveCollaborator PERMANENTLY deletes a domain from the account. -// -// See https://developer.dnsimple.com/v2/domains/collaborators#remove -func (s *DomainsService) RemoveCollaborator(accountID string, domainIdentifier string, collaboratorID int64) (*collaboratorResponse, error) { - path := versioned(collaboratorPath(accountID, domainIdentifier, collaboratorID)) - collaboratorResponse := &collaboratorResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - collaboratorResponse.HttpResponse = resp - return collaboratorResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_delegation_signer_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_delegation_signer_records.go deleted file mode 100644 index f2f0092..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_delegation_signer_records.go +++ /dev/null @@ -1,105 +0,0 @@ -package dnsimple - -import "fmt" - -// DelegationSignerRecord represents a delegation signer record for a domain in DNSimple. -type DelegationSignerRecord struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Algorithm string `json:"algorithm"` - Digest string `json:"digest"` - DigestType string `json:"digest_type"` - Keytag string `json:"keytag"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func delegationSignerRecordPath(accountID string, domainIdentifier string, dsRecordID int64) (path string) { - path = fmt.Sprintf("%v/ds_records", domainPath(accountID, domainIdentifier)) - if dsRecordID != 0 { - path += fmt.Sprintf("/%v", dsRecordID) - } - return -} - -// delegationSignerRecordResponse represents a response from an API method that returns a DelegationSignerRecord struct. -type delegationSignerRecordResponse struct { - Response - Data *DelegationSignerRecord `json:"data"` -} - -// delegationSignerRecordResponse represents a response from an API method that returns a DelegationSignerRecord struct. -type delegationSignerRecordsResponse struct { - Response - Data []DelegationSignerRecord `json:"data"` -} - -// ListDelegationSignerRecords lists the delegation signer records for a domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-list -func (s *DomainsService) ListDelegationSignerRecords(accountID string, domainIdentifier string, options *ListOptions) (*delegationSignerRecordsResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, 0)) - dsRecordsResponse := &delegationSignerRecordsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, dsRecordsResponse) - if err != nil { - return nil, err - } - - dsRecordsResponse.HttpResponse = resp - return dsRecordsResponse, nil -} - -// CreateDelegationSignerRecord creates a new delegation signer record. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-create -func (s *DomainsService) CreateDelegationSignerRecord(accountID string, domainIdentifier string, dsRecordAttributes DelegationSignerRecord) (*delegationSignerRecordResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, 0)) - dsRecordResponse := &delegationSignerRecordResponse{} - - resp, err := s.client.post(path, dsRecordAttributes, dsRecordResponse) - if err != nil { - return nil, err - } - - dsRecordResponse.HttpResponse = resp - return dsRecordResponse, nil -} - -// GetDelegationSignerRecord fetches a delegation signer record. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-get -func (s *DomainsService) GetDelegationSignerRecord(accountID string, domainIdentifier string, dsRecordID int64) (*delegationSignerRecordResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, dsRecordID)) - dsRecordResponse := &delegationSignerRecordResponse{} - - resp, err := s.client.get(path, dsRecordResponse) - if err != nil { - return nil, err - } - - dsRecordResponse.HttpResponse = resp - return dsRecordResponse, nil -} - -// DeleteDelegationSignerRecord PERMANENTLY deletes a delegation signer record -// from the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-delete -func (s *DomainsService) DeleteDelegationSignerRecord(accountID string, domainIdentifier string, dsRecordID int64) (*delegationSignerRecordResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, dsRecordID)) - dsRecordResponse := &delegationSignerRecordResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - dsRecordResponse.HttpResponse = resp - return dsRecordResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_dnssec.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_dnssec.go deleted file mode 100644 index 1ef054b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_dnssec.go +++ /dev/null @@ -1,70 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// Dnssec represents the current DNSSEC settings for a domain in DNSimple. -type Dnssec struct { - Enabled bool `json:"enabled"` -} - -func dnssecPath(accountID string, domainIdentifier string) (path string) { - path = fmt.Sprintf("%v/dnssec", domainPath(accountID, domainIdentifier)) - return -} - -// dnssecResponse represents a response from an API method that returns a Dnssec struct. -type dnssecResponse struct { - Response - Data *Dnssec `json:"data"` -} - -// EnableDnssec enables DNSSEC on the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#enable - -func (s *DomainsService) EnableDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) { - path := versioned(dnssecPath(accountID, domainIdentifier)) - dnssecResponse := &dnssecResponse{} - - resp, err := s.client.post(path, dnssecResponse, nil) - if err != nil { - return nil, err - } - - dnssecResponse.HttpResponse = resp - return dnssecResponse, nil -} - -// DisableDnssec disables DNSSEC on the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#disable -func (s *DomainsService) DisableDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) { - path := versioned(dnssecPath(accountID, domainIdentifier)) - dnssecResponse := &dnssecResponse{} - - resp, err := s.client.delete(path, dnssecResponse, nil) - if err != nil { - return nil, err - } - - dnssecResponse.HttpResponse = resp - return dnssecResponse, nil -} - -// GetDnssec retrieves the current status of DNSSEC on the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#get -func (s *DomainsService) GetDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) { - path := versioned(dnssecPath(accountID, domainIdentifier)) - dnssecResponse := &dnssecResponse{} - - resp, err := s.client.get(path, dnssecResponse) - if err != nil { - return nil, err - } - - dnssecResponse.HttpResponse = resp - return dnssecResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_email_forwards.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_email_forwards.go deleted file mode 100644 index 3d4299a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_email_forwards.go +++ /dev/null @@ -1,104 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// EmailForward represents an email forward in DNSimple. -type EmailForward struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - From string `json:"from,omitempty"` - To string `json:"to,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func emailForwardPath(accountID string, domainIdentifier string, forwardID int64) (path string) { - path = fmt.Sprintf("%v/email_forwards", domainPath(accountID, domainIdentifier)) - if forwardID != 0 { - path += fmt.Sprintf("/%v", forwardID) - } - return -} - -// emailForwardResponse represents a response from an API method that returns an EmailForward struct. -type emailForwardResponse struct { - Response - Data *EmailForward `json:"data"` -} - -// emailForwardsResponse represents a response from an API method that returns a collection of EmailForward struct. -type emailForwardsResponse struct { - Response - Data []EmailForward `json:"data"` -} - -// ListEmailForwards lists the email forwards for a domain. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#list -func (s *DomainsService) ListEmailForwards(accountID string, domainIdentifier string, options *ListOptions) (*emailForwardsResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, 0)) - forwardsResponse := &emailForwardsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, forwardsResponse) - if err != nil { - return nil, err - } - - forwardsResponse.HttpResponse = resp - return forwardsResponse, nil -} - -// CreateEmailForward creates a new email forward. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#create -func (s *DomainsService) CreateEmailForward(accountID string, domainIdentifier string, forwardAttributes EmailForward) (*emailForwardResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, 0)) - forwardResponse := &emailForwardResponse{} - - resp, err := s.client.post(path, forwardAttributes, forwardResponse) - if err != nil { - return nil, err - } - - forwardResponse.HttpResponse = resp - return forwardResponse, nil -} - -// GetEmailForward fetches an email forward. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#get -func (s *DomainsService) GetEmailForward(accountID string, domainIdentifier string, forwardID int64) (*emailForwardResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, forwardID)) - forwardResponse := &emailForwardResponse{} - - resp, err := s.client.get(path, forwardResponse) - if err != nil { - return nil, err - } - - forwardResponse.HttpResponse = resp - return forwardResponse, nil -} - -// DeleteEmailForward PERMANENTLY deletes an email forward from the domain. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#delete -func (s *DomainsService) DeleteEmailForward(accountID string, domainIdentifier string, forwardID int64) (*emailForwardResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, forwardID)) - forwardResponse := &emailForwardResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - forwardResponse.HttpResponse = resp - return forwardResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_pushes.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_pushes.go deleted file mode 100644 index b965c7d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_pushes.go +++ /dev/null @@ -1,111 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// DomainPush represents a domain push in DNSimple. -type DomainPush struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - ContactID int64 `json:"contact_id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - AcceptedAt string `json:"accepted_at,omitempty"` -} - -func domainPushPath(accountID string, pushID int64) (path string) { - path = fmt.Sprintf("/%v/pushes", accountID) - if pushID != 0 { - path += fmt.Sprintf("/%v", pushID) - } - return -} - -// domainPushResponse represents a response from an API method that returns a DomainPush struct. -type domainPushResponse struct { - Response - Data *DomainPush `json:"data"` -} - -// domainPushesResponse represents a response from an API method that returns a collection of DomainPush struct. -type domainPushesResponse struct { - Response - Data []DomainPush `json:"data"` -} - -// DomainPushAttributes represent a domain push payload (see initiate). -type DomainPushAttributes struct { - NewAccountEmail string `json:"new_account_email,omitempty"` - ContactID int64 `json:"contact_id,omitempty"` -} - -// InitiatePush initiate a new domain push. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#initiate -func (s *DomainsService) InitiatePush(accountID, domainID string, pushAttributes DomainPushAttributes) (*domainPushResponse, error) { - path := versioned(fmt.Sprintf("/%v/pushes", domainPath(accountID, domainID))) - pushResponse := &domainPushResponse{} - - resp, err := s.client.post(path, pushAttributes, pushResponse) - if err != nil { - return nil, err - } - - pushResponse.HttpResponse = resp - return pushResponse, nil -} - -// ListPushes lists the pushes for an account. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#list -func (s *DomainsService) ListPushes(accountID string, options *ListOptions) (*domainPushesResponse, error) { - path := versioned(domainPushPath(accountID, 0)) - pushesResponse := &domainPushesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, pushesResponse) - if err != nil { - return nil, err - } - - pushesResponse.HttpResponse = resp - return pushesResponse, nil -} - -// AcceptPush accept a push for a domain. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#accept -func (s *DomainsService) AcceptPush(accountID string, pushID int64, pushAttributes DomainPushAttributes) (*domainPushResponse, error) { - path := versioned(domainPushPath(accountID, pushID)) - pushResponse := &domainPushResponse{} - - resp, err := s.client.post(path, pushAttributes, nil) - if err != nil { - return nil, err - } - - pushResponse.HttpResponse = resp - return pushResponse, nil -} - -// RejectPush reject a push for a domain. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#reject -func (s *DomainsService) RejectPush(accountID string, pushID int64) (*domainPushResponse, error) { - path := versioned(domainPushPath(accountID, pushID)) - pushResponse := &domainPushResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - pushResponse.HttpResponse = resp - return pushResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/identity.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/identity.go deleted file mode 100644 index be7ca9e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/identity.go +++ /dev/null @@ -1,48 +0,0 @@ -package dnsimple - -// IdentityService handles communication with several authentication identity -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/identity/ -type IdentityService struct { - client *Client -} - -// WhoamiData represents an authenticated context -// that contains information about the current logged User and/or Account. -type WhoamiData struct { - User *User `json:"user,omitempty"` - Account *Account `json:"account,omitempty"` -} - -// whoamiResponse represents a response from an API method that returns a Whoami struct. -type whoamiResponse struct { - Response - Data *WhoamiData `json:"data"` -} - -// Whoami gets the current authenticate context. -// -// See https://developer.dnsimple.com/v2/whoami -func (s *IdentityService) Whoami() (*whoamiResponse, error) { - path := versioned("/whoami") - whoamiResponse := &whoamiResponse{} - - resp, err := s.client.get(path, whoamiResponse) - if err != nil { - return nil, err - } - - whoamiResponse.HttpResponse = resp - return whoamiResponse, nil -} - -// Whoami is a state-less shortcut to client.Whoami() -// that returns only the relevant Data. -func Whoami(c *Client) (data *WhoamiData, err error) { - resp, err := c.Identity.Whoami() - if resp != nil { - data = resp.Data - } - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/oauth.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/oauth.go deleted file mode 100644 index 74a2b34..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/oauth.go +++ /dev/null @@ -1,113 +0,0 @@ -package dnsimple - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" -) - -// GrantType is a string that identifies a particular grant type in the exchange request. -type GrantType string - -const ( - // AuthorizationCodeGrant is the type of access token request - // for an Authorization Code Grant flow. - // https://tools.ietf.org/html/rfc6749#section-4.1 - AuthorizationCodeGrant = GrantType("authorization_code") -) - -// OauthService handles communication with the authorization related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/oauth/ -type OauthService struct { - client *Client -} - -// AccessToken represents a DNSimple Oauth access token. -type AccessToken struct { - Token string `json:"access_token"` - Type string `json:"token_type"` - AccountID int `json:"account_id"` -} - -// ExchangeAuthorizationRequest represents a request to exchange -// an authorization code for an access token. -// RedirectURI is optional, all the other fields are mandatory. -type ExchangeAuthorizationRequest struct { - Code string `json:"code"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - RedirectURI string `json:"redirect_uri,omitempty"` - State string `json:"state,omitempty"` - GrantType GrantType `json:"grant_type,omitempty"` -} - -// ExchangeAuthorizationError represents a failed request to exchange -// an authorization code for an access token. -type ExchangeAuthorizationError struct { - // HTTP response - HttpResponse *http.Response - - ErrorCode string `json:"error"` - ErrorDescription string `json:"error_description"` -} - -// Error implements the error interface. -func (r *ExchangeAuthorizationError) Error() string { - return fmt.Sprintf("%v %v: %v %v", - r.HttpResponse.Request.Method, r.HttpResponse.Request.URL, - r.ErrorCode, r.ErrorDescription) -} - -// ExchangeAuthorizationForToken exchanges the short-lived authorization code for an access token -// you can use to authenticate your API calls. -func (s *OauthService) ExchangeAuthorizationForToken(authorization *ExchangeAuthorizationRequest) (*AccessToken, error) { - path := versioned("/oauth/access_token") - - req, err := s.client.NewRequest("POST", path, authorization) - if err != nil { - return nil, err - } - - resp, err := s.client.httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - errorResponse := &ExchangeAuthorizationError{} - errorResponse.HttpResponse = resp - json.NewDecoder(resp.Body).Decode(errorResponse) - return nil, errorResponse - } - - accessToken := &AccessToken{} - err = json.NewDecoder(resp.Body).Decode(accessToken) - - return accessToken, err -} - -// AuthorizationOptions represents the option you can use to generate an authorization URL. -type AuthorizationOptions struct { - RedirectURI string `url:"redirect_uri,omitempty"` - // A randomly generated string to verify the validity of the request. - // Currently "state" is required by the DNSimple OAuth implementation, so you must specify it. - State string `url:"state,omitempty"` -} - -// AuthorizeURL generates the URL to authorize an user for an application via the OAuth2 flow. -func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string { - uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1)) - uri.Path = "/oauth/authorize" - query := uri.Query() - query.Add("client_id", clientID) - query.Add("response_type", "code") - uri.RawQuery = query.Encode() - - path, _ := addURLQueryOptions(uri.String(), options) - return path -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go deleted file mode 100644 index 625bbb2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go +++ /dev/null @@ -1,261 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// RegistrarService handles communication with the registrar related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/registrar/ -type RegistrarService struct { - client *Client -} - -// DomainCheck represents the result of a domain check. -type DomainCheck struct { - Domain string `json:"domain"` - Available bool `json:"available"` - Premium bool `json:"premium"` -} - -// domainCheckResponse represents a response from a domain check request. -type domainCheckResponse struct { - Response - Data *DomainCheck `json:"data"` -} - -// CheckDomain checks a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#check -func (s *RegistrarService) CheckDomain(accountID string, domainName string) (*domainCheckResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/check", accountID, domainName)) - checkResponse := &domainCheckResponse{} - - resp, err := s.client.get(path, checkResponse) - if err != nil { - return nil, err - } - - checkResponse.HttpResponse = resp - return checkResponse, nil -} - -// DomainPremiumPrice represents the premium price for a premium domain. -type DomainPremiumPrice struct { - // The domain premium price - PremiumPrice string `json:"premium_price"` - // The registrar action. - // Possible values are registration|transfer|renewal - Action string `json:"action"` -} - -// domainPremiumPriceResponse represents a response from a domain premium price request. -type domainPremiumPriceResponse struct { - Response - Data *DomainPremiumPrice `json:"data"` -} - -// DomainPremiumPriceOptions specifies the optional parameters you can provide -// to customize the RegistrarService.GetDomainPremiumPrice method. -type DomainPremiumPriceOptions struct { - Action string `url:"action,omitempty"` -} - -// Gets the premium price for a domain. -// -// You must specify an action to get the price for. Valid actions are: -// - registration -// - transfer -// - renewal -// -// See https://developer.dnsimple.com/v2/registrar/#premium-price -func (s *RegistrarService) GetDomainPremiumPrice(accountID string, domainName string, options *DomainPremiumPriceOptions) (*domainPremiumPriceResponse, error) { - var err error - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/premium_price", accountID, domainName)) - priceResponse := &domainPremiumPriceResponse{} - - if options != nil { - path, err = addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - } - - resp, err := s.client.get(path, priceResponse) - if err != nil { - return nil, err - } - - priceResponse.HttpResponse = resp - return priceResponse, nil -} - -// DomainRegistration represents the result of a domain renewal call. -type DomainRegistration struct { - ID int `json:"id"` - DomainID int `json:"domain_id"` - RegistrantID int `json:"registrant_id"` - Period int `json:"period"` - State string `json:"state"` - AutoRenew bool `json:"auto_renew"` - WhoisPrivacy bool `json:"whois_privacy"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// domainRegistrationResponse represents a response from an API method that results in a domain registration. -type domainRegistrationResponse struct { - Response - Data *DomainRegistration `json:"data"` -} - -// DomainRegisterRequest represents the attributes you can pass to a register API request. -// Some attributes are mandatory. -type DomainRegisterRequest struct { - // The ID of the Contact to use as registrant for the domain - RegistrantID int `json:"registrant_id"` - // Set to true to enable the whois privacy service. An extra cost may apply. - // Default to false. - EnableWhoisPrivacy bool `json:"whois_privacy,omitempty"` - // Set to true to enable the auto-renewal of the domain. - // Default to true. - EnableAutoRenewal bool `json:"auto_renew,omitempty"` - // Required as confirmation of the price, only if the domain is premium. - PremiumPrice string `json:"premium_price,omitempty"` -} - -// RegisterDomain registers a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#register -func (s *RegistrarService) RegisterDomain(accountID string, domainName string, request *DomainRegisterRequest) (*domainRegistrationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/registrations", accountID, domainName)) - registrationResponse := &domainRegistrationResponse{} - - // TODO: validate mandatory attributes RegistrantID - - resp, err := s.client.post(path, request, registrationResponse) - if err != nil { - return nil, err - } - - registrationResponse.HttpResponse = resp - return registrationResponse, nil -} - -// DomainTransfer represents the result of a domain renewal call. -type DomainTransfer struct { - ID int `json:"id"` - DomainID int `json:"domain_id"` - RegistrantID int `json:"registrant_id"` - State string `json:"state"` - AutoRenew bool `json:"auto_renew"` - WhoisPrivacy bool `json:"whois_privacy"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// domainTransferResponse represents a response from an API method that results in a domain transfer. -type domainTransferResponse struct { - Response - Data *DomainTransfer `json:"data"` -} - -// DomainTransferRequest represents the attributes you can pass to a transfer API request. -// Some attributes are mandatory. -type DomainTransferRequest struct { - // The ID of the Contact to use as registrant for the domain - RegistrantID int `json:"registrant_id"` - // The Auth-Code required to transfer the domain. - // This is provided by the current registrar of the domain. - AuthCode string `json:"auth_code,omitempty"` - // Set to true to enable the whois privacy service. An extra cost may apply. - // Default to false. - EnableWhoisPrivacy bool `json:"whois_privacy,omitempty"` - // Set to true to enable the auto-renewal of the domain. - // Default to true. - EnableAutoRenewal bool `json:"auto_renew,omitempty"` - // Required as confirmation of the price, only if the domain is premium. - PremiumPrice string `json:"premium_price,omitempty"` -} - -// TransferDomain transfers a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#transfer -func (s *RegistrarService) TransferDomain(accountID string, domainName string, request *DomainTransferRequest) (*domainTransferResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/transfers", accountID, domainName)) - transferResponse := &domainTransferResponse{} - - // TODO: validate mandatory attributes RegistrantID - - resp, err := s.client.post(path, request, transferResponse) - if err != nil { - return nil, err - } - - transferResponse.HttpResponse = resp - return transferResponse, nil -} - -// domainTransferOutResponse represents a response from an API method that results in a domain transfer out. -type domainTransferOutResponse struct { - Response - Data *Domain `json:"data"` -} - -// Transfer out a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#transfer-out -func (s *RegistrarService) TransferDomainOut(accountID string, domainName string) (*domainTransferOutResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/authorize_transfer_out", accountID, domainName)) - transferResponse := &domainTransferOutResponse{} - - resp, err := s.client.post(path, nil, nil) - if err != nil { - return nil, err - } - - transferResponse.HttpResponse = resp - return transferResponse, nil -} - -// DomainRenewal represents the result of a domain renewal call. -type DomainRenewal struct { - ID int `json:"id"` - DomainID int `json:"domain_id"` - Period int `json:"period"` - State string `json:"state"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// domainRenewalResponse represents a response from an API method that returns a domain renewal. -type domainRenewalResponse struct { - Response - Data *DomainRenewal `json:"data"` -} - -// DomainRenewRequest represents the attributes you can pass to a renew API request. -// Some attributes are mandatory. -type DomainRenewRequest struct { - // The number of years - Period int `json:"period"` - // Required as confirmation of the price, only if the domain is premium. - PremiumPrice string `json:"premium_price,omitempty"` -} - -// RenewDomain renews a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#register -func (s *RegistrarService) RenewDomain(accountID string, domainName string, request *DomainRenewRequest) (*domainRenewalResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/renewals", accountID, domainName)) - renewalResponse := &domainRenewalResponse{} - - resp, err := s.client.post(path, request, renewalResponse) - if err != nil { - return nil, err - } - - renewalResponse.HttpResponse = resp - return renewalResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_auto_renewal.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_auto_renewal.go deleted file mode 100644 index c98f8d5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_auto_renewal.go +++ /dev/null @@ -1,37 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// EnableDomainAutoRenewal enables auto-renewal for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/auto-renewal/#enable -func (s *RegistrarService) EnableDomainAutoRenewal(accountID string, domainName string) (*domainResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/auto_renewal", accountID, domainName)) - domainResponse := &domainResponse{} - - resp, err := s.client.put(path, nil, nil) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// DisableDomainAutoRenewal disables auto-renewal for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/auto-renewal/#enable -func (s *RegistrarService) DisableDomainAutoRenewal(accountID string, domainName string) (*domainResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/auto_renewal", accountID, domainName)) - domainResponse := &domainResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_delegation.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_delegation.go deleted file mode 100644 index 4ebd345..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_delegation.go +++ /dev/null @@ -1,84 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// Delegation represents a list of name servers that correspond to a domain delegation. -type Delegation []string - -// delegationResponse represents a response from an API method that returns a delegation struct. -type delegationResponse struct { - Response - Data *Delegation `json:"data"` -} - -// vanityDelegationResponse represents a response for vanity name server enable and disable operations. -type vanityDelegationResponse struct { - Response - Data []VanityNameServer `json:"data"` -} - -// GetDomainDelegation gets the current delegated name servers for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#get -func (s *RegistrarService) GetDomainDelegation(accountID string, domainName string) (*delegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation", accountID, domainName)) - delegationResponse := &delegationResponse{} - - resp, err := s.client.get(path, delegationResponse) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} - -// ChangeDomainDelegation updates the delegated name severs for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#get -func (s *RegistrarService) ChangeDomainDelegation(accountID string, domainName string, newDelegation *Delegation) (*delegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation", accountID, domainName)) - delegationResponse := &delegationResponse{} - - resp, err := s.client.put(path, newDelegation, delegationResponse) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} - -// ChangeDomainDelegationToVanity enables vanity name servers for the given domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#delegateToVanity -func (s *RegistrarService) ChangeDomainDelegationToVanity(accountID string, domainName string, newDelegation *Delegation) (*vanityDelegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation/vanity", accountID, domainName)) - delegationResponse := &vanityDelegationResponse{} - - resp, err := s.client.put(path, newDelegation, delegationResponse) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} - -// ChangeDomainDelegationFromVanity disables vanity name servers for the given domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#dedelegateFromVanity -func (s *RegistrarService) ChangeDomainDelegationFromVanity(accountID string, domainName string) (*vanityDelegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation/vanity", accountID, domainName)) - delegationResponse := &vanityDelegationResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_whois_privacy.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_whois_privacy.go deleted file mode 100644 index edf47b1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_whois_privacy.go +++ /dev/null @@ -1,69 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// WhoisPrivacy represents a whois privacy in DNSimple. -type WhoisPrivacy struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Enabled bool `json:"enabled,omitempty"` - ExpiresOn string `json:"expires_on,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// whoisPrivacyResponse represents a response from an API method that returns a WhoisPrivacy struct. -type whoisPrivacyResponse struct { - Response - Data *WhoisPrivacy `json:"data"` -} - -// GetWhoisPrivacy gets the whois privacy for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/whois-privacy/#get -func (s *RegistrarService) GetWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy", accountID, domainName)) - privacyResponse := &whoisPrivacyResponse{} - - resp, err := s.client.get(path, privacyResponse) - if err != nil { - return nil, err - } - - privacyResponse.HttpResponse = resp - return privacyResponse, nil -} - -// EnableWhoisPrivacy enables the whois privacy for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/whois-privacy/#enable -func (s *RegistrarService) EnableWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy", accountID, domainName)) - privacyResponse := &whoisPrivacyResponse{} - - resp, err := s.client.put(path, nil, privacyResponse) - if err != nil { - return nil, err - } - - privacyResponse.HttpResponse = resp - return privacyResponse, nil -} - -// DisablePrivacy disables the whois privacy for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/whois-privacy/#enable -func (s *RegistrarService) DisableWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy", accountID, domainName)) - privacyResponse := &whoisPrivacyResponse{} - - resp, err := s.client.delete(path, nil, privacyResponse) - if err != nil { - return nil, err - } - - privacyResponse.HttpResponse = resp - return privacyResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services.go deleted file mode 100644 index 18afd11..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services.go +++ /dev/null @@ -1,94 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ServicesService handles communication with the service related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/services/ -type ServicesService struct { - client *Client -} - -// Service represents a Service in DNSimple. -type Service struct { - ID int64 `json:"id,omitempty"` - SID string `json:"sid,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - SetupDescription string `json:"setup_description,omitempty"` - RequiresSetup bool `json:"requires_setup,omitempty"` - DefaultSubdomain string `json:"default_subdomain,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Settings []ServiceSetting `json:"settings,omitempty"` -} - -// ServiceSetting represents a single group of settings for a DNSimple Service. -type ServiceSetting struct { - Name string `json:"name,omitempty"` - Label string `json:"label,omitempty"` - Append string `json:"append,omitempty"` - Description string `json:"description,omitempty"` - Example string `json:"example,omitempty"` - Password bool `json:"password,omitempty"` -} - -func servicePath(serviceIdentifier string) (path string) { - path = "/services" - if serviceIdentifier != "" { - path += fmt.Sprintf("/%v", serviceIdentifier) - } - return -} - -// serviceResponse represents a response from an API method that returns a Service struct. -type serviceResponse struct { - Response - Data *Service `json:"data"` -} - -// servicesResponse represents a response from an API method that returns a collection of Service struct. -type servicesResponse struct { - Response - Data []Service `json:"data"` -} - -// ListServices lists the one-click services available in DNSimple. -// -// See https://developer.dnsimple.com/v2/services/#list -func (s *ServicesService) ListServices(options *ListOptions) (*servicesResponse, error) { - path := versioned(servicePath("")) - servicesResponse := &servicesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, servicesResponse) - if err != nil { - return servicesResponse, err - } - - servicesResponse.HttpResponse = resp - return servicesResponse, nil -} - -// GetService fetches a one-click service. -// -// See https://developer.dnsimple.com/v2/services/#get -func (s *ServicesService) GetService(serviceIdentifier string) (*serviceResponse, error) { - path := versioned(servicePath(serviceIdentifier)) - serviceResponse := &serviceResponse{} - - resp, err := s.client.get(path, serviceResponse) - if err != nil { - return nil, err - } - - serviceResponse.HttpResponse = resp - return serviceResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services_domains.go deleted file mode 100644 index 0426dd6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services_domains.go +++ /dev/null @@ -1,70 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -func domainServicesPath(accountID string, domainIdentifier string, serviceIdentifier string) string { - if serviceIdentifier != "" { - return fmt.Sprintf("/%v/domains/%v/services/%v", accountID, domainIdentifier, serviceIdentifier) - } - return fmt.Sprintf("/%v/domains/%v/services", accountID, domainIdentifier) -} - -// DomainServiceSettings represents optional settings when applying a DNSimple one-click service to a domain. -type DomainServiceSettings struct { - Settings map[string]string `url:"settings,omitempty"` -} - -// AppliedServices lists the applied one-click services for a domain. -// -// See https://developer.dnsimple.com/v2/services/domains/#applied -func (s *ServicesService) AppliedServices(accountID string, domainIdentifier string, options *ListOptions) (*servicesResponse, error) { - path := versioned(domainServicesPath(accountID, domainIdentifier, "")) - servicesResponse := &servicesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, servicesResponse) - if err != nil { - return servicesResponse, err - } - - servicesResponse.HttpResponse = resp - return servicesResponse, nil -} - -// ApplyService applies a one-click services to a domain. -// -// See https://developer.dnsimple.com/v2/services/domains/#apply -func (s *ServicesService) ApplyService(accountID string, serviceIdentifier string, domainIdentifier string, settings DomainServiceSettings) (*serviceResponse, error) { - path := versioned(domainServicesPath(accountID, domainIdentifier, serviceIdentifier)) - serviceResponse := &serviceResponse{} - - resp, err := s.client.post(path, settings, nil) - if err != nil { - return nil, err - } - - serviceResponse.HttpResponse = resp - return serviceResponse, nil -} - -// UnapplyService unapplies a one-click services from a domain. -// -// See https://developer.dnsimple.com/v2/services/domains/#unapply -func (s *ServicesService) UnapplyService(accountID string, serviceIdentifier string, domainIdentifier string) (*serviceResponse, error) { - path := versioned(domainServicesPath(accountID, domainIdentifier, serviceIdentifier)) - serviceResponse := &serviceResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - serviceResponse.HttpResponse = resp - return serviceResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates.go deleted file mode 100644 index 0cd2ec8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates.go +++ /dev/null @@ -1,129 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// TemplatesService handles communication with the template related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/templates/ -type TemplatesService struct { - client *Client -} - -// Template represents a Template in DNSimple. -type Template struct { - ID int64 `json:"id,omitempty"` - SID string `json:"sid,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func templatePath(accountID string, templateIdentifier string) (path string) { - path = fmt.Sprintf("/%v/templates", accountID) - if templateIdentifier != "" { - path += fmt.Sprintf("/%v", templateIdentifier) - } - return -} - -// templateResponse represents a response from an API method that returns a Template struct. -type templateResponse struct { - Response - Data *Template `json:"data"` -} - -// templatesResponse represents a response from an API method that returns a collection of Template struct. -type templatesResponse struct { - Response - Data []Template `json:"data"` -} - -// ListTemplates list the templates for an account. -// -// See https://developer.dnsimple.com/v2/templates/#list -func (s *TemplatesService) ListTemplates(accountID string, options *ListOptions) (*templatesResponse, error) { - path := versioned(templatePath(accountID, "")) - templatesResponse := &templatesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, templatesResponse) - if err != nil { - return templatesResponse, err - } - - templatesResponse.HttpResponse = resp - return templatesResponse, nil -} - -// CreateTemplate creates a new template. -// -// See https://developer.dnsimple.com/v2/templates/#create -func (s *TemplatesService) CreateTemplate(accountID string, templateAttributes Template) (*templateResponse, error) { - path := versioned(templatePath(accountID, "")) - templateResponse := &templateResponse{} - - resp, err := s.client.post(path, templateAttributes, templateResponse) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} - -// GetTemplate fetches a template. -// -// See https://developer.dnsimple.com/v2/templates/#get -func (s *TemplatesService) GetTemplate(accountID string, templateIdentifier string) (*templateResponse, error) { - path := versioned(templatePath(accountID, templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.get(path, templateResponse) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} - -// UpdateTemplate updates a template. -// -// See https://developer.dnsimple.com/v2/templates/#update -func (s *TemplatesService) UpdateTemplate(accountID string, templateIdentifier string, templateAttributes Template) (*templateResponse, error) { - path := versioned(templatePath(accountID, templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.patch(path, templateAttributes, templateResponse) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} - -// DeleteTemplate deletes a template. -// -// See https://developer.dnsimple.com/v2/templates/#delete -func (s *TemplatesService) DeleteTemplate(accountID string, templateIdentifier string) (*templateResponse, error) { - path := versioned(templatePath(accountID, templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_domains.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_domains.go deleted file mode 100644 index 01901bb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ApplyTemplate applies a template to the given domain. -// -// See https://developer.dnsimple.com/v2/templates/domains/#apply -func (s *TemplatesService) ApplyTemplate(accountID string, templateIdentifier string, domainIdentifier string) (*templateResponse, error) { - path := versioned(fmt.Sprintf("%v/templates/%v", domainPath(accountID, domainIdentifier), templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.post(path, nil, nil) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_records.go deleted file mode 100644 index 74f6fd6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_records.go +++ /dev/null @@ -1,107 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// TemplateRecord represents a DNS record for a template in DNSimple. -type TemplateRecord struct { - ID int64 `json:"id,omitempty"` - TemplateID int64 `json:"template_id,omitempty"` - Name string `json:"name"` - Content string `json:"content,omitempty"` - TTL int `json:"ttl,omitempty"` - Type string `json:"type,omitempty"` - Priority int `json:"priority,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func templateRecordPath(accountID string, templateIdentifier string, templateRecordID int64) string { - if templateRecordID != 0 { - return fmt.Sprintf("%v/records/%v", templatePath(accountID, templateIdentifier), templateRecordID) - } - - return templatePath(accountID, templateIdentifier) + "/records" -} - -// templateRecordResponse represents a response from an API method that returns a TemplateRecord struct. -type templateRecordResponse struct { - Response - Data *TemplateRecord `json:"data"` -} - -// templateRecordsResponse represents a response from an API method that returns a collection of TemplateRecord struct. -type templateRecordsResponse struct { - Response - Data []TemplateRecord `json:"data"` -} - -// ListTemplateRecords list the templates for an account. -// -// See https://developer.dnsimple.com/v2/templates/records/#list -func (s *TemplatesService) ListTemplateRecords(accountID string, templateIdentifier string, options *ListOptions) (*templateRecordsResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, 0)) - templateRecordsResponse := &templateRecordsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, templateRecordsResponse) - if err != nil { - return templateRecordsResponse, err - } - - templateRecordsResponse.HttpResponse = resp - return templateRecordsResponse, nil -} - -// CreateTemplateRecord creates a new template record. -// -// See https://developer.dnsimple.com/v2/templates/records/#create -func (s *TemplatesService) CreateTemplateRecord(accountID string, templateIdentifier string, templateRecordAttributes TemplateRecord) (*templateRecordResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, 0)) - templateRecordResponse := &templateRecordResponse{} - - resp, err := s.client.post(path, templateRecordAttributes, templateRecordResponse) - if err != nil { - return nil, err - } - - templateRecordResponse.HttpResponse = resp - return templateRecordResponse, nil -} - -// GetTemplateRecord fetches a template record. -// -// See https://developer.dnsimple.com/v2/templates/records/#get -func (s *TemplatesService) GetTemplateRecord(accountID string, templateIdentifier string, templateRecordID int64) (*templateRecordResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, templateRecordID)) - templateRecordResponse := &templateRecordResponse{} - - resp, err := s.client.get(path, templateRecordResponse) - if err != nil { - return nil, err - } - - templateRecordResponse.HttpResponse = resp - return templateRecordResponse, nil -} - -// DeleteTemplateRecord deletes a template record. -// -// See https://developer.dnsimple.com/v2/templates/records/#delete -func (s *TemplatesService) DeleteTemplateRecord(accountID string, templateIdentifier string, templateRecordID int64) (*templateRecordResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, templateRecordID)) - templateRecordResponse := &templateRecordResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - templateRecordResponse.HttpResponse = resp - return templateRecordResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/tlds.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/tlds.go deleted file mode 100644 index ee0da04..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/tlds.go +++ /dev/null @@ -1,117 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// TldsService handles communication with the Tld related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/tlds/ -type TldsService struct { - client *Client -} - -// Tld represents a TLD in DNSimple. -type Tld struct { - Tld string `json:"tld"` - TldType int `json:"tld_type"` - WhoisPrivacy bool `json:"whois_privacy"` - AutoRenewOnly bool `json:"auto_renew_only"` - MinimumRegistration int `json:"minimum_registration"` - RegistrationEnabled bool `json:"registration_enabled"` - RenewalEnabled bool `json:"renewal_enabled"` - TransferEnabled bool `json:"transfer_enabled"` -} - -// TldExtendedAttribute represents an extended attributes supported or required -// by a specific TLD. -// -// See https://developer.dnsimple.com/v2/tlds/ -type TldExtendedAttribute struct { - Name string `json:"name"` - Description string `json:"description"` - Required bool `json:"required"` - Options []TldExtendedAttributeOption `json:"options"` -} - -// TldExtendedAttributeOption represents a single option you can assign to an extended attributes. -// -// See https://developer.dnsimple.com/v2/tlds/ -type TldExtendedAttributeOption struct { - Title string `json:"title"` - Value string `json:"value"` - Description string `json:"description"` -} - -// tldResponse represents a response from an API method that returns a Tld struct. -type tldResponse struct { - Response - Data *Tld `json:"data"` -} - -// tldsResponse represents a response from an API method that returns a collection of Tld struct. -type tldsResponse struct { - Response - Data []Tld `json:"data"` -} - -// tldExtendedAttributesResponse represents a response from an API method that returns -// a collection of Tld extended attributes. -type tldExtendedAttributesResponse struct { - Response - Data []TldExtendedAttribute `json:"data"` -} - -// ListTlds lists the supported TLDs. -// -// See https://developer.dnsimple.com/v2/tlds/#list -func (s *TldsService) ListTlds(options *ListOptions) (*tldsResponse, error) { - path := versioned("/tlds") - tldsResponse := &tldsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, tldsResponse) - if err != nil { - return tldsResponse, err - } - - tldsResponse.HttpResponse = resp - return tldsResponse, nil -} - -// GetTld fetches a TLD. -// -// See https://developer.dnsimple.com/v2/tlds/#get -func (s *TldsService) GetTld(tld string) (*tldResponse, error) { - path := versioned(fmt.Sprintf("/tlds/%s", tld)) - tldResponse := &tldResponse{} - - resp, err := s.client.get(path, tldResponse) - if err != nil { - return nil, err - } - - tldResponse.HttpResponse = resp - return tldResponse, nil -} - -// GetTld fetches the extended attributes of a TLD. -// -// See https://developer.dnsimple.com/v2/tlds/#get -func (s *TldsService) GetTldExtendedAttributes(tld string) (*tldExtendedAttributesResponse, error) { - path := versioned(fmt.Sprintf("/tlds/%s/extended_attributes", tld)) - tldResponse := &tldExtendedAttributesResponse{} - - resp, err := s.client.get(path, tldResponse) - if err != nil { - return nil, err - } - - tldResponse.HttpResponse = resp - return tldResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/users.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/users.go deleted file mode 100644 index 9c33f40..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/users.go +++ /dev/null @@ -1,7 +0,0 @@ -package dnsimple - -// User represents a DNSimple user. -type User struct { - ID int64 `json:"id,omitempty"` - Email string `json:"email,omitempty"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/vanity_name_server.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/vanity_name_server.go deleted file mode 100644 index cd1314a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/vanity_name_server.go +++ /dev/null @@ -1,65 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// VanityNameServersService handles communication with Vanity Name Servers -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/vanity/ -type VanityNameServersService struct { - client *Client -} - -// VanityNameServer represents data for a single vanity name server -type VanityNameServer struct { - ID int64 `json:"id,omitempty"` - Name string `json:"name,omitempty"` - IPv4 string `json:"ipv4,omitempty"` - IPv6 string `json:"ipv6,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func vanityNameServerPath(accountID string, domainIdentifier string) string { - return fmt.Sprintf("/%v/vanity/%v", accountID, domainIdentifier) -} - -// vanityNameServerResponse represents a response for vanity name server enable and disable operations. -type vanityNameServerResponse struct { - Response - Data []VanityNameServer `json:"data"` -} - -// EnableVanityNameServers Vanity Name Servers for the given domain -// -// See https://developer.dnsimple.com/v2/vanity/#enable -func (s *VanityNameServersService) EnableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) { - path := versioned(vanityNameServerPath(accountID, domainIdentifier)) - vanityNameServerResponse := &vanityNameServerResponse{} - - resp, err := s.client.put(path, nil, vanityNameServerResponse) - if err != nil { - return nil, err - } - - vanityNameServerResponse.HttpResponse = resp - return vanityNameServerResponse, nil -} - -// DisableVanityNameServers Vanity Name Servers for the given domain -// -// See https://developer.dnsimple.com/v2/vanity/#disable -func (s *VanityNameServersService) DisableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) { - path := versioned(vanityNameServerPath(accountID, domainIdentifier)) - vanityNameServerResponse := &vanityNameServerResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - vanityNameServerResponse.HttpResponse = resp - return vanityNameServerResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/webhooks.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/webhooks.go deleted file mode 100644 index 1426333..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/webhooks.go +++ /dev/null @@ -1,103 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// WebhooksService handles communication with the webhook related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/webhooks -type WebhooksService struct { - client *Client -} - -// Webhook represents a DNSimple webhook. -type Webhook struct { - ID int64 `json:"id,omitempty"` - URL string `json:"url,omitempty"` -} - -func webhookPath(accountID string, webhookID int64) (path string) { - path = fmt.Sprintf("/%v/webhooks", accountID) - if webhookID != 0 { - path = fmt.Sprintf("%v/%v", path, webhookID) - } - return -} - -// webhookResponse represents a response from an API method that returns a Webhook struct. -type webhookResponse struct { - Response - Data *Webhook `json:"data"` -} - -// webhookResponse represents a response from an API method that returns a collection of Webhook struct. -type webhooksResponse struct { - Response - Data []Webhook `json:"data"` -} - -// ListWebhooks lists the webhooks for an account. -// -// See https://developer.dnsimple.com/v2/webhooks#list -func (s *WebhooksService) ListWebhooks(accountID string, _ *ListOptions) (*webhooksResponse, error) { - path := versioned(webhookPath(accountID, 0)) - webhooksResponse := &webhooksResponse{} - - resp, err := s.client.get(path, webhooksResponse) - if err != nil { - return webhooksResponse, err - } - - webhooksResponse.HttpResponse = resp - return webhooksResponse, nil -} - -// CreateWebhook creates a new webhook. -// -// See https://developer.dnsimple.com/v2/webhooks#create -func (s *WebhooksService) CreateWebhook(accountID string, webhookAttributes Webhook) (*webhookResponse, error) { - path := versioned(webhookPath(accountID, 0)) - webhookResponse := &webhookResponse{} - - resp, err := s.client.post(path, webhookAttributes, webhookResponse) - if err != nil { - return nil, err - } - - webhookResponse.HttpResponse = resp - return webhookResponse, nil -} - -// GetWebhook fetches a webhook. -// -// See https://developer.dnsimple.com/v2/webhooks#get -func (s *WebhooksService) GetWebhook(accountID string, webhookID int64) (*webhookResponse, error) { - path := versioned(webhookPath(accountID, webhookID)) - webhookResponse := &webhookResponse{} - - resp, err := s.client.get(path, webhookResponse) - if err != nil { - return nil, err - } - - webhookResponse.HttpResponse = resp - return webhookResponse, nil -} - -// DeleteWebhook PERMANENTLY deletes a webhook from the account. -// -// See https://developer.dnsimple.com/v2/webhooks#delete -func (s *WebhooksService) DeleteWebhook(accountID string, webhookID int64) (*webhookResponse, error) { - path := versioned(webhookPath(accountID, webhookID)) - webhookResponse := &webhookResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - webhookResponse.HttpResponse = resp - return webhookResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zone_distributions.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zone_distributions.go deleted file mode 100644 index f92d757..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zone_distributions.go +++ /dev/null @@ -1,46 +0,0 @@ -package dnsimple - -import "fmt" - -// ZoneDistribution is the result of the zone distribution check. -type ZoneDistribution struct { - Distributed bool `json:"distributed"` -} - -// zoneDistributionResponse represents a response from an API method that returns a ZoneDistribution struct. -type zoneDistributionResponse struct { - Response - Data *ZoneDistribution `json:"data"` -} - -// CheckZoneDistribution checks if a zone is fully distributed across DNSimple nodes. -// -// See https://developer.dnsimple.com/v2/zones/#checkZoneDistribution -func (s *ZonesService) CheckZoneDistribution(accountID string, zoneName string) (*zoneDistributionResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v/distribution", accountID, zoneName)) - zoneDistributionResponse := &zoneDistributionResponse{} - - resp, err := s.client.get(path, zoneDistributionResponse) - if err != nil { - return nil, err - } - - zoneDistributionResponse.HttpResponse = resp - return zoneDistributionResponse, nil -} - -// CheckZoneRecordDistribution checks if a zone is fully distributed across DNSimple nodes. -// -// See https://developer.dnsimple.com/v2/zones/#checkZoneRecordDistribution -func (s *ZonesService) CheckZoneRecordDistribution(accountID string, zoneName string, recordID int64) (*zoneDistributionResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v/records/%v/distribution", accountID, zoneName, recordID)) - zoneDistributionResponse := &zoneDistributionResponse{} - - resp, err := s.client.get(path, zoneDistributionResponse) - if err != nil { - return nil, err - } - - zoneDistributionResponse.HttpResponse = resp - return zoneDistributionResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones.go deleted file mode 100644 index f521fcf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones.go +++ /dev/null @@ -1,108 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ZonesService handles communication with the zone related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/zones/ -type ZonesService struct { - client *Client -} - -// Zone represents a Zone in DNSimple. -type Zone struct { - ID int64 `json:"id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - Name string `json:"name,omitempty"` - Reverse bool `json:"reverse,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// ZoneFile represents a Zone File in DNSimple. -type ZoneFile struct { - Zone string `json:"zone,omitempty"` -} - -// zoneResponse represents a response from an API method that returns a Zone struct. -type zoneResponse struct { - Response - Data *Zone `json:"data"` -} - -// zonesResponse represents a response from an API method that returns a collection of Zone struct. -type zonesResponse struct { - Response - Data []Zone `json:"data"` -} - -// zoneFileResponse represents a response from an API method that returns a ZoneFile struct. -type zoneFileResponse struct { - Response - Data *ZoneFile `json:"data"` -} - -// ZoneListOptions specifies the optional parameters you can provide -// to customize the ZonesService.ListZones method. -type ZoneListOptions struct { - // Select domains where the name contains given string. - NameLike string `url:"name_like,omitempty"` - - ListOptions -} - -// ListZones the zones for an account. -// -// See https://developer.dnsimple.com/v2/zones/#list -func (s *ZonesService) ListZones(accountID string, options *ZoneListOptions) (*zonesResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones", accountID)) - zonesResponse := &zonesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, zonesResponse) - if err != nil { - return zonesResponse, err - } - - zonesResponse.HttpResponse = resp - return zonesResponse, nil -} - -// GetZone fetches a zone. -// -// See https://developer.dnsimple.com/v2/zones/#get -func (s *ZonesService) GetZone(accountID string, zoneName string) (*zoneResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v", accountID, zoneName)) - zoneResponse := &zoneResponse{} - - resp, err := s.client.get(path, zoneResponse) - if err != nil { - return nil, err - } - - zoneResponse.HttpResponse = resp - return zoneResponse, nil -} - -// GetZoneFile fetches a zone file. -// -// See https://developer.dnsimple.com/v2/zones/#get-file -func (s *ZonesService) GetZoneFile(accountID string, zoneName string) (*zoneFileResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v/file", accountID, zoneName)) - zoneFileResponse := &zoneFileResponse{} - - resp, err := s.client.get(path, zoneFileResponse) - if err != nil { - return nil, err - } - - zoneFileResponse.HttpResponse = resp - return zoneFileResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones_records.go b/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones_records.go deleted file mode 100644 index fbb432d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones_records.go +++ /dev/null @@ -1,142 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ZoneRecord represents a DNS record in DNSimple. -type ZoneRecord struct { - ID int64 `json:"id,omitempty"` - ZoneID string `json:"zone_id,omitempty"` - ParentID int64 `json:"parent_id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name"` - Content string `json:"content,omitempty"` - TTL int `json:"ttl,omitempty"` - Priority int `json:"priority,omitempty"` - SystemRecord bool `json:"system_record,omitempty"` - Regions []string `json:"regions,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func zoneRecordPath(accountID string, zoneName string, recordID int64) (path string) { - path = fmt.Sprintf("/%v/zones/%v/records", accountID, zoneName) - if recordID != 0 { - path += fmt.Sprintf("/%v", recordID) - } - return -} - -// zoneRecordResponse represents a response from an API method that returns a ZoneRecord struct. -type zoneRecordResponse struct { - Response - Data *ZoneRecord `json:"data"` -} - -// zoneRecordsResponse represents a response from an API method that returns a collection of ZoneRecord struct. -type zoneRecordsResponse struct { - Response - Data []ZoneRecord `json:"data"` -} - -// ZoneRecordListOptions specifies the optional parameters you can provide -// to customize the ZonesService.ListZoneRecords method. -type ZoneRecordListOptions struct { - // Select records where the name matches given string. - Name string `url:"name,omitempty"` - - // Select records where the name contains given string. - NameLike string `url:"name_like,omitempty"` - - // Select records of given type. - // Eg. TXT, A, NS. - Type string `url:"type,omitempty"` - - ListOptions -} - -// ListRecords lists the zone records for a zone. -// -// See https://developer.dnsimple.com/v2/zones/records/#listZoneRecords -func (s *ZonesService) ListRecords(accountID string, zoneName string, options *ZoneRecordListOptions) (*zoneRecordsResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, 0)) - recordsResponse := &zoneRecordsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, recordsResponse) - if err != nil { - return nil, err - } - - recordsResponse.HttpResponse = resp - return recordsResponse, nil -} - -// CreateRecord creates a zone record. -// -// See https://developer.dnsimple.com/v2/zones/records/#createZoneRecord -func (s *ZonesService) CreateRecord(accountID string, zoneName string, recordAttributes ZoneRecord) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, 0)) - recordResponse := &zoneRecordResponse{} - - resp, err := s.client.post(path, recordAttributes, recordResponse) - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} - -// GetRecord fetches a zone record. -// -// See https://developer.dnsimple.com/v2/zones/records/#getZoneRecord -func (s *ZonesService) GetRecord(accountID string, zoneName string, recordID int64) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, recordID)) - recordResponse := &zoneRecordResponse{} - - resp, err := s.client.get(path, recordResponse) - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} - -// UpdateRecord updates a zone record. -// -// See https://developer.dnsimple.com/v2/zones/records/#updateZoneRecord -func (s *ZonesService) UpdateRecord(accountID string, zoneName string, recordID int64, recordAttributes ZoneRecord) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, recordID)) - recordResponse := &zoneRecordResponse{} - resp, err := s.client.patch(path, recordAttributes, recordResponse) - - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} - -// DeleteRecord PERMANENTLY deletes a zone record from the zone. -// -// See https://developer.dnsimple.com/v2/zones/records/#deleteZoneRecord -func (s *ZonesService) DeleteRecord(accountID string, zoneName string, recordID int64) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, recordID)) - recordResponse := &zoneRecordResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/AUTHORS b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/AUTHORS deleted file mode 100644 index 5c12a2a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/AUTHORS +++ /dev/null @@ -1,9 +0,0 @@ -Pierre-Yves Ritschard -Vincent Bernat -Chris Baumbauer -Marc-Aurèle Brothier -Sebastien Goasguen -Yoan Blanc -Stefano Marengo -Pierre-Emmanuel Jacquier -Fabrizio Steiner diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/LICENSE deleted file mode 100644 index 327ecb8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2014 exoscale(tm) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/accounts.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/accounts.go deleted file mode 100644 index 9bcdec6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/accounts.go +++ /dev/null @@ -1,80 +0,0 @@ -package egoscale - -// Account provides the detailed account information -type Account struct { - AccountDetails map[string]string `json:"accountdetails,omitempty" doc:"details for the account"` - CPUAvailable string `json:"cpuavailable,omitempty" doc:"the total number of cpu cores available to be created for this account"` - CPULimit string `json:"cpulimit,omitempty" doc:"the total number of cpu cores the account can own"` - CPUTotal int64 `json:"cputotal,omitempty" doc:"the total number of cpu cores owned by account"` - DefaultZoneID *UUID `json:"defaultzoneid,omitempty" doc:"the default zone of the account"` - EipLimit string `json:"eiplimit,omitempty" doc:"the total number of public elastic ip addresses this account can acquire"` - Groups []string `json:"groups,omitempty" doc:"the list of acl groups that account belongs to"` - ID *UUID `json:"id,omitempty" doc:"the id of the account"` - IPAvailable string `json:"ipavailable,omitempty" doc:"the total number of public ip addresses available for this account to acquire"` - IPLimit string `json:"iplimit,omitempty" doc:"the total number of public ip addresses this account can acquire"` - IPTotal int64 `json:"iptotal,omitempty" doc:"the total number of public ip addresses allocated for this account"` - IsCleanupRequired bool `json:"iscleanuprequired,omitempty" doc:"true if the account requires cleanup"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if account is default, false otherwise"` - MemoryAvailable string `json:"memoryavailable,omitempty" doc:"the total memory (in MB) available to be created for this account"` - MemoryLimit string `json:"memorylimit,omitempty" doc:"the total memory (in MB) the account can own"` - MemoryTotal int64 `json:"memorytotal,omitempty" doc:"the total memory (in MB) owned by account"` - Name string `json:"name,omitempty" doc:"the name of the account"` - NetworkAvailable string `json:"networkavailable,omitempty" doc:"the total number of networks available to be created for this account"` - NetworkDomain string `json:"networkdomain,omitempty" doc:"the network domain"` - NetworkLimit string `json:"networklimit,omitempty" doc:"the total number of networks the account can own"` - NetworkTotal int64 `json:"networktotal,omitempty" doc:"the total number of networks owned by account"` - PrimaryStorageAvailable string `json:"primarystorageavailable,omitempty" doc:"the total primary storage space (in GiB) available to be used for this account"` - PrimaryStorageLimit string `json:"primarystoragelimit,omitempty" doc:"the total primary storage space (in GiB) the account can own"` - PrimaryStorageTotal int64 `json:"primarystoragetotal,omitempty" doc:"the total primary storage space (in GiB) owned by account"` - ProjectAvailable string `json:"projectavailable,omitempty" doc:"the total number of projects available for administration by this account"` - ProjectLimit string `json:"projectlimit,omitempty" doc:"the total number of projects the account can own"` - ProjectTotal int64 `json:"projecttotal,omitempty" doc:"the total number of projects being administrated by this account"` - SecondaryStorageAvailable string `json:"secondarystorageavailable,omitempty" doc:"the total secondary storage space (in GiB) available to be used for this account"` - SecondaryStorageLimit string `json:"secondarystoragelimit,omitempty" doc:"the total secondary storage space (in GiB) the account can own"` - SecondaryStorageTotal int64 `json:"secondarystoragetotal,omitempty" doc:"the total secondary storage space (in GiB) owned by account"` - SMTP bool `json:"smtp,omitempty" doc:"if SMTP outbound is allowed"` - SnapshotAvailable string `json:"snapshotavailable,omitempty" doc:"the total number of snapshots available for this account"` - SnapshotLimit string `json:"snapshotlimit,omitempty" doc:"the total number of snapshots which can be stored by this account"` - SnapshotTotal int64 `json:"snapshottotal,omitempty" doc:"the total number of snapshots stored by this account"` - State string `json:"state,omitempty" doc:"the state of the account"` - TemplateAvailable string `json:"templateavailable,omitempty" doc:"the total number of templates available to be created by this account"` - TemplateLimit string `json:"templatelimit,omitempty" doc:"the total number of templates which can be created by this account"` - TemplateTotal int64 `json:"templatetotal,omitempty" doc:"the total number of templates which have been created by this account"` - User []User `json:"user,omitempty" doc:"the list of users associated with account"` - VMAvailable string `json:"vmavailable,omitempty" doc:"the total number of virtual machines available for this account to acquire"` - VMLimit string `json:"vmlimit,omitempty" doc:"the total number of virtual machines that can be deployed by this account"` - VMRunning int `json:"vmrunning,omitempty" doc:"the total number of virtual machines running for this account"` - VMStopped int `json:"vmstopped,omitempty" doc:"the total number of virtual machines stopped for this account"` - VMTotal int64 `json:"vmtotal,omitempty" doc:"the total number of virtual machines deployed by this account"` - VolumeAvailable string `json:"volumeavailable,omitempty" doc:"the total volume available for this account"` - VolumeLimit string `json:"volumelimit,omitempty" doc:"the total volume which can be used by this account"` - VolumeTotal int64 `json:"volumetotal,omitempty" doc:"the total volume being used by this account"` -} - -// ListRequest builds the ListAccountsGroups request -func (a Account) ListRequest() (ListCommand, error) { - return &ListAccounts{ - ID: a.ID, - State: a.State, - }, nil -} - -//go:generate go run generate/main.go -interface=Listable ListAccounts - -// ListAccounts represents a query to display the accounts -type ListAccounts struct { - ID *UUID `json:"id,omitempty" doc:"List account by account ID"` - IsCleanUpRequired *bool `json:"iscleanuprequired,omitempty" doc:"list accounts by cleanuprequired attribute (values are true or false)"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"List account by account name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - State string `json:"state,omitempty" doc:"List accounts by state. Valid states are enabled, disabled, and locked."` - _ bool `name:"listAccounts" description:"Lists accounts and provides detailed account information for listed accounts"` -} - -// ListAccountsResponse represents a list of accounts -type ListAccountsResponse struct { - Count int `json:"count"` - Account []Account `json:"account"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/accounts_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/accounts_response.go deleted file mode 100644 index 106daca..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/accounts_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListAccounts) Response() interface{} { - return new(ListAccountsResponse) -} - -// ListRequest returns itself -func (ls *ListAccounts) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListAccounts) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListAccounts) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListAccounts) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListAccountsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListAccountsResponse was expected, got %T", resp)) - return - } - - for i := range items.Account { - if !callback(&items.Account[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/addresses.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/addresses.go deleted file mode 100644 index 602915f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/addresses.go +++ /dev/null @@ -1,156 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "net" -) - -// IPAddress represents an IP Address -type IPAddress struct { - Allocated string `json:"allocated,omitempty" doc:"date the public IP address was acquired"` - Associated string `json:"associated,omitempty" doc:"date the public IP address was associated"` - AssociatedNetworkID *UUID `json:"associatednetworkid,omitempty" doc:"the ID of the Network associated with the IP address"` - AssociatedNetworkName string `json:"associatednetworkname,omitempty" doc:"the name of the Network associated with the IP address"` - ForVirtualNetwork bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the IP address"` - ID *UUID `json:"id,omitempty" doc:"public IP address id"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"public IP address"` - IsElastic bool `json:"iselastic,omitempty" doc:"is an elastic ip"` - IsPortable bool `json:"isportable,omitempty" doc:"is public IP portable across the zones"` - IsSourceNat bool `json:"issourcenat,omitempty" doc:"true if the IP address is a source nat address, false otherwise"` - IsStaticNat *bool `json:"isstaticnat,omitempty" doc:"true if this ip is for static nat, false otherwise"` - IsSystem bool `json:"issystem,omitempty" doc:"true if this ip is system ip (was allocated as a part of deployVm or createLbRule)"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the Network where ip belongs to"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"the physical network this belongs to"` - Purpose string `json:"purpose,omitempty" doc:"purpose of the IP address. In Acton this value is not null for Ips with isSystem=true, and can have either StaticNat or LB value"` - ReverseDNS []ReverseDNS `json:"reversedns,omitempty" doc:"the list of PTR record(s) associated with the ip address"` - State string `json:"state,omitempty" doc:"State of the ip address. Can be: Allocatin, Allocated and Releasing"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with ip address"` - VirtualMachineDisplayName string `json:"virtualmachinedisplayname,omitempty" doc:"virtual machine display name the ip address is assigned to (not null only for static nat Ip)"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"virtual machine id the ip address is assigned to (not null only for static nat Ip)"` - VirtualMachineName string `json:"virtualmachinename,omitempty" doc:"virtual machine name the ip address is assigned to (not null only for static nat Ip)"` - VlanID *UUID `json:"vlanid,omitempty" doc:"the ID of the VLAN associated with the IP address. This parameter is visible to ROOT admins only"` - VlanName string `json:"vlanname,omitempty" doc:"the VLAN associated with the IP address"` - VMIPAddress net.IP `json:"vmipaddress,omitempty" doc:"virtual machine (dnat) ip address (not null only for static nat Ip)"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the zone the public IP address belongs to"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the zone the public IP address belongs to"` -} - -// ResourceType returns the type of the resource -func (IPAddress) ResourceType() string { - return "PublicIpAddress" -} - -// ListRequest builds the ListAdresses request -func (ipaddress IPAddress) ListRequest() (ListCommand, error) { - req := &ListPublicIPAddresses{ - AssociatedNetworkID: ipaddress.AssociatedNetworkID, - ID: ipaddress.ID, - IPAddress: ipaddress.IPAddress, - PhysicalNetworkID: ipaddress.PhysicalNetworkID, - VlanID: ipaddress.VlanID, - ZoneID: ipaddress.ZoneID, - } - if ipaddress.IsElastic { - req.IsElastic = &ipaddress.IsElastic - } - if ipaddress.IsSourceNat { - req.IsSourceNat = &ipaddress.IsSourceNat - } - if ipaddress.ForVirtualNetwork { - req.ForVirtualNetwork = &ipaddress.ForVirtualNetwork - } - - return req, nil -} - -// Delete removes the resource -func (ipaddress IPAddress) Delete(ctx context.Context, client *Client) error { - if ipaddress.ID == nil { - return fmt.Errorf("an IPAddress may only be deleted using ID") - } - - return client.BooleanRequestWithContext(ctx, &DisassociateIPAddress{ - ID: ipaddress.ID, - }) -} - -// AssociateIPAddress (Async) represents the IP creation -type AssociateIPAddress struct { - IsPortable *bool `json:"isportable,omitempty" doc:"should be set to true if public IP is required to be transferable across zones, if not specified defaults to false"` - NetworkdID *UUID `json:"networkid,omitempty" doc:"The network this ip address should be associated to."` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the availability zone you want to acquire an public IP address from"` - _ bool `name:"associateIpAddress" description:"Acquires and associates a public IP to an account."` -} - -// Response returns the struct to unmarshal -func (AssociateIPAddress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AssociateIPAddress) AsyncResponse() interface{} { - return new(IPAddress) -} - -// DisassociateIPAddress (Async) represents the IP deletion -type DisassociateIPAddress struct { - ID *UUID `json:"id" doc:"the id of the public ip address to disassociate"` - _ bool `name:"disassociateIpAddress" description:"Disassociates an ip address from the account."` -} - -// Response returns the struct to unmarshal -func (DisassociateIPAddress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DisassociateIPAddress) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// UpdateIPAddress (Async) represents the IP modification -type UpdateIPAddress struct { - ID *UUID `json:"id" doc:"the id of the public ip address to update"` - CustomID *UUID `json:"customid,omitempty" doc:"an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only"` - _ bool `name:"updateIpAddress" description:"Updates an ip address"` -} - -// Response returns the struct to unmarshal -func (UpdateIPAddress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateIPAddress) AsyncResponse() interface{} { - return new(IPAddress) -} - -//go:generate go run generate/main.go -interface=Listable ListPublicIPAddresses - -// ListPublicIPAddresses represents a search for public IP addresses -type ListPublicIPAddresses struct { - AllocatedOnly *bool `json:"allocatedonly,omitempty" doc:"limits search results to allocated public IP addresses"` - AssociatedNetworkID *UUID `json:"associatednetworkid,omitempty" doc:"lists all public IP addresses associated to the network specified"` - ForLoadBalancing *bool `json:"forloadbalancing,omitempty" doc:"list only ips used for load balancing"` - ForVirtualNetwork *bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the IP address"` - ID *UUID `json:"id,omitempty" doc:"lists ip address by id"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"lists the specified IP address"` - IsElastic *bool `json:"iselastic,omitempty" doc:"list only elastic ip addresses"` - IsSourceNat *bool `json:"issourcenat,omitempty" doc:"list only source nat ip addresses"` - IsStaticNat *bool `json:"isstaticnat,omitempty" doc:"list only static nat ip addresses"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"lists all public IP addresses by physical network id"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - VlanID *UUID `json:"vlanid,omitempty" doc:"lists all public IP addresses by VLAN ID"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"lists all public IP addresses by Zone ID"` - _ bool `name:"listPublicIpAddresses" description:"Lists all public ip addresses"` -} - -// ListPublicIPAddressesResponse represents a list of public IP addresses -type ListPublicIPAddressesResponse struct { - Count int `json:"count"` - PublicIPAddress []IPAddress `json:"publicipaddress"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/affinity_groups.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/affinity_groups.go deleted file mode 100644 index 90268be..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/affinity_groups.go +++ /dev/null @@ -1,158 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "net/url" -) - -// AffinityGroup represents an (anti-)affinity group -// -// Affinity and Anti-Affinity groups provide a way to influence where VMs should run. -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html#affinity-groups -type AffinityGroup struct { - Account string `json:"account,omitempty" doc:"the account owning the affinity group"` - Description string `json:"description,omitempty" doc:"the description of the affinity group"` - ID *UUID `json:"id,omitempty" doc:"the ID of the affinity group"` - Name string `json:"name,omitempty" doc:"the name of the affinity group"` - Type string `json:"type,omitempty" doc:"the type of the affinity group"` - VirtualMachineIDs []string `json:"virtualmachineIds,omitempty" doc:"virtual machine Ids associated with this affinity group"` -} - -// ListRequest builds the ListAffinityGroups request -func (ag AffinityGroup) ListRequest() (ListCommand, error) { - return &ListAffinityGroups{ - ID: ag.ID, - Name: ag.Name, - }, nil -} - -// Delete removes the given Affinity Group -func (ag AffinityGroup) Delete(ctx context.Context, client *Client) error { - if ag.ID == nil && ag.Name == "" { - return fmt.Errorf("an Affinity Group may only be deleted using ID or Name") - } - - req := &DeleteAffinityGroup{} - - if ag.ID != nil { - req.ID = ag.ID - } else { - req.Name = ag.Name - } - - return client.BooleanRequestWithContext(ctx, req) -} - -// AffinityGroupType represent an affinity group type -type AffinityGroupType struct { - Type string `json:"type,omitempty" doc:"the type of the affinity group"` -} - -// CreateAffinityGroup (Async) represents a new (anti-)affinity group -type CreateAffinityGroup struct { - Description string `json:"description,omitempty" doc:"Optional description of the affinity group"` - Name string `json:"name,omitempty" doc:"Name of the affinity group"` - Type string `json:"type" doc:"Type of the affinity group from the available affinity/anti-affinity group types"` - _ bool `name:"createAffinityGroup" description:"Creates an affinity/anti-affinity group"` -} - -func (req CreateAffinityGroup) onBeforeSend(params url.Values) error { - // Name must be set, but can be empty - if req.Name == "" { - params.Set("name", "") - } - return nil -} - -// Response returns the struct to unmarshal -func (CreateAffinityGroup) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (CreateAffinityGroup) AsyncResponse() interface{} { - return new(AffinityGroup) -} - -// UpdateVMAffinityGroup (Async) represents a modification of a (anti-)affinity group -type UpdateVMAffinityGroup struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - AffinityGroupIDs []UUID `json:"affinitygroupids,omitempty" doc:"comma separated list of affinity groups id that are going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter"` - AffinityGroupNames []string `json:"affinitygroupnames,omitempty" doc:"comma separated list of affinity groups names that are going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter"` - _ bool `name:"updateVMAffinityGroup" description:"Updates the affinity/anti-affinity group associations of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect."` -} - -func (req UpdateVMAffinityGroup) onBeforeSend(params url.Values) error { - // Either AffinityGroupIDs or AffinityGroupNames must be set - if len(req.AffinityGroupIDs) == 0 && len(req.AffinityGroupNames) == 0 { - params.Set("affinitygroupids", "") - } - return nil -} - -// Response returns the struct to unmarshal -func (UpdateVMAffinityGroup) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateVMAffinityGroup) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// DeleteAffinityGroup (Async) represents an (anti-)affinity group to be deleted -type DeleteAffinityGroup struct { - ID *UUID `json:"id,omitempty" doc:"The ID of the affinity group. Mutually exclusive with name parameter"` - Name string `json:"name,omitempty" doc:"The name of the affinity group. Mutually exclusive with ID parameter"` - _ bool `name:"deleteAffinityGroup" description:"Deletes affinity group"` -} - -// Response returns the struct to unmarshal -func (DeleteAffinityGroup) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteAffinityGroup) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListAffinityGroups - -// ListAffinityGroups represents an (anti-)affinity groups search -type ListAffinityGroups struct { - ID *UUID `json:"id,omitempty" doc:"List the affinity group by the ID provided"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"Lists affinity groups by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - Type string `json:"type,omitempty" doc:"Lists affinity groups by type"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"Lists affinity groups by virtual machine ID"` - _ bool `name:"listAffinityGroups" description:"Lists affinity groups"` -} - -// ListAffinityGroupsResponse represents a list of (anti-)affinity groups -type ListAffinityGroupsResponse struct { - Count int `json:"count"` - AffinityGroup []AffinityGroup `json:"affinitygroup"` -} - -// ListAffinityGroupTypes represents an (anti-)affinity groups search -type ListAffinityGroupTypes struct { - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listAffinityGroupTypes" description:"Lists affinity group types available"` -} - -// Response returns the struct to unmarshal -func (ListAffinityGroupTypes) Response() interface{} { - return new(ListAffinityGroupTypesResponse) -} - -// ListAffinityGroupTypesResponse represents a list of (anti-)affinity group types -type ListAffinityGroupTypesResponse struct { - Count int `json:"count"` - AffinityGroupType []AffinityGroupType `json:"affinitygrouptype"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/affinitygroups_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/affinitygroups_response.go deleted file mode 100644 index 12c5bd7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/affinitygroups_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListAffinityGroups) Response() interface{} { - return new(ListAffinityGroupsResponse) -} - -// ListRequest returns itself -func (ls *ListAffinityGroups) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListAffinityGroups) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListAffinityGroups) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListAffinityGroups) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListAffinityGroupsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListAffinityGroupsResponse was expected, got %T", resp)) - return - } - - for i := range items.AffinityGroup { - if !callback(&items.AffinityGroup[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/apis.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/apis.go deleted file mode 100644 index 098a037..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/apis.go +++ /dev/null @@ -1,48 +0,0 @@ -package egoscale - -// API represents an API service -type API struct { - Description string `json:"description,omitempty" doc:"description of the api"` - IsAsync bool `json:"isasync" doc:"true if api is asynchronous"` - Name string `json:"name,omitempty" doc:"the name of the api command"` - Related string `json:"related,omitempty" doc:"comma separated related apis"` - Since string `json:"since,omitempty" doc:"version of CloudStack the api was introduced in"` - Type string `json:"type,omitempty" doc:"response field type"` - Params []APIParam `json:"params,omitempty" doc:"the list params the api accepts"` - Response []APIField `json:"response,omitempty" doc:"api response fields"` -} - -// APIParam represents an API parameter field -type APIParam struct { - Description string `json:"description"` - Length int64 `json:"length"` - Name string `json:"name"` - Required bool `json:"required"` - Since string `json:"since,omitempty"` - Type string `json:"type"` -} - -// APIField represents an API response field -type APIField struct { - Description string `json:"description"` - Name string `json:"name"` - Response []APIField `json:"response,omitempty"` - Type string `json:"type"` -} - -// ListAPIs represents a query to list the api -type ListAPIs struct { - Name string `json:"name,omitempty" doc:"API name"` - _ bool `name:"listApis" description:"lists all available apis on the server"` -} - -// ListAPIsResponse represents a list of API -type ListAPIsResponse struct { - Count int `json:"count"` - API []API `json:"api"` -} - -// Response returns the struct to unmarshal -func (*ListAPIs) Response() interface{} { - return new(ListAPIsResponse) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/async_jobs.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/async_jobs.go deleted file mode 100644 index d815aab..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/async_jobs.go +++ /dev/null @@ -1,96 +0,0 @@ -package egoscale - -import ( - "encoding/json" - "errors" -) - -// AsyncJobResult represents an asynchronous job result -type AsyncJobResult struct { - AccountID *UUID `json:"accountid,omitempty" doc:"the account that executed the async command"` - Cmd string `json:"cmd,omitempty" doc:"the async command executed"` - Created string `json:"created,omitempty" doc:"the created date of the job"` - JobID *UUID `json:"jobid" doc:"extra field for the initial async call"` - JobInstanceID *UUID `json:"jobinstanceid,omitempty" doc:"the unique ID of the instance/entity object related to the job"` - JobInstanceType string `json:"jobinstancetype,omitempty" doc:"the instance/entity object related to the job"` - JobProcStatus int `json:"jobprocstatus,omitempty" doc:"the progress information of the PENDING job"` - JobResult *json.RawMessage `json:"jobresult,omitempty" doc:"the result reason"` - JobResultCode int `json:"jobresultcode,omitempty" doc:"the result code for the job"` - JobResultType string `json:"jobresulttype,omitempty" doc:"the result type"` - JobStatus JobStatusType `json:"jobstatus,omitempty" doc:"the current job status-should be 0 for PENDING"` - UserID *UUID `json:"userid,omitempty" doc:"the user that executed the async command"` -} - -// ListRequest buils the (empty) ListAsyncJobs request -func (a AsyncJobResult) ListRequest() (ListCommand, error) { - req := &ListAsyncJobs{ - StartDate: a.Created, - } - - return req, nil -} - -// Error builds an error message from the result -func (a AsyncJobResult) Error() error { - r := new(ErrorResponse) - if e := json.Unmarshal(*a.JobResult, r); e != nil { - return e - } - return r -} - -// QueryAsyncJobResult represents a query to fetch the status of async job -type QueryAsyncJobResult struct { - JobID *UUID `json:"jobid" doc:"the ID of the asynchronous job"` - _ bool `name:"queryAsyncJobResult" description:"Retrieves the current status of asynchronous job."` -} - -// Response returns the struct to unmarshal -func (QueryAsyncJobResult) Response() interface{} { - return new(AsyncJobResult) -} - -//go:generate go run generate/main.go -interface=Listable ListAsyncJobs - -// ListAsyncJobs list the asynchronous jobs -type ListAsyncJobs struct { - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - StartDate string `json:"startdate,omitempty" doc:"the start date of the async job"` - _ bool `name:"listAsyncJobs" description:"Lists all pending asynchronous jobs for the account."` -} - -// ListAsyncJobsResponse represents a list of job results -type ListAsyncJobsResponse struct { - Count int `json:"count"` - AsyncJob []AsyncJobResult `json:"asyncjobs"` -} - -// Result unmarshals the result of an AsyncJobResult into the given interface -func (a AsyncJobResult) Result(i interface{}) error { - if a.JobStatus == Failure { - return a.Error() - } - - if a.JobStatus == Success { - m := map[string]json.RawMessage{} - err := json.Unmarshal(*(a.JobResult), &m) - - if err == nil { - if len(m) >= 1 { - if _, ok := m["success"]; ok { - return json.Unmarshal(*(a.JobResult), i) - } - - // otherwise, pick the first key - for k := range m { - return json.Unmarshal(m[k], i) - } - } - return errors.New("empty response") - } - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/asyncjobs_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/asyncjobs_response.go deleted file mode 100644 index e4744e8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/asyncjobs_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListAsyncJobs) Response() interface{} { - return new(ListAsyncJobsResponse) -} - -// ListRequest returns itself -func (ls *ListAsyncJobs) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListAsyncJobs) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListAsyncJobs) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListAsyncJobs) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListAsyncJobsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListAsyncJobsResponse was expected, got %T", resp)) - return - } - - for i := range items.AsyncJob { - if !callback(&items.AsyncJob[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/cidr.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/cidr.go deleted file mode 100644 index 74c054b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/cidr.go +++ /dev/null @@ -1,62 +0,0 @@ -package egoscale - -import ( - "bytes" - "encoding/json" - "fmt" - "net" -) - -// CIDR represents a nicely JSON serializable net.IPNet -type CIDR struct { - net.IPNet -} - -// UnmarshalJSON unmarshals the raw JSON into the MAC address -func (cidr *CIDR) UnmarshalJSON(b []byte) error { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - c, err := ParseCIDR(s) - if err != nil { - return err - } - *cidr = CIDR{c.IPNet} - - return nil -} - -// MarshalJSON converts the CIDR to a string representation -func (cidr CIDR) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("%q", cidr)), nil -} - -// String returns the string representation of a CIDR -func (cidr CIDR) String() string { - return cidr.IPNet.String() -} - -// ParseCIDR parses a CIDR from a string -func ParseCIDR(s string) (*CIDR, error) { - _, net, err := net.ParseCIDR(s) - if err != nil { - return nil, err - } - return &CIDR{*net}, nil -} - -// MustParseCIDR forces parseCIDR or panics -func MustParseCIDR(s string) *CIDR { - cidr, err := ParseCIDR(s) - if err != nil { - panic(err) - } - - return cidr -} - -// Equal compare two CIDR -func (cidr CIDR) Equal(c CIDR) bool { - return (cidr.IPNet.IP.Equal(c.IPNet.IP) && bytes.Equal(cidr.IPNet.Mask, c.IPNet.Mask)) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/client.go deleted file mode 100644 index 083dedd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/client.go +++ /dev/null @@ -1,410 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/http/httputil" - "os" - "reflect" - "strings" - "time" -) - -// Taggable represents a resource to which tags can be attached -// -// This is a helper to fill the resourcetype of a CreateTags call -type Taggable interface { - // ResourceType is the name of the Taggable type - ResourceType() string -} - -// Deletable represents an Interface that can be "Delete" by the client -type Deletable interface { - // Delete removes the given resource(s) or throws - Delete(context context.Context, client *Client) error -} - -// Listable represents an Interface that can be "List" by the client -type Listable interface { - // ListRequest builds the list command - ListRequest() (ListCommand, error) -} - -// Client represents the API client -type Client struct { - // HTTPClient holds the HTTP client - HTTPClient *http.Client - // Endpoint is the HTTP URL - Endpoint string - // APIKey is the API identifier - APIKey string - // apisecret is the API secret, hence non exposed - apiSecret string - // PageSize represents the default size for a paginated result - PageSize int - // Timeout represents the default timeout for the async requests - Timeout time.Duration - // Expiration representation how long a signed payload may be used - Expiration time.Duration - // RetryStrategy represents the waiting strategy for polling the async requests - RetryStrategy RetryStrategyFunc - // Logger contains any log, plug your own - Logger *log.Logger -} - -// RetryStrategyFunc represents a how much time to wait between two calls to the API -type RetryStrategyFunc func(int64) time.Duration - -// IterateItemFunc represents the callback to iterate a list of results, if false stops -type IterateItemFunc func(interface{}, error) bool - -// WaitAsyncJobResultFunc represents the callback to wait a results of an async request, if false stops -type WaitAsyncJobResultFunc func(*AsyncJobResult, error) bool - -// NewClient creates an API client with default timeout (60) -// -// Timeout is set to both the HTTP client and the client itself. -func NewClient(endpoint, apiKey, apiSecret string) *Client { - timeout := 60 * time.Second - expiration := 10 * time.Minute - - httpClient := &http.Client{ - Transport: http.DefaultTransport, - } - - client := &Client{ - HTTPClient: httpClient, - Endpoint: endpoint, - APIKey: apiKey, - apiSecret: apiSecret, - PageSize: 50, - Timeout: timeout, - Expiration: expiration, - RetryStrategy: MonotonicRetryStrategyFunc(2), - Logger: log.New(ioutil.Discard, "", 0), - } - - if prefix, ok := os.LookupEnv("EXOSCALE_TRACE"); ok { - client.Logger = log.New(os.Stderr, prefix, log.LstdFlags) - client.TraceOn() - } - - return client -} - -// Get populates the given resource or fails -func (client *Client) Get(ls Listable) (interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.GetWithContext(ctx, ls) -} - -// GetWithContext populates the given resource or fails -func (client *Client) GetWithContext(ctx context.Context, ls Listable) (interface{}, error) { - gs, err := client.ListWithContext(ctx, ls) - if err != nil { - return nil, err - } - - count := len(gs) - if count != 1 { - req, err := ls.ListRequest() - if err != nil { - return nil, err - } - params, err := client.Payload(req) - if err != nil { - return nil, err - } - - // removing sensitive/useless informations - params.Del("expires") - params.Del("response") - params.Del("signature") - params.Del("signatureversion") - - // formatting the query string nicely - payload := params.Encode() - payload = strings.Replace(payload, "&", ", ", -1) - - if count == 0 { - return nil, &ErrorResponse{ - CSErrorCode: ServerAPIException, - ErrorCode: ParamError, - ErrorText: fmt.Sprintf("not found, query: %s", payload), - } - } - return nil, fmt.Errorf("more than one element found: %s", payload) - } - - return gs[0], nil -} - -// Delete removes the given resource of fails -func (client *Client) Delete(g Deletable) error { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.DeleteWithContext(ctx, g) -} - -// DeleteWithContext removes the given resource of fails -func (client *Client) DeleteWithContext(ctx context.Context, g Deletable) error { - return g.Delete(ctx, client) -} - -// List lists the given resource (and paginate till the end) -func (client *Client) List(g Listable) ([]interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.ListWithContext(ctx, g) -} - -// ListWithContext lists the given resources (and paginate till the end) -func (client *Client) ListWithContext(ctx context.Context, g Listable) (s []interface{}, err error) { - s = make([]interface{}, 0) - - defer func() { - if e := recover(); e != nil { - if g == nil || reflect.ValueOf(g).IsNil() { - err = fmt.Errorf("g Listable shouldn't be nil, got %#v", g) - return - } - - panic(e) - } - }() - - req, e := g.ListRequest() - if e != nil { - err = e - return - } - client.PaginateWithContext(ctx, req, func(item interface{}, e error) bool { - if item != nil { - s = append(s, item) - return true - } - err = e - return false - }) - - return -} - -// AsyncListWithContext lists the given resources (and paginate till the end) -// -// -// // NB: goroutine may leak if not read until the end. Create a proper context! -// ctx, cancel := context.WithCancel(context.Background()) -// defer cancel() -// -// outChan, errChan := client.AsyncListWithContext(ctx, new(egoscale.VirtualMachine)) -// -// for { -// select { -// case i, ok := <- outChan: -// if ok { -// vm := i.(egoscale.VirtualMachine) -// // ... -// } else { -// outChan = nil -// } -// case err, ok := <- errChan: -// if ok { -// // do something -// } -// // Once an error has been received, you can expect the channels to be closed. -// errChan = nil -// } -// if errChan == nil && outChan == nil { -// break -// } -// } -// -func (client *Client) AsyncListWithContext(ctx context.Context, g Listable) (<-chan interface{}, <-chan error) { - outChan := make(chan interface{}, client.PageSize) - errChan := make(chan error) - - go func() { - defer close(outChan) - defer close(errChan) - - req, err := g.ListRequest() - if err != nil { - errChan <- err - return - } - client.PaginateWithContext(ctx, req, func(item interface{}, e error) bool { - if item != nil { - outChan <- item - return true - } - errChan <- e - return false - }) - }() - - return outChan, errChan -} - -// Paginate runs the ListCommand and paginates -func (client *Client) Paginate(g Listable, callback IterateItemFunc) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - client.PaginateWithContext(ctx, g, callback) -} - -// PaginateWithContext runs the ListCommand as long as the ctx is valid -func (client *Client) PaginateWithContext(ctx context.Context, g Listable, callback IterateItemFunc) { - req, err := g.ListRequest() - if err != nil { - callback(nil, err) - return - } - - pageSize := client.PageSize - - page := 1 - - for { - req.SetPage(page) - req.SetPageSize(pageSize) - resp, err := client.RequestWithContext(ctx, req) - if err != nil { - // in case of 431, the response is knowingly empty - if errResponse, ok := err.(*ErrorResponse); ok && page == 1 && errResponse.ErrorCode == ParamError { - break - } - - callback(nil, err) - break - } - - size := 0 - didErr := false - req.Each(resp, func(element interface{}, err error) bool { - // If the context was cancelled, kill it in flight - if e := ctx.Err(); e != nil { - element = nil - err = e - } - - if callback(element, err) { - size++ - return true - } - - didErr = true - return false - }) - - if size < pageSize || didErr { - break - } - - page++ - } -} - -// APIName returns the name of the given command -func (client *Client) APIName(command Command) string { - // This is due to a limitation of Go<=1.7 - _, ok := command.(*AuthorizeSecurityGroupEgress) - _, okPtr := command.(AuthorizeSecurityGroupEgress) - if ok || okPtr { - return "authorizeSecurityGroupEgress" - } - - info, err := info(command) - if err != nil { - panic(err) - } - return info.Name -} - -// APIDescription returns the description of the given command -func (client *Client) APIDescription(command Command) string { - info, err := info(command) - if err != nil { - return "*missing description*" - } - return info.Description -} - -// Response returns the response structure of the given command -func (client *Client) Response(command Command) interface{} { - switch c := command.(type) { - case AsyncCommand: - return c.AsyncResponse() - default: - return command.Response() - } -} - -// TraceOn activates the HTTP tracer -func (client *Client) TraceOn() { - if _, ok := client.HTTPClient.Transport.(*traceTransport); !ok { - client.HTTPClient.Transport = &traceTransport{ - transport: client.HTTPClient.Transport, - logger: client.Logger, - } - } -} - -// TraceOff deactivates the HTTP tracer -func (client *Client) TraceOff() { - if rt, ok := client.HTTPClient.Transport.(*traceTransport); ok { - client.HTTPClient.Transport = rt.transport - } -} - -// traceTransport contains the original HTTP transport to enable it to be reverted -type traceTransport struct { - transport http.RoundTripper - logger *log.Logger -} - -// RoundTrip executes a single HTTP transaction -func (t *traceTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if dump, err := httputil.DumpRequest(req, true); err == nil { - t.logger.Printf("%s", dump) - } - - resp, err := t.transport.RoundTrip(req) - if err != nil { - return nil, err - } - - if dump, err := httputil.DumpResponse(resp, true); err == nil { - t.logger.Printf("%s", dump) - } - - return resp, nil -} - -// MonotonicRetryStrategyFunc returns a function that waits for n seconds for each iteration -func MonotonicRetryStrategyFunc(seconds int) RetryStrategyFunc { - return func(iteration int64) time.Duration { - return time.Duration(seconds) * time.Second - } -} - -// FibonacciRetryStrategy waits for an increasing amount of time following the Fibonacci sequence -func FibonacciRetryStrategy(iteration int64) time.Duration { - var a, b, i, tmp int64 - a = 0 - b = 1 - for i = 0; i < iteration; i++ { - tmp = a + b - a = b - b = tmp - } - return time.Duration(a) * time.Second -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/cserrorcode_string.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/cserrorcode_string.go deleted file mode 100644 index 4711d54..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/cserrorcode_string.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by "stringer -type CSErrorCode"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const _CSErrorCode_name = "CloudRuntimeExceptionExecutionExceptionHypervisorVersionChangedExceptionCloudExceptionAccountLimitExceptionAgentUnavailableExceptionCloudAuthenticationExceptionConcurrentOperationExceptionConflictingNetworkSettingsExceptionDiscoveredWithErrorExceptionHAStateExceptionInsufficientAddressCapacityExceptionInsufficientCapacityExceptionInsufficientNetworkCapacityExceptionInsufficientServerCapacityExceptionInsufficientStorageCapacityExceptionInternalErrorExceptionInvalidParameterValueExceptionManagementServerExceptionNetworkRuleConflictExceptionPermissionDeniedExceptionResourceAllocationExceptionResourceInUseExceptionResourceUnavailableExceptionStorageUnavailableExceptionUnsupportedServiceExceptionVirtualMachineMigrationExceptionAsyncCommandQueuedRequestLimitExceptionServerAPIException" - -var _CSErrorCode_map = map[CSErrorCode]string{ - 4250: _CSErrorCode_name[0:21], - 4260: _CSErrorCode_name[21:39], - 4265: _CSErrorCode_name[39:72], - 4275: _CSErrorCode_name[72:86], - 4280: _CSErrorCode_name[86:107], - 4285: _CSErrorCode_name[107:132], - 4290: _CSErrorCode_name[132:160], - 4300: _CSErrorCode_name[160:188], - 4305: _CSErrorCode_name[188:223], - 4310: _CSErrorCode_name[223:251], - 4315: _CSErrorCode_name[251:267], - 4320: _CSErrorCode_name[267:303], - 4325: _CSErrorCode_name[303:332], - 4330: _CSErrorCode_name[332:368], - 4335: _CSErrorCode_name[368:403], - 4340: _CSErrorCode_name[403:439], - 4345: _CSErrorCode_name[439:461], - 4350: _CSErrorCode_name[461:491], - 4355: _CSErrorCode_name[491:516], - 4360: _CSErrorCode_name[516:544], - 4365: _CSErrorCode_name[544:569], - 4370: _CSErrorCode_name[569:596], - 4375: _CSErrorCode_name[596:618], - 4380: _CSErrorCode_name[618:646], - 4385: _CSErrorCode_name[646:673], - 4390: _CSErrorCode_name[673:700], - 4395: _CSErrorCode_name[700:732], - 4540: _CSErrorCode_name[732:750], - 4545: _CSErrorCode_name[750:771], - 9999: _CSErrorCode_name[771:789], -} - -func (i CSErrorCode) String() string { - if str, ok := _CSErrorCode_map[i]; ok { - return str - } - return "CSErrorCode(" + strconv.FormatInt(int64(i), 10) + ")" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/dns.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/dns.go deleted file mode 100644 index 4b6535c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/dns.go +++ /dev/null @@ -1,367 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" -) - -// DNSDomain represents a domain -type DNSDomain struct { - ID int64 `json:"id"` - AccountID int64 `json:"account_id,omitempty"` - UserID int64 `json:"user_id,omitempty"` - RegistrantID int64 `json:"registrant_id,omitempty"` - Name string `json:"name"` - UnicodeName string `json:"unicode_name"` - Token string `json:"token"` - State string `json:"state"` - Language string `json:"language,omitempty"` - Lockable bool `json:"lockable"` - AutoRenew bool `json:"auto_renew"` - WhoisProtected bool `json:"whois_protected"` - RecordCount int64 `json:"record_count"` - ServiceCount int64 `json:"service_count"` - ExpiresOn string `json:"expires_on,omitempty"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` -} - -// DNSDomainResponse represents a domain creation response -type DNSDomainResponse struct { - Domain *DNSDomain `json:"domain"` -} - -// DNSRecord represents a DNS record -type DNSRecord struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Name string `json:"name"` - TTL int `json:"ttl,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Content string `json:"content"` - RecordType string `json:"record_type"` - Prio int `json:"prio,omitempty"` -} - -// DNSRecordResponse represents the creation of a DNS record -type DNSRecordResponse struct { - Record DNSRecord `json:"record"` -} - -// UpdateDNSRecord represents a DNS record -type UpdateDNSRecord struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Content string `json:"content,omitempty"` - RecordType string `json:"record_type,omitempty"` - Prio int `json:"prio,omitempty"` -} - -// UpdateDNSRecordResponse represents the creation of a DNS record -type UpdateDNSRecordResponse struct { - Record UpdateDNSRecord `json:"record"` -} - -// DNSErrorResponse represents an error in the API -type DNSErrorResponse struct { - Message string `json:"message,omitempty"` - Errors map[string][]string `json:"errors"` -} - -// Record represent record type -type Record int - -//go:generate stringer -type=Record -const ( - // A record type - A Record = iota - // AAAA record type - AAAA - // ALIAS record type - ALIAS - // CNAME record type - CNAME - // HINFO record type - HINFO - // MX record type - MX - // NAPTR record type - NAPTR - // NS record type - NS - // POOL record type - POOL - // SPF record type - SPF - // SRV record type - SRV - // SSHFP record type - SSHFP - // TXT record type - TXT - // URL record type - URL -) - -// Error formats the DNSerror into a string -func (req *DNSErrorResponse) Error() string { - if len(req.Errors) > 0 { - errs := []string{} - for name, ss := range req.Errors { - if len(ss) > 0 { - errs = append(errs, fmt.Sprintf("%s: %s", name, strings.Join(ss, ", "))) - } - } - return fmt.Sprintf("dns error: %s (%s)", req.Message, strings.Join(errs, "; ")) - } - return fmt.Sprintf("dns error: %s", req.Message) -} - -// CreateDomain creates a DNS domain -func (client *Client) CreateDomain(ctx context.Context, name string) (*DNSDomain, error) { - m, err := json.Marshal(DNSDomainResponse{ - Domain: &DNSDomain{ - Name: name, - }, - }) - if err != nil { - return nil, err - } - - resp, err := client.dnsRequest(ctx, "/v1/domains", nil, string(m), "POST") - if err != nil { - return nil, err - } - - var d *DNSDomainResponse - if err := json.Unmarshal(resp, &d); err != nil { - return nil, err - } - - return d.Domain, nil -} - -// GetDomain gets a DNS domain -func (client *Client) GetDomain(ctx context.Context, name string) (*DNSDomain, error) { - resp, err := client.dnsRequest(ctx, "/v1/domains/"+name, nil, "", "GET") - if err != nil { - return nil, err - } - - var d *DNSDomainResponse - if err := json.Unmarshal(resp, &d); err != nil { - return nil, err - } - - return d.Domain, nil -} - -// GetDomains gets DNS domains -func (client *Client) GetDomains(ctx context.Context) ([]DNSDomain, error) { - resp, err := client.dnsRequest(ctx, "/v1/domains", nil, "", "GET") - if err != nil { - return nil, err - } - - var d []DNSDomainResponse - if err := json.Unmarshal(resp, &d); err != nil { - return nil, err - } - - domains := make([]DNSDomain, len(d)) - for i := range d { - domains[i] = *d[i].Domain - } - return domains, nil -} - -// DeleteDomain delets a DNS domain -func (client *Client) DeleteDomain(ctx context.Context, name string) error { - _, err := client.dnsRequest(ctx, "/v1/domains/"+name, nil, "", "DELETE") - return err -} - -// GetRecord returns a DNS record -func (client *Client) GetRecord(ctx context.Context, domain string, recordID int64) (*DNSRecord, error) { - id := strconv.FormatInt(recordID, 10) - resp, err := client.dnsRequest(ctx, "/v1/domains/"+domain+"/records/"+id, nil, "", "GET") - if err != nil { - return nil, err - } - - var r DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - return &(r.Record), nil -} - -// GetRecords returns the DNS records -func (client *Client) GetRecords(ctx context.Context, domain string) ([]DNSRecord, error) { - resp, err := client.dnsRequest(ctx, "/v1/domains/"+domain+"/records", nil, "", "GET") - if err != nil { - return nil, err - } - - var r []DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - records := make([]DNSRecord, 0, len(r)) - for _, rec := range r { - records = append(records, rec.Record) - } - - return records, nil -} - -// GetRecordsWithFilters returns the DNS records (filters can be empty) -func (client *Client) GetRecordsWithFilters(ctx context.Context, domain, name, recordType string) ([]DNSRecord, error) { - - filters := url.Values{} - if name != "" { - filters.Add("name", name) - } - if recordType != "" { - filters.Add("record_type", recordType) - } - - resp, err := client.dnsRequest(ctx, "/v1/domains/"+domain+"/records", filters, "", "GET") - if err != nil { - return nil, err - } - - var r []DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - records := make([]DNSRecord, 0, len(r)) - for _, rec := range r { - records = append(records, rec.Record) - } - - return records, nil -} - -// CreateRecord creates a DNS record -func (client *Client) CreateRecord(ctx context.Context, name string, rec DNSRecord) (*DNSRecord, error) { - body, err := json.Marshal(DNSRecordResponse{ - Record: rec, - }) - if err != nil { - return nil, err - } - - resp, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records", nil, string(body), "POST") - if err != nil { - return nil, err - } - - var r DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - return &(r.Record), nil -} - -// UpdateRecord updates a DNS record -func (client *Client) UpdateRecord(ctx context.Context, name string, rec UpdateDNSRecord) (*DNSRecord, error) { - body, err := json.Marshal(UpdateDNSRecordResponse{ - Record: rec, - }) - if err != nil { - return nil, err - } - - id := strconv.FormatInt(rec.ID, 10) - resp, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records/"+id, nil, string(body), "PUT") - if err != nil { - return nil, err - } - - var r DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - return &(r.Record), nil -} - -// DeleteRecord deletes a record -func (client *Client) DeleteRecord(ctx context.Context, name string, recordID int64) error { - id := strconv.FormatInt(recordID, 10) - _, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records/"+id, nil, "", "DELETE") - - return err -} - -func (client *Client) dnsRequest(ctx context.Context, uri string, urlValues url.Values, params, method string) (json.RawMessage, error) { - rawURL := client.Endpoint + uri - url, err := url.Parse(rawURL) - if err != nil { - return nil, err - } - - q := url.Query() - for k, vs := range urlValues { - for _, v := range vs { - q.Add(k, v) - } - } - url.RawQuery = q.Encode() - - req, err := http.NewRequest(method, url.String(), strings.NewReader(params)) - if err != nil { - return nil, err - } - - var hdr = make(http.Header) - hdr.Add("X-DNS-TOKEN", client.APIKey+":"+client.apiSecret) - hdr.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version)) - hdr.Add("Accept", "application/json") - if params != "" { - hdr.Add("Content-Type", "application/json") - } - req.Header = hdr - - resp, err := client.HTTPClient.Do(req.WithContext(ctx)) - if err != nil { - return nil, err - } - defer resp.Body.Close() // nolint: errcheck - - contentType := resp.Header.Get("content-type") - if !strings.Contains(contentType, "application/json") { - return nil, fmt.Errorf(`response content-type expected to be "application/json", got %q`, contentType) - } - - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode >= 400 { - e := new(DNSErrorResponse) - if err := json.Unmarshal(b, e); err != nil { - return nil, err - } - return nil, e - } - - return b, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/doc.go deleted file mode 100644 index 0d9997e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/doc.go +++ /dev/null @@ -1,180 +0,0 @@ -/* - -Package egoscale is a mapping for the Exoscale API (https://community.exoscale.com/api/compute/). - -Requests and Responses - -To build a request, construct the adequate struct. This library expects a pointer for efficiency reasons only. The response is a struct corresponding to the data at stake. E.g. DeployVirtualMachine gives a VirtualMachine, as a pointer as well to avoid big copies. - -Then everything within the struct is not a pointer. Find below some examples of how egoscale may be used. If anything feels odd or unclear, please let us know: https://github.com/exoscale/egoscale/issues - - req := &egoscale.DeployVirtualMachine{ - Size: 10, - ServiceOfferingID: egoscale.MustParseUUID("..."), - TemplateID: egoscale.MustParseUUID("..."), - ZoneID: egoscale.MastParseUUID("..."), - } - - fmt.Println("Deployment started") - resp, err := cs.Request(req) - if err != nil { - panic(err) - } - - vm := resp.(*egoscale.VirtualMachine) - fmt.Printf("Virtual Machine ID: %s\n", vm.ID) - -This example deploys a virtual machine while controlling the job status as it goes. It enables a finer control over errors, e.g. HTTP timeout, and eventually a way to kill it of (from the client side). - - req := &egoscale.DeployVirtualMachine{ - Size: 10, - ServiceOfferingID: egoscale.MustParseUUID("..."), - TemplateID: egoscale.MustParseUUID("..."), - ZoneID: egoscale.MustParseUUID("..."), - } - vm := &egoscale.VirtualMachine{} - - fmt.Println("Deployment started") - cs.AsyncRequest(req, func(jobResult *egoscale.AsyncJobResult, err error) bool { - if err != nil { - // any kind of error - panic(err) - } - - // Keep waiting - if jobResult.JobStatus == egoscale.Pending { - fmt.Println("wait...") - return true - } - - // Unmarshal the response into the response struct - if err := jobResult.Response(vm); err != nil { - // JSON unmarshaling error - panic(err) - } - - // Stop waiting - return false - }) - - fmt.Printf("Virtual Machine ID: %s\n", vm.ID) - -Debugging and traces - -As this library is mostly an HTTP client, you can reuse all the existing tools around it. - - cs := egoscale.NewClient("https://api.exoscale.com/compute", "EXO...", "...") - // sets a logger on stderr - cs.Logger = log.New(os.Stderr, "prefix", log.LstdFlags) - // activates the HTTP traces - cs.TraceOn() - -Nota bene: when running the tests or the egoscale library via another tool, e.g. the exo cli, the environment variable EXOSCALE_TRACE=prefix does the above configuration for you. As a developer using egoscale as a library, you'll find it more convenient to plug your favorite io.Writer as it's a Logger. - - -APIs - -All the available APIs on the server and provided by the API Discovery plugin. - - cs := egoscale.NewClient("https://api.exoscale.com/compute", "EXO...", "...") - - resp, err := cs.Request(&egoscale.ListAPIs{}) - if err != nil { - panic(err) - } - - for _, api := range resp.(*egoscale.ListAPIsResponse).API { - fmt.Printf("%s %s\n", api.Name, api.Description) - } - // Output: - // listNetworks Lists all available networks - // ... - -Security Groups - -Security Groups provide a way to isolate traffic to VMs. Rules are added via the two Authorization commands. - - resp, err := cs.Request(&egoscale.CreateSecurityGroup{ - Name: "Load balancer", - Description: "Open HTTP/HTTPS ports from the outside world", - }) - securityGroup := resp.(*egoscale.SecurityGroup) - - resp, err = cs.Request(&egoscale.AuthorizeSecurityGroupIngress{ - Description: "SSH traffic", - SecurityGroupID: securityGroup.ID, - CidrList: []CIDR{ - *egoscale.MustParseCIDR("0.0.0.0/0"), - *egoscale.MustParseCIDR("::/0"), - }, - Protocol: "tcp", - StartPort: 22, - EndPort: 22, - }) - // The modified SecurityGroup is returned - securityGroup := resp.(*egoscale.SecurityGroup) - - // ... - err = client.BooleanRequest(&egoscale.DeleteSecurityGroup{ - ID: securityGroup.ID, - }) - // ... - -Security Group also implement the generic List, Get and Delete interfaces (Listable and Deletable). - - // List all Security Groups - sgs, _ := cs.List(&egoscale.SecurityGroup{}) - for _, s := range sgs { - sg := s.(egoscale.SecurityGroup) - // ... - } - - // Get a Security Group - sgQuery := &egoscale.SecurityGroup{Name: "Load balancer"} - resp, err := cs.Get(sgQuery); err != nil { - ... - } - sg := resp.(*egoscale.SecurityGroup) - - if err := cs.Delete(sg); err != nil { - ... - } - // The SecurityGroup has been deleted - -See: https://community.exoscale.com/documentation/compute/security-groups/ - -Zones - -A Zone corresponds to a Data Center. You may list them. Zone implements the Listable interface, which let you perform a list in two different ways. The first exposes the underlying request while the second one hide them and you only manipulate the structs of your interest. - - // Using ListZones request - req := &egoscale.ListZones{} - resp, err := client.Request(req) - if err != nil { - panic(err) - } - - for _, zone := range resp.(*egoscale.ListZonesResponse) { - ... - } - - // Using client.List - zone := &egoscale.Zone{} - zones, err := client.List(zone) - if err != nil { - panic(err) - } - - for _, z := range zones { - zone := z.(egoscale.Zone) - ... - } - -Elastic IPs - -An Elastic IP is a way to attach an IP address to many Virtual Machines. The API side of the story configures the external environment, like the routing. Some work is required within the machine to properly configure the interfaces. - -See: https://community.exoscale.com/documentation/compute/eip/ - -*/ -package egoscale diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/errorcode_string.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/errorcode_string.go deleted file mode 100644 index 1971125..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/errorcode_string.go +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by "stringer -type ErrorCode"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const ( - _ErrorCode_name_0 = "Unauthorized" - _ErrorCode_name_1 = "MethodNotAllowed" - _ErrorCode_name_2 = "UnsupportedActionError" - _ErrorCode_name_3 = "APILimitExceededMalformedParameterErrorParamError" - _ErrorCode_name_4 = "InternalErrorAccountErrorAccountResourceLimitErrorInsufficientCapacityErrorResourceUnavailableErrorResourceAllocationErrorResourceInUseErrorNetworkRuleConflictError" -) - -var ( - _ErrorCode_index_3 = [...]uint8{0, 16, 39, 49} - _ErrorCode_index_4 = [...]uint8{0, 13, 25, 50, 75, 99, 122, 140, 164} -) - -func (i ErrorCode) String() string { - switch { - case i == 401: - return _ErrorCode_name_0 - case i == 405: - return _ErrorCode_name_1 - case i == 422: - return _ErrorCode_name_2 - case 429 <= i && i <= 431: - i -= 429 - return _ErrorCode_name_3[_ErrorCode_index_3[i]:_ErrorCode_index_3[i+1]] - case 530 <= i && i <= 537: - i -= 530 - return _ErrorCode_name_4[_ErrorCode_index_4[i]:_ErrorCode_index_4[i+1]] - default: - return "ErrorCode(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/events.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/events.go deleted file mode 100644 index c6adbfd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/events.go +++ /dev/null @@ -1,76 +0,0 @@ -package egoscale - -// Event represents an event in the system -type Event struct { - Account string `json:"account,omitempty" doc:"the account name for the account that owns the object being acted on in the event (e.g. the owner of the virtual machine, ip address, or security group)"` - Created string `json:"created,omitempty" doc:"the date the event was created"` - Description string `json:"description,omitempty" doc:"a brief description of the event"` - ID *UUID `json:"id" doc:"the ID of the event"` - Level string `json:"level,omitempty" doc:"the event level (INFO, WARN, ERROR)"` - ParentID *UUID `json:"parentid,omitempty" doc:"whether the event is parented"` - State string `json:"state,omitempty" doc:"the state of the event"` - Type string `json:"type,omitempty" doc:"the type of the event (see event types)"` - UserName string `json:"username,omitempty" doc:"the name of the user who performed the action (can be different from the account if an admin is performing an action for a user, e.g. starting/stopping a user's virtual machine)"` -} - -// ListRequest builds the ListEvents request -func (event Event) ListRequest() (ListCommand, error) { - req := &ListEvents{ - ID: event.ID, - Level: event.Level, - Type: event.Type, - } - - return req, nil -} - -// EventType represent a type of event -type EventType struct { - Name string `json:"name,omitempty" doc:"Event Type"` -} - -// ListRequest builds the ListEventTypes request -func (EventType) ListRequest() (ListCommand, error) { - req := &ListEventTypes{} - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListEvents - -// ListEvents list the events -type ListEvents struct { - Duration int `json:"duration,omitempty" doc:"the duration of the event"` - EndDate string `json:"enddate,omitempty" doc:"the end date range of the list you want to retrieve (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\")"` - EntryTime int `json:"entrytime,omitempty" doc:"the time the event was entered"` - ID *UUID `json:"id,omitempty" doc:"the ID of the event"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Level string `json:"level,omitempty" doc:"the event level (INFO, WARN, ERROR)"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - StartDate string `json:"startdate,omitempty" doc:"the start date range of the list you want to retrieve (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\")"` - Type string `json:"type,omitempty" doc:"the event type (see event types)"` - _ bool `name:"listEvents" description:"A command to list events."` -} - -// ListEventsResponse represents a response of a list query -type ListEventsResponse struct { - Count int `json:"count"` - Event []Event `json:"event"` -} - -//go:generate go run generate/main.go -interface=Listable ListEventTypes - -// ListEventTypes list the event types -type ListEventTypes struct { - Page int `json:"page,omitempty"` // fake - PageSize int `json:"pagesize,omitempty"` // fake - _ bool `name:"listEventTypes" description:"List Event Types"` -} - -// ListEventTypesResponse represents a response of a list query -type ListEventTypesResponse struct { - Count int `json:"count"` - EventType []EventType `json:"eventtype"` - _ bool `name:"listEventTypes" description:"List Event Types"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/events_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/events_response.go deleted file mode 100644 index 2af10cf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/events_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListEvents) Response() interface{} { - return new(ListEventsResponse) -} - -// ListRequest returns itself -func (ls *ListEvents) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListEvents) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListEvents) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListEvents) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListEventsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListEventsResponse was expected, got %T", resp)) - return - } - - for i := range items.Event { - if !callback(&items.Event[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/eventtypes_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/eventtypes_response.go deleted file mode 100644 index 073d964..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/eventtypes_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListEventTypes) Response() interface{} { - return new(ListEventTypesResponse) -} - -// ListRequest returns itself -func (ls *ListEventTypes) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListEventTypes) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListEventTypes) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListEventTypes) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListEventTypesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListEventTypesResponse was expected, got %T", resp)) - return - } - - for i := range items.EventType { - if !callback(&items.EventType[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/instance_groups.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/instance_groups.go deleted file mode 100644 index 52bffba..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/instance_groups.go +++ /dev/null @@ -1,71 +0,0 @@ -package egoscale - -// InstanceGroup represents a group of VM -type InstanceGroup struct { - Account string `json:"account,omitempty" doc:"the account owning the instance group"` - Created string `json:"created,omitempty" doc:"time and date the instance group was created"` - ID *UUID `json:"id,omitempty" doc:"the id of the instance group"` - Name string `json:"name,omitempty" doc:"the name of the instance group"` -} - -// ListRequest builds the ListInstanceGroups request -func (ig InstanceGroup) ListRequest() (ListCommand, error) { - req := &ListInstanceGroups{ - ID: ig.ID, - Name: ig.Name, - } - - return req, nil -} - -// CreateInstanceGroup creates a VM group -type CreateInstanceGroup struct { - Name string `json:"name" doc:"the name of the instance group"` - _ bool `name:"createInstanceGroup" description:"Creates a vm group"` -} - -// Response returns the struct to unmarshal -func (CreateInstanceGroup) Response() interface{} { - return new(InstanceGroup) -} - -// UpdateInstanceGroup updates a VM group -type UpdateInstanceGroup struct { - ID *UUID `json:"id" doc:"Instance group ID"` - Name string `json:"name,omitempty" doc:"new instance group name"` - _ bool `name:"updateInstanceGroup" description:"Updates a vm group"` -} - -// Response returns the struct to unmarshal -func (UpdateInstanceGroup) Response() interface{} { - return new(InstanceGroup) -} - -// DeleteInstanceGroup deletes a VM group -type DeleteInstanceGroup struct { - ID *UUID `json:"id" doc:"the ID of the instance group"` - _ bool `name:"deleteInstanceGroup" description:"Deletes a vm group"` -} - -// Response returns the struct to unmarshal -func (DeleteInstanceGroup) Response() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListInstanceGroups - -// ListInstanceGroups lists VM groups -type ListInstanceGroups struct { - ID *UUID `json:"id,omitempty" doc:"List instance groups by ID"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"List instance groups by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listInstanceGroups" description:"Lists vm groups"` -} - -// ListInstanceGroupsResponse represents a list of instance groups -type ListInstanceGroupsResponse struct { - Count int `json:"count"` - InstanceGroup []InstanceGroup `json:"instancegroup"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/instancegroups_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/instancegroups_response.go deleted file mode 100644 index 90fc1db..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/instancegroups_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListInstanceGroups) Response() interface{} { - return new(ListInstanceGroupsResponse) -} - -// ListRequest returns itself -func (ls *ListInstanceGroups) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListInstanceGroups) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListInstanceGroups) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListInstanceGroups) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListInstanceGroupsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListInstanceGroupsResponse was expected, got %T", resp)) - return - } - - for i := range items.InstanceGroup { - if !callback(&items.InstanceGroup[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/isos.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/isos.go deleted file mode 100644 index d9a0ace..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/isos.go +++ /dev/null @@ -1,94 +0,0 @@ -package egoscale - -// ISO represents an attachable ISO disc -type ISO Template - -// ResourceType returns the type of the resource -func (ISO) ResourceType() string { - return "ISO" -} - -// ListRequest produces the ListIsos command. -func (iso ISO) ListRequest() (ListCommand, error) { - req := &ListISOs{ - ID: iso.ID, - Name: iso.Name, - ZoneID: iso.ZoneID, - } - if iso.Bootable { - *req.Bootable = true - } - if iso.IsFeatured { - req.IsoFilter = "featured" - } - if iso.IsPublic { - *req.IsPublic = true - } - if iso.IsReady { - *req.IsReady = true - } - - for i := range iso.Tags { - req.Tags = append(req.Tags, iso.Tags[i]) - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListISOs - -// ListISOs represents the list all available ISO files request -type ListISOs struct { - _ bool `name:"listIsos" description:"Lists all available ISO files."` - Bootable *bool `json:"bootable,omitempty" doc:"True if the ISO is bootable, false otherwise"` - ID *UUID `json:"id,omitempty" doc:"List ISO by id"` - IsoFilter string `json:"isofilter,omitempty" doc:"Possible values are \"featured\", \"self\", \"selfexecutable\",\"sharedexecutable\",\"executable\", and \"community\". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured. * all : all templates (only usable by admins)."` - IsPublic *bool `json:"ispublic,omitempty" doc:"True if the ISO is publicly available to all users, false otherwise."` - IsReady *bool `json:"isready,omitempty" doc:"True if this ISO is ready to be deployed"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"List all isos by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ShowRemoved *bool `json:"showremoved,omitempty" doc:"Show removed ISOs as well"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"The ID of the zone"` -} - -// ListISOsResponse represents a list of ISO files -type ListISOsResponse struct { - Count int `json:"count"` - ISO []ISO `json:"iso"` -} - -// AttachISO represents the request to attach an ISO to a virtual machine. -type AttachISO struct { - _ bool `name:"attachIso" description:"Attaches an ISO to a virtual machine."` - ID *UUID `json:"id" doc:"the ID of the ISO file"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"the ID of the virtual machine"` -} - -// Response returns the struct to unmarshal -func (AttachISO) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AttachISO) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// DetachISO represents the request to detach an ISO to a virtual machine. -type DetachISO struct { - _ bool `name:"detachIso" description:"Detaches any ISO file (if any) currently attached to a virtual machine."` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"The ID of the virtual machine"` -} - -// Response returns the struct to unmarshal -func (DetachISO) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DetachISO) AsyncResponse() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/isos_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/isos_response.go deleted file mode 100644 index 2faa45a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/isos_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListISOs) Response() interface{} { - return new(ListISOsResponse) -} - -// ListRequest returns itself -func (ls *ListISOs) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListISOs) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListISOs) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListISOs) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListISOsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListISOsResponse was expected, got %T", resp)) - return - } - - for i := range items.ISO { - if !callback(&items.ISO[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/jobstatustype_string.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/jobstatustype_string.go deleted file mode 100644 index 2985616..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/jobstatustype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type JobStatusType"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const _JobStatusType_name = "PendingSuccessFailure" - -var _JobStatusType_index = [...]uint8{0, 7, 14, 21} - -func (i JobStatusType) String() string { - if i < 0 || i >= JobStatusType(len(_JobStatusType_index)-1) { - return "JobStatusType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _JobStatusType_name[_JobStatusType_index[i]:_JobStatusType_index[i+1]] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/macaddress.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/macaddress.go deleted file mode 100644 index 3c1dcae..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/macaddress.go +++ /dev/null @@ -1,63 +0,0 @@ -package egoscale - -import ( - "encoding/json" - "fmt" - "net" -) - -// MACAddress is a nicely JSON serializable net.HardwareAddr -type MACAddress net.HardwareAddr - -// String returns the MAC address in standard format -func (mac MACAddress) String() string { - return (net.HardwareAddr)(mac).String() -} - -// MAC48 builds a MAC-48 MACAddress -func MAC48(a, b, c, d, e, f byte) MACAddress { - m := make(MACAddress, 6) - m[0] = a - m[1] = b - m[2] = c - m[3] = d - m[4] = e - m[5] = f - return m -} - -// UnmarshalJSON unmarshals the raw JSON into the MAC address -func (mac *MACAddress) UnmarshalJSON(b []byte) error { - var addr string - if err := json.Unmarshal(b, &addr); err != nil { - return err - } - hw, err := ParseMAC(addr) - if err != nil { - return err - } - - *mac = make(MACAddress, 6) - copy(*mac, hw) - return nil -} - -// MarshalJSON converts the MAC Address to a string representation -func (mac MACAddress) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("%q", mac.String())), nil -} - -// ParseMAC converts a string into a MACAddress -func ParseMAC(s string) (MACAddress, error) { - hw, err := net.ParseMAC(s) - return (MACAddress)(hw), err -} - -// MustParseMAC acts like ParseMAC but panics if in case of an error -func MustParseMAC(s string) MACAddress { - mac, err := ParseMAC(s) - if err != nil { - panic(err) - } - return mac -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/network_offerings.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/network_offerings.go deleted file mode 100644 index 989d587..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/network_offerings.go +++ /dev/null @@ -1,91 +0,0 @@ -package egoscale - -// NetworkOffering corresponds to the Compute Offerings -type NetworkOffering struct { - Availability string `json:"availability,omitempty" doc:"availability of the network offering"` - ConserveMode bool `json:"conservemode,omitempty" doc:"true if network offering is ip conserve mode enabled"` - Created string `json:"created,omitempty" doc:"the date this network offering was created"` - Details map[string]string `json:"details,omitempty" doc:"additional key/value details tied with network offering"` - DisplayText string `json:"displaytext,omitempty" doc:"an alternate display text of the network offering."` - EgressDefaultPolicy bool `json:"egressdefaultpolicy,omitempty" doc:"true if guest network default egress policy is allow; false if default egress policy is deny"` - GuestIPType string `json:"guestiptype,omitempty" doc:"guest type of the network offering, can be Shared or Isolated"` - ID *UUID `json:"id,omitempty" doc:"the id of the network offering"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if network offering is default, false otherwise"` - IsPersistent bool `json:"ispersistent,omitempty" doc:"true if network offering supports persistent networks, false otherwise"` - MaxConnections int `json:"maxconnections,omitempty" doc:"maximum number of concurrents connections to be handled by lb"` - Name string `json:"name,omitempty" doc:"the name of the network offering"` - NetworkRate int `json:"networkrate,omitempty" doc:"data transfer rate in megabits per second allowed."` - Service []Service `json:"service,omitempty" doc:"the list of supported services"` - ServiceOfferingID *UUID `json:"serviceofferingid,omitempty" doc:"the ID of the service offering used by virtual router provider"` - SpecifyIPRanges bool `json:"specifyipranges,omitempty" doc:"true if network offering supports specifying ip ranges, false otherwise"` - SpecifyVlan bool `json:"specifyvlan,omitempty" doc:"true if network offering supports vlans, false otherwise"` - State string `json:"state,omitempty" doc:"state of the network offering. Can be Disabled/Enabled/Inactive"` - SupportsStrechedL2Subnet bool `json:"supportsstrechedl2subnet,omitempty" doc:"true if network offering supports network that span multiple zones"` - Tags string `json:"tags,omitempty" doc:"the tags for the network offering"` - TrafficType string `json:"traffictype,omitempty" doc:"the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage."` -} - -// ListRequest builds the ListNetworkOfferings request -// -// This doesn't take into account the IsDefault flag as the default value is true. -func (no NetworkOffering) ListRequest() (ListCommand, error) { - req := &ListNetworkOfferings{ - Availability: no.Availability, - ID: no.ID, - Name: no.Name, - State: no.State, - TrafficType: no.TrafficType, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListNetworkOfferings - -// ListNetworkOfferings represents a query for network offerings -type ListNetworkOfferings struct { - Availability string `json:"availability,omitempty" doc:"the availability of network offering. Default value is Required"` - DisplayText string `json:"displaytext,omitempty" doc:"list network offerings by display text"` - GuestIPType string `json:"guestiptype,omitempty" doc:"list network offerings by guest type: Shared or Isolated"` - ID *UUID `json:"id,omitempty" doc:"list network offerings by id"` - IsDefault *bool `json:"isdefault,omitempty" doc:"true if need to list only default network offerings. Default value is false"` - IsTagged *bool `json:"istagged,omitempty" doc:"true if offering has tags specified"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"list network offerings by name"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to."` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - SourceNATSupported *bool `json:"sourcenatsupported,omitempty" doc:"true if need to list only netwok offerings where source nat is supported, false otherwise"` - SpecifyIPRanges *bool `json:"specifyipranges,omitempty" doc:"true if need to list only network offerings which support specifying ip ranges"` - SpecifyVlan *bool `json:"specifyvlan,omitempty" doc:"the tags for the network offering."` - State string `json:"state,omitempty" doc:"list network offerings by state"` - SupportedServices []Service `json:"supportedservices,omitempty" doc:"list network offerings supporting certain services"` - Tags string `json:"tags,omitempty" doc:"list network offerings by tags"` - TrafficType string `json:"traffictype,omitempty" doc:"list by traffic type"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"list network offerings available for network creation in specific zone"` - _ bool `name:"listNetworkOfferings" description:"Lists all available network offerings."` -} - -// ListNetworkOfferingsResponse represents a list of service offerings -type ListNetworkOfferingsResponse struct { - Count int `json:"count"` - NetworkOffering []NetworkOffering `json:"networkoffering"` -} - -// UpdateNetworkOffering represents a modification of a network offering -type UpdateNetworkOffering struct { - Availability string `json:"availability,omitempty" doc:"the availability of network offering. Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering"` - DisplayText string `json:"displaytext,omitempty" doc:"the display text of the network offering"` - ID *UUID `json:"id,omitempty" doc:"the id of the network offering"` - KeepAliveEnabled *bool `json:"keepaliveenabled,omitempty" doc:"if true keepalive will be turned on in the loadbalancer. At the time of writing this has only an effect on haproxy; the mode http and httpclose options are unset in the haproxy conf file."` - MaxConnections int `json:"maxconnections,omitempty" doc:"maximum number of concurrent connections supported by the network offering"` - Name string `json:"name,omitempty" doc:"the name of the network offering"` - SortKey int `json:"sortkey,omitempty" doc:"sort key of the network offering, integer"` - State string `json:"state,omitempty" doc:"update state for the network offering"` - _ bool `name:"updateNetworkOffering" description:"Updates a network offering."` -} - -// Response returns the struct to unmarshal -func (UpdateNetworkOffering) Response() interface{} { - return new(NetworkOffering) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networkofferings_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networkofferings_response.go deleted file mode 100644 index 656de72..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networkofferings_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListNetworkOfferings) Response() interface{} { - return new(ListNetworkOfferingsResponse) -} - -// ListRequest returns itself -func (ls *ListNetworkOfferings) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListNetworkOfferings) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListNetworkOfferings) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListNetworkOfferings) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListNetworkOfferingsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListNetworkOfferingsResponse was expected, got %T", resp)) - return - } - - for i := range items.NetworkOffering { - if !callback(&items.NetworkOffering[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networks.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networks.go deleted file mode 100644 index 4d6ce12..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networks.go +++ /dev/null @@ -1,229 +0,0 @@ -package egoscale - -import ( - "net" - "net/url" -) - -// Network represents a network -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html -type Network struct { - Account string `json:"account,omitempty" doc:"the owner of the network"` - AccountID *UUID `json:"accountid,omitempty" doc:"the owner ID of the network"` - BroadcastDomainType string `json:"broadcastdomaintype,omitempty" doc:"Broadcast domain type of the network"` - BroadcastURI string `json:"broadcasturi,omitempty" doc:"broadcast uri of the network."` - CanUseForDeploy bool `json:"canusefordeploy,omitempty" doc:"list networks available for vm deployment"` - CIDR *CIDR `json:"cidr,omitempty" doc:"Cloudstack managed address space, all CloudStack managed VMs get IP address from CIDR"` - DisplayText string `json:"displaytext,omitempty" doc:"the displaytext of the network"` - DNS1 net.IP `json:"dns1,omitempty" doc:"the first DNS for the network"` - DNS2 net.IP `json:"dns2,omitempty" doc:"the second DNS for the network"` - EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. Required for managed networks."` - Gateway net.IP `json:"gateway,omitempty" doc:"the network's gateway"` - ID *UUID `json:"id,omitempty" doc:"the id of the network"` - IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the cidr of IPv6 network"` - IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of IPv6 network"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if network is default, false otherwise"` - IsPersistent bool `json:"ispersistent,omitempty" doc:"list networks that are persistent"` - IsSystem bool `json:"issystem,omitempty" doc:"true if network is system, false otherwise"` - Name string `json:"name,omitempty" doc:"the name of the network"` - Netmask net.IP `json:"netmask,omitempty" doc:"the network's netmask"` - NetworkCIDR *CIDR `json:"networkcidr,omitempty" doc:"the network CIDR of the guest network configured with IP reservation. It is the summation of CIDR and RESERVED_IP_RANGE"` - NetworkDomain string `json:"networkdomain,omitempty" doc:"the network domain"` - NetworkOfferingAvailability string `json:"networkofferingavailability,omitempty" doc:"availability of the network offering the network is created from"` - NetworkOfferingConserveMode bool `json:"networkofferingconservemode,omitempty" doc:"true if network offering is ip conserve mode enabled"` - NetworkOfferingDisplayText string `json:"networkofferingdisplaytext,omitempty" doc:"display text of the network offering the network is created from"` - NetworkOfferingID *UUID `json:"networkofferingid,omitempty" doc:"network offering id the network is created from"` - NetworkOfferingName string `json:"networkofferingname,omitempty" doc:"name of the network offering the network is created from"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"the physical network id"` - Related string `json:"related,omitempty" doc:"related to what other network configuration"` - ReservedIPRange string `json:"reservediprange,omitempty" doc:"the network's IP range not to be used by CloudStack guest VMs and can be used for non CloudStack purposes"` - RestartRequired bool `json:"restartrequired,omitempty" doc:"true network requires restart"` - Service []Service `json:"service,omitempty" doc:"the list of services"` - SpecifyIPRanges bool `json:"specifyipranges,omitempty" doc:"true if network supports specifying ip ranges, false otherwise"` - StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range. Required for managed networks."` - State string `json:"state,omitempty" doc:"state of the network"` - StrechedL2Subnet bool `json:"strechedl2subnet,omitempty" doc:"true if network can span multiple zones"` - SubdomainAccess bool `json:"subdomainaccess,omitempty" doc:"true if users from subdomains can access the domain level network"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with network"` - TrafficType string `json:"traffictype,omitempty" doc:"the traffic type of the network"` - Type string `json:"type,omitempty" doc:"the type of the network"` - Vlan string `json:"vlan,omitemtpy" doc:"The vlan of the network. This parameter is visible to ROOT admins only"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"zone id of the network"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the zone the network belongs to"` - ZonesNetworkSpans []Zone `json:"zonesnetworkspans,omitempty" doc:"If a network is enabled for 'streched l2 subnet' then represents zones on which network currently spans"` -} - -// ListRequest builds the ListNetworks request -func (network Network) ListRequest() (ListCommand, error) { - //TODO add tags support - req := &ListNetworks{ - ID: network.ID, - Keyword: network.Name, // this is a hack as listNetworks doesn't support to search by name. - PhysicalNetworkID: network.PhysicalNetworkID, - TrafficType: network.TrafficType, - Type: network.Type, - ZoneID: network.ZoneID, - } - - if network.CanUseForDeploy { - req.CanUseForDeploy = &network.CanUseForDeploy - } - if network.RestartRequired { - req.RestartRequired = &network.RestartRequired - } - - return req, nil -} - -// ResourceType returns the type of the resource -func (Network) ResourceType() string { - return "Network" -} - -// Service is a feature of a network -type Service struct { - Capability []ServiceCapability `json:"capability,omitempty"` - Name string `json:"name"` - Provider []ServiceProvider `json:"provider,omitempty"` -} - -// ServiceCapability represents optional capability of a service -type ServiceCapability struct { - CanChooseServiceCapability bool `json:"canchooseservicecapability"` - Name string `json:"name"` - Value string `json:"value"` -} - -// ServiceProvider represents the provider of the service -type ServiceProvider struct { - CanEnableIndividualService bool `json:"canenableindividualservice"` - DestinationPhysicalNetworkID *UUID `json:"destinationphysicalnetworkid"` - ID *UUID `json:"id"` - Name string `json:"name"` - PhysicalNetworkID *UUID `json:"physicalnetworkid"` - ServiceList []string `json:"servicelist,omitempty"` -} - -// CreateNetwork creates a network -type CreateNetwork struct { - DisplayText string `json:"displaytext,omitempty" doc:"the display text of the network"` // This field is required but might be empty - EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. Required for managed networks."` - EndIpv6 net.IP `json:"endipv6,omitempty" doc:"the ending IPv6 address in the IPv6 network range"` - Gateway net.IP `json:"gateway,omitempty" doc:"the gateway of the network. Required for Shared networks and Isolated networks when it belongs to VPC"` - IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the CIDR of IPv6 network, must be at least /64"` - IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of the IPv6 network. Required for Shared networks and Isolated networks when it belongs to VPC"` - IsolatedPVlan string `json:"isolatedpvlan,omitempty" doc:"the isolated private vlan for this network"` - Name string `json:"name,omitempty" doc:"the name of the network"` // This field is required but might be empty - Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the network. Required for managed networks."` - NetworkDomain string `json:"networkdomain,omitempty" doc:"network domain"` - NetworkOfferingID *UUID `json:"networkofferingid" doc:"the network offering id"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"the Physical Network ID the network belongs to"` - StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range. Required for managed networks."` - StartIpv6 net.IP `json:"startipv6,omitempty" doc:"the beginning IPv6 address in the IPv6 network range"` - Vlan string `json:"vlan,omitempty" doc:"the ID or VID of the network"` - ZoneID *UUID `json:"zoneid" doc:"the Zone ID for the network"` - _ bool `name:"createNetwork" description:"Creates a network"` -} - -// Response returns the struct to unmarshal -func (CreateNetwork) Response() interface{} { - return new(Network) -} - -func (req CreateNetwork) onBeforeSend(params url.Values) error { - // Those fields are required but might be empty - if req.Name == "" { - params.Set("name", "") - } - if req.DisplayText == "" { - params.Set("displaytext", "") - } - return nil -} - -// UpdateNetwork (Async) updates a network -type UpdateNetwork struct { - _ bool `name:"updateNetwork" description:"Updates a network"` - ChangeCIDR *bool `json:"changecidr,omitempty" doc:"Force update even if cidr type is different"` - DisplayText string `json:"displaytext,omitempty" doc:"the new display text for the network"` - EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. Required for managed networks."` - GuestVMCIDR *CIDR `json:"guestvmcidr,omitempty" doc:"CIDR for Guest VMs,Cloudstack allocates IPs to Guest VMs only from this CIDR"` - ID *UUID `json:"id" doc:"the ID of the network"` - Name string `json:"name,omitempty" doc:"the new name for the network"` - Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the network. Required for managed networks."` - NetworkDomain string `json:"networkdomain,omitempty" doc:"network domain"` - NetworkOfferingID *UUID `json:"networkofferingid,omitempty" doc:"network offering ID"` - StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range. Required for managed networks."` -} - -// Response returns the struct to unmarshal -func (UpdateNetwork) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateNetwork) AsyncResponse() interface{} { - return new(Network) -} - -// RestartNetwork (Async) updates a network -type RestartNetwork struct { - ID *UUID `json:"id" doc:"The id of the network to restart."` - Cleanup *bool `json:"cleanup,omitempty" doc:"If cleanup old network elements"` - _ bool `name:"restartNetwork" description:"Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules"` -} - -// Response returns the struct to unmarshal -func (RestartNetwork) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RestartNetwork) AsyncResponse() interface{} { - return new(Network) -} - -// DeleteNetwork deletes a network -type DeleteNetwork struct { - ID *UUID `json:"id" doc:"the ID of the network"` - Forced *bool `json:"forced,omitempty" doc:"Force delete a network. Network will be marked as 'Destroy' even when commands to shutdown and cleanup to the backend fails."` - _ bool `name:"deleteNetwork" description:"Deletes a network"` -} - -// Response returns the struct to unmarshal -func (DeleteNetwork) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteNetwork) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListNetworks - -// ListNetworks represents a query to a network -type ListNetworks struct { - CanUseForDeploy *bool `json:"canusefordeploy,omitempty" doc:"List networks available for vm deployment"` - ID *UUID `json:"id,omitempty" doc:"List networks by id"` - IsSystem *bool `json:"issystem,omitempty" doc:"true If network is system, false otherwise"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"List networks by physical network id"` - RestartRequired *bool `json:"restartrequired,omitempty" doc:"List networks by restartRequired"` - SpecifyIPRanges *bool `json:"specifyipranges,omitempty" doc:"True if need to list only networks which support specifying ip ranges"` - SupportedServices []Service `json:"supportedservices,omitempty" doc:"List networks supporting certain services"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - TrafficType string `json:"traffictype,omitempty" doc:"Type of the traffic"` - Type string `json:"type,omitempty" doc:"The type of the network. Supported values are: Isolated and Shared"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"The Zone ID of the network"` - _ bool `name:"listNetworks" description:"Lists all available networks."` -} - -// ListNetworksResponse represents the list of networks -type ListNetworksResponse struct { - Count int `json:"count"` - Network []Network `json:"network"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networks_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networks_response.go deleted file mode 100644 index 0588906..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/networks_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListNetworks) Response() interface{} { - return new(ListNetworksResponse) -} - -// ListRequest returns itself -func (ls *ListNetworks) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListNetworks) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListNetworks) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListNetworks) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListNetworksResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListNetworksResponse was expected, got %T", resp)) - return - } - - for i := range items.Network { - if !callback(&items.Network[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/nics.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/nics.go deleted file mode 100644 index 1086311..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/nics.go +++ /dev/null @@ -1,120 +0,0 @@ -package egoscale - -import ( - "net" -) - -// Nic represents a Network Interface Controller (NIC) -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html#configuring-multiple-ip-addresses-on-a-single-nic -type Nic struct { - BroadcastURI string `json:"broadcasturi,omitempty" doc:"the broadcast uri of the nic"` - DeviceID *UUID `json:"deviceid,omitempty" doc:"device id for the network when plugged into the virtual machine"` - Gateway net.IP `json:"gateway,omitempty" doc:"the gateway of the nic"` - ID *UUID `json:"id,omitempty" doc:"the ID of the nic"` - IP6Address net.IP `json:"ip6address,omitempty" doc:"the IPv6 address of network"` - IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the cidr of IPv6 network"` - IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of IPv6 network"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"the ip address of the nic"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if nic is default, false otherwise"` - IsolationURI string `json:"isolationuri,omitempty" doc:"the isolation uri of the nic"` - MACAddress MACAddress `json:"macaddress,omitempty" doc:"true if nic is default, false otherwise"` - Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the nic"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the corresponding network"` - NetworkName string `json:"networkname,omitempty" doc:"the name of the corresponding network"` - ReverseDNS []ReverseDNS `json:"reversedns,omitempty" doc:"the list of PTR record(s) associated with the virtual machine"` - SecondaryIP []NicSecondaryIP `json:"secondaryip,omitempty" doc:"the Secondary ipv4 addr of nic"` - TrafficType string `json:"traffictype,omitempty" doc:"the traffic type of the nic"` - Type string `json:"type,omitempty" doc:"the type of the nic"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"Id of the vm to which the nic belongs"` -} - -// ListRequest build a ListNics request from the given Nic -func (nic Nic) ListRequest() (ListCommand, error) { - req := &ListNics{ - VirtualMachineID: nic.VirtualMachineID, - NicID: nic.ID, - NetworkID: nic.NetworkID, - } - - return req, nil -} - -// NicSecondaryIP represents a link between NicID and IPAddress -type NicSecondaryIP struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the secondary private IP addr"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Secondary IP address"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the network"` - NicID *UUID `json:"nicid,omitempty" doc:"the ID of the nic"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the ID of the vm"` -} - -//go:generate go run generate/main.go -interface=Listable ListNics - -// ListNics represents the NIC search -type ListNics struct { - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - NetworkID *UUID `json:"networkid,omitempty" doc:"list nic of the specific vm's network"` - NicID *UUID `json:"nicid,omitempty" doc:"the ID of the nic to to list IPs"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the ID of the vm"` - _ bool `name:"listNics" description:"list the vm nics IP to NIC"` -} - -// ListNicsResponse represents a list of templates -type ListNicsResponse struct { - Count int `json:"count"` - Nic []Nic `json:"nic"` -} - -// AddIPToNic (Async) represents the assignation of a secondary IP -type AddIPToNic struct { - NicID *UUID `json:"nicid" doc:"the ID of the nic to which you want to assign private IP"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Secondary IP Address"` - _ bool `name:"addIpToNic" description:"Assigns secondary IP to NIC"` -} - -// Response returns the struct to unmarshal -func (AddIPToNic) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AddIPToNic) AsyncResponse() interface{} { - return new(NicSecondaryIP) -} - -// RemoveIPFromNic (Async) represents a deletion request -type RemoveIPFromNic struct { - ID *UUID `json:"id" doc:"the ID of the secondary ip address to nic"` - _ bool `name:"removeIpFromNic" description:"Removes secondary IP from the NIC."` -} - -// Response returns the struct to unmarshal -func (RemoveIPFromNic) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RemoveIPFromNic) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// ActivateIP6 (Async) activates the IP6 on the given NIC -// -// Exoscale specific API: https://community.exoscale.ch/api/compute/#activateip6_GET -type ActivateIP6 struct { - NicID *UUID `json:"nicid" doc:"the ID of the nic to which you want to assign the IPv6"` - _ bool `name:"activateIp6" description:"Activate the IPv6 on the VM's nic"` -} - -// Response returns the struct to unmarshal -func (ActivateIP6) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ActivateIP6) AsyncResponse() interface{} { - return new(Nic) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/nics_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/nics_response.go deleted file mode 100644 index dcf9609..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/nics_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListNics) Response() interface{} { - return new(ListNicsResponse) -} - -// ListRequest returns itself -func (ls *ListNics) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListNics) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListNics) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListNics) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListNicsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListNicsResponse was expected, got %T", resp)) - return - } - - for i := range items.Nic { - if !callback(&items.Nic[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/oscategories_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/oscategories_response.go deleted file mode 100644 index 985f875..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/oscategories_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListOSCategories) Response() interface{} { - return new(ListOSCategoriesResponse) -} - -// ListRequest returns itself -func (ls *ListOSCategories) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListOSCategories) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListOSCategories) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListOSCategories) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListOSCategoriesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListOSCategoriesResponse was expected, got %T", resp)) - return - } - - for i := range items.OSCategory { - if !callback(&items.OSCategory[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/publicipaddresses_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/publicipaddresses_response.go deleted file mode 100644 index 2ee92bd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/publicipaddresses_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListPublicIPAddresses) Response() interface{} { - return new(ListPublicIPAddressesResponse) -} - -// ListRequest returns itself -func (ls *ListPublicIPAddresses) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListPublicIPAddresses) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListPublicIPAddresses) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListPublicIPAddresses) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListPublicIPAddressesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListPublicIPAddressesResponse was expected, got %T", resp)) - return - } - - for i := range items.PublicIPAddress { - if !callback(&items.PublicIPAddress[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/record_string.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/record_string.go deleted file mode 100644 index b84303b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/record_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type=Record"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const _Record_name = "AAAAAALIASCNAMEHINFOMXNAPTRNSPOOLSPFSRVSSHFPTXTURL" - -var _Record_index = [...]uint8{0, 1, 5, 10, 15, 20, 22, 27, 29, 33, 36, 39, 44, 47, 50} - -func (i Record) String() string { - if i < 0 || i >= Record(len(_Record_index)-1) { - return "Record(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Record_name[_Record_index[i]:_Record_index[i+1]] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/request.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/request.go deleted file mode 100644 index f029714..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/request.go +++ /dev/null @@ -1,405 +0,0 @@ -package egoscale - -import ( - "bytes" - "context" - "crypto/hmac" - "crypto/sha1" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" -) - -// Error formats a CloudStack error into a standard error -func (e ErrorResponse) Error() string { - return fmt.Sprintf("API error %s %d (%s %d): %s", e.ErrorCode, e.ErrorCode, e.CSErrorCode, e.CSErrorCode, e.ErrorText) -} - -// Error formats a CloudStack job response into a standard error -func (e BooleanResponse) Error() error { - if !e.Success { - return fmt.Errorf("API error: %s", e.DisplayText) - } - - return nil -} - -func responseKey(key string) (string, bool) { - // XXX: addIpToNic, activateIp6, restorevmresponse are kind of special - var responseKeys = map[string]string{ - "addiptonicresponse": "addiptovmnicresponse", - "activateip6response": "activateip6nicresponse", - "restorevirtualmachineresponse": "restorevmresponse", - "updatevmaffinitygroupresponse": "updatevirtualmachineresponse", - } - - k, ok := responseKeys[key] - return k, ok -} - -func (client *Client) parseResponse(resp *http.Response, apiName string) (json.RawMessage, error) { - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - m := map[string]json.RawMessage{} - if err := json.Unmarshal(b, &m); err != nil { - return nil, err - } - - key := fmt.Sprintf("%sresponse", strings.ToLower(apiName)) - response, ok := m[key] - if !ok { - if resp.StatusCode >= 400 { - response, ok = m["errorresponse"] - } - - if !ok { - // try again with the special keys - value, ok := responseKey(key) - if ok { - key = value - } - - response, ok = m[key] - - if !ok { - return nil, fmt.Errorf("malformed JSON response %d, %q was expected.\n%s", resp.StatusCode, key, b) - } - } - } - - if resp.StatusCode >= 400 { - errorResponse := new(ErrorResponse) - if e := json.Unmarshal(response, errorResponse); e != nil && errorResponse.ErrorCode <= 0 { - return nil, fmt.Errorf("%d %s", resp.StatusCode, b) - } - return nil, errorResponse - } - - n := map[string]json.RawMessage{} - if err := json.Unmarshal(response, &n); err != nil { - return nil, err - } - - // list response may contain only one key - if len(n) > 1 || strings.HasPrefix(key, "list") { - return response, nil - } - - if len(n) == 1 { - for k := range n { - // boolean response and asyncjob result may also contain - // only one key - if k == "success" || k == "jobid" { - return response, nil - } - return n[k], nil - } - } - - return response, nil -} - -// asyncRequest perform an asynchronous job with a context -func (client *Client) asyncRequest(ctx context.Context, asyncCommand AsyncCommand) (interface{}, error) { - var err error - - resp := asyncCommand.AsyncResponse() - client.AsyncRequestWithContext( - ctx, - asyncCommand, - func(j *AsyncJobResult, e error) bool { - if e != nil { - err = e - return false - } - if j.JobStatus != Pending { - if r := j.Result(resp); r != nil { - err = r - } - return false - } - return true - }, - ) - return resp, err -} - -// SyncRequestWithContext performs a sync request with a context -func (client *Client) SyncRequestWithContext(ctx context.Context, command Command) (interface{}, error) { - body, err := client.request(ctx, command) - if err != nil { - return nil, err - } - - response := command.Response() - b, ok := response.(*BooleanResponse) - if ok { - m := make(map[string]interface{}) - if errUnmarshal := json.Unmarshal(body, &m); errUnmarshal != nil { - return nil, errUnmarshal - } - - b.DisplayText, _ = m["displaytext"].(string) - - if success, okSuccess := m["success"].(string); okSuccess { - b.Success = success == "true" - } - - if success, okSuccess := m["success"].(bool); okSuccess { - b.Success = success - } - - return b, nil - } - - if err := json.Unmarshal(body, response); err != nil { - errResponse := new(ErrorResponse) - if e := json.Unmarshal(body, errResponse); e == nil && errResponse.ErrorCode > 0 { - return errResponse, nil - } - return nil, err - } - - return response, nil -} - -// BooleanRequest performs the given boolean command -func (client *Client) BooleanRequest(command Command) error { - resp, err := client.Request(command) - if err != nil { - return err - } - - if b, ok := resp.(*BooleanResponse); ok { - return b.Error() - } - - panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp)) -} - -// BooleanRequestWithContext performs the given boolean command -func (client *Client) BooleanRequestWithContext(ctx context.Context, command Command) error { - resp, err := client.RequestWithContext(ctx, command) - if err != nil { - return err - } - - if b, ok := resp.(*BooleanResponse); ok { - return b.Error() - } - - panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp)) -} - -// Request performs the given command -func (client *Client) Request(command Command) (interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.RequestWithContext(ctx, command) -} - -// RequestWithContext preforms a command with a context -func (client *Client) RequestWithContext(ctx context.Context, command Command) (interface{}, error) { - switch c := command.(type) { - case AsyncCommand: - return client.asyncRequest(ctx, c) - default: - return client.SyncRequestWithContext(ctx, command) - } -} - -// SyncRequest performs the command as is -func (client *Client) SyncRequest(command Command) (interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.SyncRequestWithContext(ctx, command) -} - -// AsyncRequest performs the given command -func (client *Client) AsyncRequest(asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - client.AsyncRequestWithContext(ctx, asyncCommand, callback) -} - -// AsyncRequestWithContext preforms a request with a context -func (client *Client) AsyncRequestWithContext(ctx context.Context, asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) { - result, err := client.SyncRequestWithContext(ctx, asyncCommand) - if err != nil { - if !callback(nil, err) { - return - } - } - - jobResult, ok := result.(*AsyncJobResult) - if !ok { - callback(nil, fmt.Errorf("wrong type, AsyncJobResult was expected instead of %T", result)) - } - - // Successful response - if jobResult.JobID == nil || jobResult.JobStatus != Pending { - callback(jobResult, nil) - // without a JobID, the next requests will only fail - return - } - - for iteration := 0; ; iteration++ { - time.Sleep(client.RetryStrategy(int64(iteration))) - - req := &QueryAsyncJobResult{JobID: jobResult.JobID} - resp, err := client.SyncRequestWithContext(ctx, req) - if err != nil && !callback(nil, err) { - return - } - - result, ok := resp.(*AsyncJobResult) - if !ok { - if !callback(nil, fmt.Errorf("wrong type. AsyncJobResult expected, got %T", resp)) { - return - } - } - - if !callback(result, nil) { - return - } - } -} - -// Payload builds the HTTP request params from the given command -func (client *Client) Payload(command Command) (url.Values, error) { - params, err := prepareValues("", command) - if err != nil { - return nil, err - } - if hookReq, ok := command.(onBeforeHook); ok { - if err := hookReq.onBeforeSend(params); err != nil { - return params, err - } - } - params.Set("apikey", client.APIKey) - params.Set("command", client.APIName(command)) - params.Set("response", "json") - - if params.Get("expires") == "" && client.Expiration >= 0 { - params.Set("signatureversion", "3") - params.Set("expires", time.Now().Add(client.Expiration).Local().Format("2006-01-02T15:04:05-0700")) - } - - return params, nil -} - -// Sign signs the HTTP request and returns the signature as as base64 encoding -func (client *Client) Sign(params url.Values) (string, error) { - query := encodeValues(params) - query = strings.ToLower(query) - mac := hmac.New(sha1.New, []byte(client.apiSecret)) - _, err := mac.Write([]byte(query)) - if err != nil { - return "", err - } - - signature := base64.StdEncoding.EncodeToString(mac.Sum(nil)) - return signature, nil -} - -// request makes a Request while being close to the metal -func (client *Client) request(ctx context.Context, command Command) (json.RawMessage, error) { - params, err := client.Payload(command) - if err != nil { - return nil, err - } - signature, err := client.Sign(params) - if err != nil { - return nil, err - } - params.Add("signature", signature) - - method := "GET" - query := params.Encode() - url := fmt.Sprintf("%s?%s", client.Endpoint, query) - - var body io.Reader - // respect Internet Explorer limit of 2048 - if len(url) > 2048 { - url = client.Endpoint - method = "POST" - body = strings.NewReader(query) - } - - request, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - request = request.WithContext(ctx) - request.Header.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version)) - - if method == "POST" { - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - request.Header.Add("Content-Length", strconv.Itoa(len(query))) - } - - resp, err := client.HTTPClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() // nolint: errcheck - - contentType := resp.Header.Get("content-type") - - if !strings.Contains(contentType, "application/json") { - return nil, fmt.Errorf(`body content-type response expected "application/json", got %q`, contentType) - } - - text, err := client.parseResponse(resp, client.APIName(command)) - if err != nil { - return nil, err - } - - return text, nil -} - -func encodeValues(params url.Values) string { - // This code is borrowed from net/url/url.go - // The way it's encoded by net/url doesn't match - // how CloudStack works to determine the signature. - // - // CloudStack only encodes the values of the query parameters - // and furthermore doesn't use '+' for whitespaces. Therefore - // after encoding the values all '+' are replaced with '%20'. - if params == nil { - return "" - } - - var buf bytes.Buffer - keys := make([]string, 0, len(params)) - for k := range params { - keys = append(keys, k) - } - - sort.Strings(keys) - for _, k := range keys { - prefix := k + "=" - for _, v := range params[k] { - if buf.Len() > 0 { - buf.WriteByte('&') - } - buf.WriteString(prefix) - buf.WriteString(csEncode(v)) - } - } - return buf.String() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/request_type.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/request_type.go deleted file mode 100644 index 7394e1a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/request_type.go +++ /dev/null @@ -1,184 +0,0 @@ -package egoscale - -import ( - "net/url" -) - -// Command represents a generic request -type Command interface { - Response() interface{} -} - -// AsyncCommand represents a async request -type AsyncCommand interface { - Command - AsyncResponse() interface{} -} - -// ListCommand represents a listing request -type ListCommand interface { - Listable - Command - // SetPage defines the current pages - SetPage(int) - // SetPageSize defines the size of the page - SetPageSize(int) - // Each reads the data from the response and feeds channels, and returns true if we are on the last page - Each(interface{}, IterateItemFunc) -} - -// onBeforeHook represents an action to be done on the params before sending them -// -// This little took helps with issue of relying on JSON serialization logic only. -// `omitempty` may make sense in some cases but not all the time. -type onBeforeHook interface { - onBeforeSend(params url.Values) error -} - -// CommandInfo represents the meta data related to a Command -type CommandInfo struct { - Name string - Description string - RootOnly bool -} - -// JobStatusType represents the status of a Job -type JobStatusType int - -//go:generate stringer -type JobStatusType -const ( - // Pending represents a job in progress - Pending JobStatusType = iota - // Success represents a successfully completed job - Success - // Failure represents a job that has failed to complete - Failure -) - -// ErrorCode represents the CloudStack ApiErrorCode enum -// -// See: https://github.com/apache/cloudstack/blob/master/api/src/main/java/org/apache/cloudstack/api/ApiErrorCode.java -type ErrorCode int - -//go:generate stringer -type ErrorCode -const ( - // Unauthorized represents ... (TODO) - Unauthorized ErrorCode = 401 - // MethodNotAllowed represents ... (TODO) - MethodNotAllowed ErrorCode = 405 - // UnsupportedActionError represents ... (TODO) - UnsupportedActionError ErrorCode = 422 - // APILimitExceeded represents ... (TODO) - APILimitExceeded ErrorCode = 429 - // MalformedParameterError represents ... (TODO) - MalformedParameterError ErrorCode = 430 - // ParamError represents ... (TODO) - ParamError ErrorCode = 431 - - // InternalError represents a server error - InternalError ErrorCode = 530 - // AccountError represents ... (TODO) - AccountError ErrorCode = 531 - // AccountResourceLimitError represents ... (TODO) - AccountResourceLimitError ErrorCode = 532 - // InsufficientCapacityError represents ... (TODO) - InsufficientCapacityError ErrorCode = 533 - // ResourceUnavailableError represents ... (TODO) - ResourceUnavailableError ErrorCode = 534 - // ResourceAllocationError represents ... (TODO) - ResourceAllocationError ErrorCode = 535 - // ResourceInUseError represents ... (TODO) - ResourceInUseError ErrorCode = 536 - // NetworkRuleConflictError represents ... (TODO) - NetworkRuleConflictError ErrorCode = 537 -) - -// CSErrorCode represents the CloudStack CSExceptionErrorCode enum -// -// See: https://github.com/apache/cloudstack/blob/master/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java -type CSErrorCode int - -//go:generate stringer -type CSErrorCode -const ( - // CloudRuntimeException ... (TODO) - CloudRuntimeException CSErrorCode = 4250 - // ExecutionException ... (TODO) - ExecutionException CSErrorCode = 4260 - // HypervisorVersionChangedException ... (TODO) - HypervisorVersionChangedException CSErrorCode = 4265 - // CloudException ... (TODO) - CloudException CSErrorCode = 4275 - // AccountLimitException ... (TODO) - AccountLimitException CSErrorCode = 4280 - // AgentUnavailableException ... (TODO) - AgentUnavailableException CSErrorCode = 4285 - // CloudAuthenticationException ... (TODO) - CloudAuthenticationException CSErrorCode = 4290 - // ConcurrentOperationException ... (TODO) - ConcurrentOperationException CSErrorCode = 4300 - // ConflictingNetworksException ... (TODO) - ConflictingNetworkSettingsException CSErrorCode = 4305 - // DiscoveredWithErrorException ... (TODO) - DiscoveredWithErrorException CSErrorCode = 4310 - // HAStateException ... (TODO) - HAStateException CSErrorCode = 4315 - // InsufficientAddressCapacityException ... (TODO) - InsufficientAddressCapacityException CSErrorCode = 4320 - // InsufficientCapacityException ... (TODO) - InsufficientCapacityException CSErrorCode = 4325 - // InsufficientNetworkCapacityException ... (TODO) - InsufficientNetworkCapacityException CSErrorCode = 4330 - // InsufficientServerCapaticyException ... (TODO) - InsufficientServerCapacityException CSErrorCode = 4335 - // InsufficientStorageCapacityException ... (TODO) - InsufficientStorageCapacityException CSErrorCode = 4340 - // InternalErrorException ... (TODO) - InternalErrorException CSErrorCode = 4345 - // InvalidParameterValueException ... (TODO) - InvalidParameterValueException CSErrorCode = 4350 - // ManagementServerException ... (TODO) - ManagementServerException CSErrorCode = 4355 - // NetworkRuleConflictException ... (TODO) - NetworkRuleConflictException CSErrorCode = 4360 - // PermissionDeniedException ... (TODO) - PermissionDeniedException CSErrorCode = 4365 - // ResourceAllocationException ... (TODO) - ResourceAllocationException CSErrorCode = 4370 - // ResourceInUseException ... (TODO) - ResourceInUseException CSErrorCode = 4375 - // ResourceUnavailableException ... (TODO) - ResourceUnavailableException CSErrorCode = 4380 - // StorageUnavailableException ... (TODO) - StorageUnavailableException CSErrorCode = 4385 - // UnsupportedServiceException ... (TODO) - UnsupportedServiceException CSErrorCode = 4390 - // VirtualMachineMigrationException ... (TODO) - VirtualMachineMigrationException CSErrorCode = 4395 - // AsyncCommandQueued ... (TODO) - AsyncCommandQueued CSErrorCode = 4540 - // RequestLimitException ... (TODO) - RequestLimitException CSErrorCode = 4545 - // ServerAPIException ... (TODO) - ServerAPIException CSErrorCode = 9999 -) - -// ErrorResponse represents the standard error response -type ErrorResponse struct { - CSErrorCode CSErrorCode `json:"cserrorcode"` - ErrorCode ErrorCode `json:"errorcode"` - ErrorText string `json:"errortext"` - UUIDList []UUIDItem `json:"uuidList,omitempty"` // uuid*L*ist is not a typo -} - -// UUIDItem represents an item of the UUIDList part of an ErrorResponse -type UUIDItem struct { - Description string `json:"description,omitempty"` - SerialVersionUID int64 `json:"serialVersionUID,omitempty"` - UUID string `json:"uuid"` -} - -// BooleanResponse represents a boolean response (usually after a deletion) -type BooleanResponse struct { - DisplayText string `json:"displaytext,omitempty"` - Success bool `json:"success"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resource_limits.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resource_limits.go deleted file mode 100644 index 56011dc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resource_limits.go +++ /dev/null @@ -1,100 +0,0 @@ -package egoscale - -// https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/configuration/Resource.java - -// ResourceTypeName represents the name of a resource type (for limits) -type ResourceTypeName string - -const ( - // VirtualMachineTypeName is the resource type name of a VM - VirtualMachineTypeName ResourceTypeName = "user_vm" - // IPAddressTypeName is the resource type name of an IP address - IPAddressTypeName ResourceTypeName = "public_ip" - // VolumeTypeName is the resource type name of a volume - VolumeTypeName ResourceTypeName = "volume" - // SnapshotTypeName is the resource type name of a snapshot - SnapshotTypeName ResourceTypeName = "snapshot" - // TemplateTypeName is the resource type name of a template - TemplateTypeName ResourceTypeName = "template" - // ProjectTypeName is the resource type name of a project - ProjectTypeName ResourceTypeName = "project" - // NetworkTypeName is the resource type name of a network - NetworkTypeName ResourceTypeName = "network" - // VPCTypeName is the resource type name of a VPC - VPCTypeName ResourceTypeName = "vpc" - // CPUTypeName is the resource type name of a CPU - CPUTypeName ResourceTypeName = "cpu" - // MemoryTypeName is the resource type name of Memory - MemoryTypeName ResourceTypeName = "memory" - // PrimaryStorageTypeName is the resource type name of primary storage - PrimaryStorageTypeName ResourceTypeName = "primary_storage" - // SecondaryStorageTypeName is the resource type name of secondary storage - SecondaryStorageTypeName ResourceTypeName = "secondary_storage" -) - -// ResourceType represents the ID of a resource type (for limits) -type ResourceType string - -const ( - // VirtualMachineType is the resource type ID of a VM - VirtualMachineType ResourceType = "0" - // IPAddressType is the resource type ID of an IP address - IPAddressType ResourceType = "1" - // VolumeType is the resource type ID of a volume - VolumeType ResourceType = "2" - // SnapshotType is the resource type ID of a snapshot - SnapshotType ResourceType = "3" - // TemplateType is the resource type ID of a template - TemplateType ResourceType = "4" - // ProjectType is the resource type ID of a project - ProjectType ResourceType = "5" - // NetworkType is the resource type ID of a network - NetworkType ResourceType = "6" - // VPCType is the resource type ID of a VPC - VPCType ResourceType = "7" - // CPUType is the resource type ID of a CPU - CPUType ResourceType = "8" - // MemoryType is the resource type ID of Memory - MemoryType ResourceType = "9" - // PrimaryStorageType is the resource type ID of primary storage - PrimaryStorageType ResourceType = "10" - // SecondaryStorageType is the resource type ID of secondary storage - SecondaryStorageType ResourceType = "11" -) - -// ResourceLimit represents the limit on a particular resource -type ResourceLimit struct { - Max int64 `json:"max,omitempty" doc:"the maximum number of the resource. A -1 means the resource currently has no limit."` - ResourceType ResourceType `json:"resourcetype,omitempty" doc:"resource type. Values include 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11. See the resourceType parameter for more information on these values."` - ResourceTypeName string `json:"resourcetypename,omitempty" doc:"resource type name. Values include user_vm, public_ip, volume, snapshot, template, network, cpu, memory, primary_storage, secondary_storage."` -} - -// ListRequest builds the ListResourceLimits request -func (limit ResourceLimit) ListRequest() (ListCommand, error) { - req := &ListResourceLimits{ - ResourceType: limit.ResourceType, - ResourceTypeName: limit.ResourceTypeName, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListResourceLimits - -// ListResourceLimits lists the resource limits -type ListResourceLimits struct { - ID int64 `json:"id,omitempty" doc:"Lists resource limits by ID."` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ResourceType ResourceType `json:"resourcetype,omitempty" doc:"Type of resource. Values are 0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, and 13. 0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses an account can own. 2 - Volume. Number of disk volumes an account can own. 3 - Snapshot. Number of snapshots an account can own. 4 - Template. Number of templates an account can register/create. 6 - Network. Number of networks an account can own. 8 - CPU. Number of CPU an account can allocate for his resources. 9 - Memory. Amount of RAM an account can allocate for his resources. 10 - PrimaryStorage. Total primary storage space (in GiB) a user can use. 11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use. 12 - Elastic IP. Number of public elastic IP addresses an account can own. 13 - SMTP. If the account is allowed SMTP outbound traffic."` - ResourceTypeName string `json:"resourcetypename,omitempty" doc:"Type of resource (wins over resourceType if both are provided). Values are: user_vm - Instance. Number of instances a user can create. public_ip - IP. Number of public IP addresses an account can own. volume - Volume. Number of disk volumes an account can own. snapshot - Snapshot. Number of snapshots an account can own. template - Template. Number of templates an account can register/create. network - Network. Number of networks an account can own. cpu - CPU. Number of CPU an account can allocate for his resources. memory - Memory. Amount of RAM an account can allocate for his resources. primary_storage - PrimaryStorage. Total primary storage space (in GiB) a user can use. secondary_storage - SecondaryStorage. Total secondary storage space (in GiB) a user can use. public_elastic_ip - IP. Number of public elastic IP addresses an account can own. smtp - SG. If the account is allowed SMTP outbound traffic."` - - _ bool `name:"listResourceLimits" description:"Lists resource limits."` -} - -// ListResourceLimitsResponse represents a list of resource limits -type ListResourceLimitsResponse struct { - Count int `json:"count"` - ResourceLimit []ResourceLimit `json:"resourcelimit"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resource_metadata.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resource_metadata.go deleted file mode 100644 index 52c5ee8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resource_metadata.go +++ /dev/null @@ -1,41 +0,0 @@ -package egoscale - -import "fmt" - -// ResourceDetail represents extra details -type ResourceDetail ResourceTag - -// ListRequest builds the ListResourceDetails request -func (detail ResourceDetail) ListRequest() (ListCommand, error) { - if detail.ResourceType == "" { - return nil, fmt.Errorf("the resourcetype parameter is required") - } - - req := &ListResourceDetails{ - ResourceType: detail.ResourceType, - ResourceID: detail.ResourceID, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListResourceDetails - -// ListResourceDetails lists the resource tag(s) (but different from listTags...) -type ListResourceDetails struct { - ResourceType string `json:"resourcetype" doc:"list by resource type"` - ForDisplay bool `json:"fordisplay,omitempty" doc:"if set to true, only details marked with display=true, are returned. False by default"` - Key string `json:"key,omitempty" doc:"list by key"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ResourceID *UUID `json:"resourceid,omitempty" doc:"list by resource id"` - Value string `json:"value,omitempty" doc:"list by key, value. Needs to be passed only along with key"` - _ bool `name:"listResourceDetails" description:"List resource detail(s)"` -} - -// ListResourceDetailsResponse represents a list of resource details -type ListResourceDetailsResponse struct { - Count int `json:"count"` - ResourceDetail []ResourceTag `json:"resourcedetail"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resourcedetails_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resourcedetails_response.go deleted file mode 100644 index 2a08cd8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resourcedetails_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListResourceDetails) Response() interface{} { - return new(ListResourceDetailsResponse) -} - -// ListRequest returns itself -func (ls *ListResourceDetails) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListResourceDetails) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListResourceDetails) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListResourceDetails) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListResourceDetailsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListResourceDetailsResponse was expected, got %T", resp)) - return - } - - for i := range items.ResourceDetail { - if !callback(&items.ResourceDetail[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resourcelimits_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resourcelimits_response.go deleted file mode 100644 index 656febf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/resourcelimits_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListResourceLimits) Response() interface{} { - return new(ListResourceLimitsResponse) -} - -// ListRequest returns itself -func (ls *ListResourceLimits) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListResourceLimits) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListResourceLimits) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListResourceLimits) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListResourceLimitsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListResourceLimitsResponse was expected, got %T", resp)) - return - } - - for i := range items.ResourceLimit { - if !callback(&items.ResourceLimit[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/reversedns.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/reversedns.go deleted file mode 100644 index e8bd124..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/reversedns.go +++ /dev/null @@ -1,83 +0,0 @@ -package egoscale - -import ( - "net" -) - -// ReverseDNS represents the PTR record linked with an IPAddress or IP6Address belonging to a Virtual Machine or a Public IP Address (Elastic IP) instance -type ReverseDNS struct { - DomainName string `json:"domainname,omitempty" doc:"the domain name of the PTR record"` - IP6Address net.IP `json:"ip6address,omitempty" doc:"the IPv6 address linked with the PTR record (mutually exclusive with ipaddress)"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"the IPv4 address linked with the PTR record (mutually exclusive with ip6address)"` - NicID *UUID `json:"nicid,omitempty" doc:"the virtual machine default NIC ID"` - PublicIPID *UUID `json:"publicipid,omitempty" doc:"the public IP address ID"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the virtual machine ID"` -} - -// DeleteReverseDNSFromPublicIPAddress is a command to create/delete the PTR record of a public IP address -type DeleteReverseDNSFromPublicIPAddress struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the public IP address"` - _ bool `name:"deleteReverseDnsFromPublicIpAddress" description:"delete the PTR DNS record from the public IP address"` -} - -// Response returns the struct to unmarshal -func (*DeleteReverseDNSFromPublicIPAddress) Response() interface{} { - return new(BooleanResponse) -} - -// DeleteReverseDNSFromVirtualMachine is a command to create/delete the PTR record(s) of a virtual machine -type DeleteReverseDNSFromVirtualMachine struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - _ bool `name:"deleteReverseDnsFromVirtualMachine" description:"Delete the PTR DNS record(s) from the virtual machine"` -} - -// Response returns the struct to unmarshal -func (*DeleteReverseDNSFromVirtualMachine) Response() interface{} { - return new(BooleanResponse) -} - -// QueryReverseDNSForPublicIPAddress is a command to create/query the PTR record of a public IP address -type QueryReverseDNSForPublicIPAddress struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the public IP address"` - _ bool `name:"queryReverseDnsForPublicIpAddress" description:"Query the PTR DNS record for the public IP address"` -} - -// Response returns the struct to unmarshal -func (*QueryReverseDNSForPublicIPAddress) Response() interface{} { - return new(IPAddress) -} - -// QueryReverseDNSForVirtualMachine is a command to create/query the PTR record(s) of a virtual machine -type QueryReverseDNSForVirtualMachine struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - _ bool `name:"queryReverseDnsForVirtualMachine" description:"Query the PTR DNS record(s) for the virtual machine"` -} - -// Response returns the struct to unmarshal -func (*QueryReverseDNSForVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// UpdateReverseDNSForPublicIPAddress is a command to create/update the PTR record of a public IP address -type UpdateReverseDNSForPublicIPAddress struct { - DomainName string `json:"domainname,omitempty" doc:"the domain name for the PTR record. It must have a valid TLD"` - ID *UUID `json:"id,omitempty" doc:"the ID of the public IP address"` - _ bool `name:"updateReverseDnsForPublicIpAddress" description:"Update/create the PTR DNS record for the public IP address"` -} - -// Response returns the struct to unmarshal -func (*UpdateReverseDNSForPublicIPAddress) Response() interface{} { - return new(IPAddress) -} - -// UpdateReverseDNSForVirtualMachine is a command to create/update the PTR record(s) of a virtual machine -type UpdateReverseDNSForVirtualMachine struct { - DomainName string `json:"domainname,omitempty" doc:"the domain name for the PTR record(s). It must have a valid TLD"` - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - _ bool `name:"updateReverseDnsForVirtualMachine" description:"Update/create the PTR DNS record(s) for the virtual machine"` -} - -// Response returns the struct to unmarshal -func (*UpdateReverseDNSForVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus.go deleted file mode 100644 index ac9c75f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus.go +++ /dev/null @@ -1,264 +0,0 @@ -package egoscale - -import ( - "context" - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/url" - "strings" - "time" -) - -// RunstatusValidationErrorResponse represents an error in the API -type RunstatusValidationErrorResponse map[string][]string - -// RunstatusErrorResponse represents the default errors -type RunstatusErrorResponse struct { - Detail string `json:"detail"` -} - -// runstatusPagesURL is the only URL that cannot be guessed -const runstatusPagesURL = "/pages" - -// RunstatusPage runstatus page -type RunstatusPage struct { - Created *time.Time `json:"created,omitempty"` - DarkTheme bool `json:"dark_theme,omitempty"` - Domain string `json:"domain,omitempty"` - GradientEnd string `json:"gradient_end,omitempty"` - GradientStart string `json:"gradient_start,omitempty"` - HeaderBackground string `json:"header_background,omitempty"` - ID int `json:"id,omitempty"` - Incidents []RunstatusIncident `json:"incidents,omitempty"` - IncidentsURL string `json:"incidents_url,omitempty"` - Logo string `json:"logo,omitempty"` - Maintenances []RunstatusMaintenance `json:"maintenances,omitempty"` - MaintenancesURL string `json:"maintenances_url,omitempty"` - Name string `json:"name"` //fake field (used to post a new runstatus page) - OkText string `json:"ok_text,omitempty"` - Plan string `json:"plan,omitempty"` - PublicURL string `json:"public_url,omitempty"` - Services []RunstatusService `json:"services,omitempty"` - ServicesURL string `json:"services_url,omitempty"` - State string `json:"state,omitempty"` - Subdomain string `json:"subdomain"` - SupportEmail string `json:"support_email,omitempty"` - TimeZone string `json:"time_zone,omitempty"` - Title string `json:"title,omitempty"` - TitleColor string `json:"title_color,omitempty"` - TwitterUsername string `json:"twitter_username,omitempty"` - URL string `json:"url,omitempty"` -} - -// Match returns true if the other page has got similarities with itself -func (page RunstatusPage) Match(other RunstatusPage) bool { - if other.Subdomain != "" && page.Subdomain == other.Subdomain { - return true - } - - if other.ID > 0 && page.ID == other.ID { - return true - } - - return false -} - -//RunstatusPageList runstatus page list -type RunstatusPageList struct { - Count int `json:"count"` - Next string `json:"next"` - Previous string `json:"previous"` - Results []RunstatusPage `json:"results"` -} - -// CreateRunstatusPage create runstatus page -func (client *Client) CreateRunstatusPage(ctx context.Context, page RunstatusPage) (*RunstatusPage, error) { - resp, err := client.runstatusRequest(ctx, client.Endpoint+runstatusPagesURL, page, "POST") - if err != nil { - return nil, err - } - - var p *RunstatusPage - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - return p, nil -} - -// DeleteRunstatusPage delete runstatus page -func (client *Client) DeleteRunstatusPage(ctx context.Context, page RunstatusPage) error { - if page.URL == "" { - return fmt.Errorf("empty URL for %#v", page) - } - _, err := client.runstatusRequest(ctx, page.URL, nil, "DELETE") - return err -} - -// GetRunstatusPage fetches the runstatus page -func (client *Client) GetRunstatusPage(ctx context.Context, page RunstatusPage) (*RunstatusPage, error) { - if page.URL != "" { - return client.getRunstatusPage(ctx, page.URL) - } - - ps, err := client.ListRunstatusPages(ctx) - if err != nil { - return nil, err - } - - for i := range ps { - if ps[i].Match(page) { - return &ps[i], nil - } - } - - return nil, fmt.Errorf("%#v not found", page) -} - -func (client *Client) getRunstatusPage(ctx context.Context, pageURL string) (*RunstatusPage, error) { - resp, err := client.runstatusRequest(ctx, pageURL, nil, "GET") - if err != nil { - return nil, err - } - - p := new(RunstatusPage) - if err := json.Unmarshal(resp, p); err != nil { - return nil, err - } - - // NOTE: fix the missing IDs - for i := range p.Maintenances { - if err := p.Maintenances[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", p.Maintenances[i], err) - } - } - - return p, nil -} - -// ListRunstatusPages list all the runstatus pages -func (client *Client) ListRunstatusPages(ctx context.Context) ([]RunstatusPage, error) { - resp, err := client.runstatusRequest(ctx, client.Endpoint+runstatusPagesURL, nil, "GET") - if err != nil { - return nil, err - } - - var p *RunstatusPageList - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - // XXX: handle pagination - return p.Results, nil -} - -// Error formats the DNSerror into a string -func (req RunstatusErrorResponse) Error() string { - return fmt.Sprintf("Runstatus error: %s", req.Detail) -} - -// Error formats the DNSerror into a string -func (req RunstatusValidationErrorResponse) Error() string { - if len(req) > 0 { - errs := []string{} - for name, ss := range req { - if len(ss) > 0 { - errs = append(errs, fmt.Sprintf("%s: %s", name, strings.Join(ss, ", "))) - } - } - return fmt.Sprintf("Runstatus error: %s", strings.Join(errs, "; ")) - } - return fmt.Sprintf("Runstatus error") -} - -func (client *Client) runstatusRequest(ctx context.Context, uri string, structParam interface{}, method string) (json.RawMessage, error) { - reqURL, err := url.Parse(uri) - if err != nil { - return nil, err - } - if reqURL.Scheme == "" { - return nil, fmt.Errorf("only absolute URI are considered valid, got %q", uri) - } - - var params string - if structParam != nil { - m, err := json.Marshal(structParam) - if err != nil { - return nil, err - } - params = string(m) - } - - req, err := http.NewRequest(method, reqURL.String(), strings.NewReader(params)) - if err != nil { - return nil, err - } - - time := time.Now().Local().Format("2006-01-02T15:04:05-0700") - - payload := fmt.Sprintf("%s%s%s", req.URL.String(), time, params) - - mac := hmac.New(sha256.New, []byte(client.apiSecret)) - _, err = mac.Write([]byte(payload)) - if err != nil { - return nil, err - } - signature := hex.EncodeToString(mac.Sum(nil)) - - var hdr = make(http.Header) - - hdr.Add("Authorization", fmt.Sprintf("Exoscale-HMAC-SHA256 %s:%s", client.APIKey, signature)) - hdr.Add("Exoscale-Date", time) - hdr.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version)) - hdr.Add("Accept", "application/json") - if params != "" { - hdr.Add("Content-Type", "application/json") - } - req.Header = hdr - - req = req.WithContext(ctx) - - resp, err := client.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() // nolint: errcheck - - if resp.StatusCode == 204 { - if method != "DELETE" { - return nil, fmt.Errorf("only DELETE is expected to produce 204, was %q", method) - } - return nil, nil - } - - contentType := resp.Header.Get("content-type") - if !strings.Contains(contentType, "application/json") { - return nil, fmt.Errorf(`response content-type expected to be "application/json", got %q`, contentType) - } - - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode >= 400 { - rerr := new(RunstatusValidationErrorResponse) - if err := json.Unmarshal(b, rerr); err == nil { - return nil, rerr - } - rverr := new(RunstatusErrorResponse) - if err := json.Unmarshal(b, rverr); err != nil { - return nil, err - } - - return nil, rverr - } - - return b, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_event.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_event.go deleted file mode 100644 index 2c69878..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_event.go +++ /dev/null @@ -1,37 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "time" -) - -//RunstatusEvent is a runstatus event -type RunstatusEvent struct { - Created *time.Time `json:"created,omitempty"` - State string `json:"state,omitempty"` - Status string `json:"status"` - Text string `json:"text"` -} - -// UpdateRunstatusIncident create runstatus incident event -// Events can be updates or final message with status completed. -func (client *Client) UpdateRunstatusIncident(ctx context.Context, incident RunstatusIncident, event RunstatusEvent) error { - if incident.EventsURL == "" { - return fmt.Errorf("empty Events URL for %#v", incident) - } - - _, err := client.runstatusRequest(ctx, incident.EventsURL, event, "POST") - return err -} - -// UpdateRunstatusMaintenance adds a event to a maintenance. -// Events can be updates or final message with status completed. -func (client *Client) UpdateRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance, event RunstatusEvent) error { - if maintenance.EventsURL == "" { - return fmt.Errorf("empty Events URL for %#v", maintenance) - } - - _, err := client.runstatusRequest(ctx, maintenance.EventsURL, event, "POST") - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_incident.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_incident.go deleted file mode 100644 index 2a4c6f7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_incident.go +++ /dev/null @@ -1,144 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "time" -) - -//RunstatusIncident is a runstatus incident -type RunstatusIncident struct { - EndDate *time.Time `json:"end_date,omitempty"` - Events []RunstatusEvent `json:"events,omitempty"` - EventsURL string `json:"events_url,omitempty"` - ID int `json:"id,omitempty"` - PageURL string `json:"page_url,omitempty"` // fake field - PostMortem string `json:"post_mortem,omitempty"` - RealTime bool `json:"real_time,omitempty"` - Services []string `json:"services"` - StartDate *time.Time `json:"start_date,omitempty"` - State string `json:"state"` - Status string `json:"status"` - StatusText string `json:"status_text"` - Title string `json:"title"` - URL string `json:"url,omitempty"` -} - -// Match returns true if the other incident has got similarities with itself -func (incident RunstatusIncident) Match(other RunstatusIncident) bool { - if other.Title != "" && incident.Title == other.Title { - return true - } - - if other.ID > 0 && incident.ID == other.ID { - return true - } - - return false -} - -//RunstatusIncidentList is a list of incident -type RunstatusIncidentList struct { - Incidents []RunstatusIncident `json:"incidents"` -} - -// GetRunstatusIncident retrieves the details of a specific incident. -func (client *Client) GetRunstatusIncident(ctx context.Context, incident RunstatusIncident) (*RunstatusIncident, error) { - if incident.URL != "" { - return client.getRunstatusIncident(ctx, incident.URL) - } - - if incident.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", incident) - } - - page, err := client.getRunstatusPage(ctx, incident.PageURL) - if err != nil { - return nil, err - } - - is, err := client.ListRunstatusIncidents(ctx, *page) - if err != nil { - return nil, err - } - - for i := range is { - if is[i].Match(incident) { - return &is[i], nil - } - } - - return nil, fmt.Errorf("%#v not found", incident) -} - -func (client *Client) getRunstatusIncident(ctx context.Context, incidentURL string) (*RunstatusIncident, error) { - resp, err := client.runstatusRequest(ctx, incidentURL, nil, "GET") - if err != nil { - return nil, err - } - - i := new(RunstatusIncident) - if err := json.Unmarshal(resp, i); err != nil { - return nil, err - } - return i, nil -} - -// ListRunstatusIncidents lists the incidents for a specific page. -func (client *Client) ListRunstatusIncidents(ctx context.Context, page RunstatusPage) ([]RunstatusIncident, error) { - if page.IncidentsURL == "" { - return nil, fmt.Errorf("empty Incidents URL for %#v", page) - } - - resp, err := client.runstatusRequest(ctx, page.IncidentsURL, nil, "GET") - if err != nil { - return nil, err - } - - var p *RunstatusIncidentList - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - // NOTE: no pagination - return p.Incidents, nil -} - -// CreateRunstatusIncident create runstatus incident -func (client *Client) CreateRunstatusIncident(ctx context.Context, incident RunstatusIncident) (*RunstatusIncident, error) { - if incident.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", incident) - } - - page, err := client.getRunstatusPage(ctx, incident.PageURL) - if err != nil { - return nil, err - } - - if page.IncidentsURL == "" { - return nil, fmt.Errorf("empty Incidents URL for %#v", page) - } - - resp, err := client.runstatusRequest(ctx, page.IncidentsURL, incident, "POST") - if err != nil { - return nil, err - } - - i := &RunstatusIncident{} - if err := json.Unmarshal(resp, &i); err != nil { - return nil, err - } - - return i, nil -} - -// DeleteRunstatusIncident delete runstatus incident -func (client *Client) DeleteRunstatusIncident(ctx context.Context, incident RunstatusIncident) error { - if incident.URL == "" { - return fmt.Errorf("empty URL for %#v", incident) - } - - _, err := client.runstatusRequest(ctx, incident.URL, nil, "DELETE") - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_maintenance.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_maintenance.go deleted file mode 100644 index d9aad33..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_maintenance.go +++ /dev/null @@ -1,178 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "log" - "net/url" - "path" - "strconv" - "time" -) - -// RunstatusMaintenance is a runstatus maintenance -type RunstatusMaintenance struct { - Created *time.Time `json:"created,omitempty"` - Description string `json:"description,omitempty"` - EndDate *time.Time `json:"end_date"` - Events []RunstatusEvent `json:"events,omitempty"` - EventsURL string `json:"events_url,omitempty"` - ID int `json:"id,omitempty"` // missing field - PageURL string `json:"page_url,omitempty"` // fake field - RealTime bool `json:"real_time,omitempty"` - Services []string `json:"services"` - StartDate *time.Time `json:"start_date"` - Status string `json:"status"` - Title string `json:"title"` - URL string `json:"url,omitempty"` -} - -// Match returns true if the other maintenance has got similarities with itself -func (maintenance RunstatusMaintenance) Match(other RunstatusMaintenance) bool { - if other.Title != "" && maintenance.Title == other.Title { - return true - } - - if other.ID > 0 && maintenance.ID == other.ID { - return true - } - - return false -} - -// FakeID fills up the ID field as it's currently missing -func (maintenance *RunstatusMaintenance) FakeID() error { - if maintenance.ID > 0 { - return nil - } - - if maintenance.URL == "" { - return fmt.Errorf("empty URL for %#v", maintenance) - } - - u, err := url.Parse(maintenance.URL) - if err != nil { - return err - } - - s := path.Base(u.Path) - id, err := strconv.Atoi(s) - if err != nil { - return err - } - maintenance.ID = id - return nil -} - -//RunstatusMaintenanceList is a list of incident -type RunstatusMaintenanceList struct { - Maintenances []RunstatusMaintenance `json:"maintenances"` -} - -// GetRunstatusMaintenance retrieves the details of a specific maintenance. -func (client *Client) GetRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance) (*RunstatusMaintenance, error) { - if maintenance.URL != "" { - return client.getRunstatusMaintenance(ctx, maintenance.URL) - } - - if maintenance.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", maintenance) - } - - page, err := client.getRunstatusPage(ctx, maintenance.PageURL) - if err != nil { - return nil, err - } - - ms, err := client.ListRunstatusMaintenances(ctx, *page) - if err != nil { - return nil, err - } - - for i := range ms { - if ms[i].Match(maintenance) { - return &ms[i], nil - } - } - - return nil, fmt.Errorf("%#v not found", maintenance) -} - -func (client *Client) getRunstatusMaintenance(ctx context.Context, maintenanceURL string) (*RunstatusMaintenance, error) { - resp, err := client.runstatusRequest(ctx, maintenanceURL, nil, "GET") - if err != nil { - return nil, err - } - - m := new(RunstatusMaintenance) - if err := json.Unmarshal(resp, m); err != nil { - return nil, err - } - return m, nil -} - -// ListRunstatusMaintenances returns the list of maintenances for the page. -func (client *Client) ListRunstatusMaintenances(ctx context.Context, page RunstatusPage) ([]RunstatusMaintenance, error) { - if page.MaintenancesURL == "" { - return nil, fmt.Errorf("empty Maintenances URL for %#v", page) - } - - resp, err := client.runstatusRequest(ctx, page.MaintenancesURL, nil, "GET") - if err != nil { - return nil, err - } - - var p *RunstatusMaintenanceList - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - // NOTE: fix the missing IDs - for i := range p.Maintenances { - if err := p.Maintenances[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", p.Maintenances[i], err) - } - } - - // NOTE: the list of maintenances doesn't have any pagination - return p.Maintenances, nil -} - -// CreateRunstatusMaintenance create runstatus Maintenance -func (client *Client) CreateRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance) (*RunstatusMaintenance, error) { - if maintenance.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", maintenance) - } - - page, err := client.getRunstatusPage(ctx, maintenance.PageURL) - if err != nil { - return nil, err - } - - resp, err := client.runstatusRequest(ctx, page.MaintenancesURL, maintenance, "POST") - if err != nil { - return nil, err - } - - m := &RunstatusMaintenance{} - if err := json.Unmarshal(resp, &m); err != nil { - return nil, err - } - - if err := m.FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", m, err) - } - - return m, nil -} - -// DeleteRunstatusMaintenance delete runstatus Maintenance -func (client *Client) DeleteRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance) error { - if maintenance.URL == "" { - return fmt.Errorf("empty URL for %#v", maintenance) - } - - _, err := client.runstatusRequest(ctx, maintenance.URL, nil, "DELETE") - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_service.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_service.go deleted file mode 100644 index 337cb88..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/runstatus_service.go +++ /dev/null @@ -1,170 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "log" - "net/url" - "path" - "strconv" -) - -// RunstatusService is a runstatus service -type RunstatusService struct { - ID int `json:"id"` // missing field - Name string `json:"name"` - PageURL string `json:"page_url,omitempty"` // fake field - State string `json:"state,omitempty"` - URL string `json:"url,omitempty"` -} - -// FakeID fills up the ID field as it's currently missing -func (service *RunstatusService) FakeID() error { - if service.ID > 0 { - return nil - } - - if service.URL == "" { - return fmt.Errorf("empty URL for %#v", service) - } - - u, err := url.Parse(service.URL) - if err != nil { - return err - } - - s := path.Base(u.Path) - id, err := strconv.Atoi(s) - if err != nil { - return err - } - service.ID = id - return nil -} - -// Match returns true if the other service has got similarities with itself -func (service RunstatusService) Match(other RunstatusService) bool { - if other.Name != "" && service.Name == other.Name { - return true - } - - if other.ID > 0 && service.ID == other.ID { - return true - } - - return false -} - -// RunstatusServiceList service list -type RunstatusServiceList struct { - Services []RunstatusService `json:"services"` -} - -// DeleteRunstatusService delete runstatus service -func (client *Client) DeleteRunstatusService(ctx context.Context, service RunstatusService) error { - if service.URL == "" { - return fmt.Errorf("empty URL for %#v", service) - } - - _, err := client.runstatusRequest(ctx, service.URL, nil, "DELETE") - return err -} - -// CreateRunstatusService create runstatus service -func (client *Client) CreateRunstatusService(ctx context.Context, service RunstatusService) (*RunstatusService, error) { - if service.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", service) - } - - page, err := client.GetRunstatusPage(ctx, RunstatusPage{URL: service.PageURL}) - if err != nil { - return nil, err - } - - resp, err := client.runstatusRequest(ctx, page.ServicesURL, service, "POST") - if err != nil { - return nil, err - } - - s := &RunstatusService{} - if err := json.Unmarshal(resp, s); err != nil { - return nil, err - } - - return s, nil -} - -// GetRunstatusService displays service detail. -func (client *Client) GetRunstatusService(ctx context.Context, service RunstatusService) (*RunstatusService, error) { - if service.URL != "" { - return client.getRunstatusService(ctx, service.URL) - } - - if service.PageURL == "" { - return nil, fmt.Errorf("empty Page URL in %#v", service) - } - - page, err := client.getRunstatusPage(ctx, service.PageURL) - if err != nil { - return nil, err - } - - ss, err := client.ListRunstatusServices(ctx, *page) - if err != nil { - return nil, err - } - - for i := range ss { - if ss[i].Match(service) { - return &ss[i], nil - } - } - - return nil, fmt.Errorf("%#v not found", service) -} - -func (client *Client) getRunstatusService(ctx context.Context, serviceURL string) (*RunstatusService, error) { - resp, err := client.runstatusRequest(ctx, serviceURL, nil, "GET") - if err != nil { - return nil, err - } - - s := &RunstatusService{} - if err := json.Unmarshal(resp, &s); err != nil { - return nil, err - } - - if err := s.FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", s, err) - } - - return s, nil -} - -// ListRunstatusServices displays the list of services. -func (client *Client) ListRunstatusServices(ctx context.Context, page RunstatusPage) ([]RunstatusService, error) { - if page.ServicesURL == "" { - return nil, fmt.Errorf("empty Services URL for %#v", page) - } - - resp, err := client.runstatusRequest(ctx, page.ServicesURL, nil, "GET") - if err != nil { - return nil, err - } - - var p *RunstatusServiceList - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - // NOTE: fix the missing IDs - for i := range p.Services { - if err := p.Services[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", p.Services[i], err) - } - } - - // NOTE: no pagination - return p.Services, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/security_groups.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/security_groups.go deleted file mode 100644 index a11e53a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/security_groups.go +++ /dev/null @@ -1,226 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "net/url" - "strconv" - "strings" -) - -// SecurityGroup represent a firewalling set of rules -type SecurityGroup struct { - Account string `json:"account,omitempty" doc:"the account owning the security group"` - Description string `json:"description,omitempty" doc:"the description of the security group"` - EgressRule []EgressRule `json:"egressrule,omitempty" doc:"the list of egress rules associated with the security group"` - ID *UUID `json:"id" doc:"the ID of the security group"` - IngressRule []IngressRule `json:"ingressrule,omitempty" doc:"the list of ingress rules associated with the security group"` - Name string `json:"name,omitempty" doc:"the name of the security group"` -} - -// UserSecurityGroup converts a SecurityGroup to a UserSecurityGroup -func (sg SecurityGroup) UserSecurityGroup() UserSecurityGroup { - return UserSecurityGroup{ - Group: sg.Name, - } -} - -// ListRequest builds the ListSecurityGroups request -func (sg SecurityGroup) ListRequest() (ListCommand, error) { - req := &ListSecurityGroups{ - ID: sg.ID, - SecurityGroupName: sg.Name, - } - - return req, nil -} - -// Delete deletes the given Security Group -func (sg SecurityGroup) Delete(ctx context.Context, client *Client) error { - if sg.ID == nil && sg.Name == "" { - return fmt.Errorf("a SecurityGroup may only be deleted using ID or Name") - } - - req := &DeleteSecurityGroup{} - - if sg.ID != nil { - req.ID = sg.ID - } else { - req.Name = sg.Name - } - - return client.BooleanRequestWithContext(ctx, req) -} - -// RuleByID returns IngressRule or EgressRule by a rule ID -func (sg SecurityGroup) RuleByID(ruleID UUID) (*IngressRule, *EgressRule) { - for i, in := range sg.IngressRule { - if in.RuleID.Equal(ruleID) { - return &sg.IngressRule[i], nil - } - } - - for i, out := range sg.EgressRule { - if out.RuleID.Equal(ruleID) { - return nil, &sg.EgressRule[i] - } - } - - return nil, nil -} - -// IngressRule represents the ingress rule -type IngressRule struct { - CIDR *CIDR `json:"cidr,omitempty" doc:"the CIDR notation for the base IP address of the security group rule"` - Description string `json:"description,omitempty" doc:"description of the security group rule"` - EndPort uint16 `json:"endport,omitempty" doc:"the ending port of the security group rule "` - IcmpCode uint8 `json:"icmpcode,omitempty" doc:"the code for the ICMP message response"` - IcmpType uint8 `json:"icmptype,omitempty" doc:"the type of the ICMP message response"` - Protocol string `json:"protocol,omitempty" doc:"the protocol of the security group rule"` - RuleID *UUID `json:"ruleid" doc:"the id of the security group rule"` - SecurityGroupName string `json:"securitygroupname,omitempty" doc:"security group name"` - StartPort uint16 `json:"startport,omitempty" doc:"the starting port of the security group rule"` -} - -// EgressRule represents the ingress rule -type EgressRule IngressRule - -// UserSecurityGroup represents the traffic of another security group -type UserSecurityGroup struct { - Group string `json:"group,omitempty"` -} - -// String gives the UserSecurityGroup name -func (usg UserSecurityGroup) String() string { - return usg.Group -} - -// CreateSecurityGroup represents a security group creation -type CreateSecurityGroup struct { - Name string `json:"name" doc:"name of the security group"` - Description string `json:"description,omitempty" doc:"the description of the security group"` - _ bool `name:"createSecurityGroup" description:"Creates a security group"` -} - -// Response returns the struct to unmarshal -func (CreateSecurityGroup) Response() interface{} { - return new(SecurityGroup) -} - -// DeleteSecurityGroup represents a security group deletion -type DeleteSecurityGroup struct { - ID *UUID `json:"id,omitempty" doc:"The ID of the security group. Mutually exclusive with name parameter"` - Name string `json:"name,omitempty" doc:"The ID of the security group. Mutually exclusive with id parameter"` - _ bool `name:"deleteSecurityGroup" description:"Deletes security group"` -} - -// Response returns the struct to unmarshal -func (DeleteSecurityGroup) Response() interface{} { - return new(BooleanResponse) -} - -// AuthorizeSecurityGroupIngress (Async) represents the ingress rule creation -type AuthorizeSecurityGroupIngress struct { - CIDRList []CIDR `json:"cidrlist,omitempty" doc:"the cidr list associated"` - Description string `json:"description,omitempty" doc:"the description of the ingress/egress rule"` - EndPort uint16 `json:"endport,omitempty" doc:"end port for this ingress/egress rule"` - IcmpCode uint8 `json:"icmpcode,omitempty" doc:"error code for this icmp message"` - IcmpType uint8 `json:"icmptype,omitempty" doc:"type of the icmp message being sent"` - Protocol string `json:"protocol,omitempty" doc:"TCP is default. UDP, ICMP, ICMPv6, AH, ESP, GRE, IPIP are the other supported protocols"` - SecurityGroupID *UUID `json:"securitygroupid,omitempty" doc:"The ID of the security group. Mutually exclusive with securitygroupname parameter"` - SecurityGroupName string `json:"securitygroupname,omitempty" doc:"The name of the security group. Mutually exclusive with securitygroupid parameter"` - StartPort uint16 `json:"startport,omitempty" doc:"start port for this ingress/egress rule"` - UserSecurityGroupList []UserSecurityGroup `json:"usersecuritygrouplist,omitempty" doc:"user to security group mapping"` - _ bool `name:"authorizeSecurityGroupIngress" description:"Authorize a particular ingress/egress rule for this security group"` -} - -// Response returns the struct to unmarshal -func (AuthorizeSecurityGroupIngress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AuthorizeSecurityGroupIngress) AsyncResponse() interface{} { - return new(SecurityGroup) -} - -func (req AuthorizeSecurityGroupIngress) onBeforeSend(params url.Values) error { - // ICMP code and type may be zero but can also be omitted... - if strings.HasPrefix(strings.ToLower(req.Protocol), "icmp") { - params.Set("icmpcode", strconv.FormatInt(int64(req.IcmpCode), 10)) - params.Set("icmptype", strconv.FormatInt(int64(req.IcmpType), 10)) - } - // StartPort may be zero but can also be omitted... - if req.EndPort != 0 && req.StartPort == 0 { - params.Set("startport", "0") - } - return nil -} - -// AuthorizeSecurityGroupEgress (Async) represents the egress rule creation -type AuthorizeSecurityGroupEgress AuthorizeSecurityGroupIngress - -// Response returns the struct to unmarshal -func (AuthorizeSecurityGroupEgress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AuthorizeSecurityGroupEgress) AsyncResponse() interface{} { - return new(SecurityGroup) -} - -func (req AuthorizeSecurityGroupEgress) onBeforeSend(params url.Values) error { - return (AuthorizeSecurityGroupIngress)(req).onBeforeSend(params) -} - -// RevokeSecurityGroupIngress (Async) represents the ingress/egress rule deletion -type RevokeSecurityGroupIngress struct { - ID *UUID `json:"id" doc:"The ID of the ingress rule"` - _ bool `name:"revokeSecurityGroupIngress" description:"Deletes a particular ingress rule from this security group"` -} - -// Response returns the struct to unmarshal -func (RevokeSecurityGroupIngress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RevokeSecurityGroupIngress) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// RevokeSecurityGroupEgress (Async) represents the ingress/egress rule deletion -type RevokeSecurityGroupEgress struct { - ID *UUID `json:"id" doc:"The ID of the egress rule"` - _ bool `name:"revokeSecurityGroupEgress" description:"Deletes a particular egress rule from this security group"` -} - -// Response returns the struct to unmarshal -func (RevokeSecurityGroupEgress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RevokeSecurityGroupEgress) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListSecurityGroups - -// ListSecurityGroups represents a search for security groups -type ListSecurityGroups struct { - ID *UUID `json:"id,omitempty" doc:"list the security group by the id provided"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - SecurityGroupName string `json:"securitygroupname,omitempty" doc:"lists security groups by name"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"lists security groups by virtual machine id"` - _ bool `name:"listSecurityGroups" description:"Lists security groups"` -} - -// ListSecurityGroupsResponse represents a list of security groups -type ListSecurityGroupsResponse struct { - Count int `json:"count"` - SecurityGroup []SecurityGroup `json:"securitygroup"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/securitygroups_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/securitygroups_response.go deleted file mode 100644 index ff08f33..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/securitygroups_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListSecurityGroups) Response() interface{} { - return new(ListSecurityGroupsResponse) -} - -// ListRequest returns itself -func (ls *ListSecurityGroups) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListSecurityGroups) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListSecurityGroups) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListSecurityGroups) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListSecurityGroupsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListSecurityGroupsResponse was expected, got %T", resp)) - return - } - - for i := range items.SecurityGroup { - if !callback(&items.SecurityGroup[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/serialization.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/serialization.go deleted file mode 100644 index 24a0c12..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/serialization.go +++ /dev/null @@ -1,402 +0,0 @@ -package egoscale - -import ( - "encoding/base64" - "fmt" - "log" - "net" - "net/url" - "reflect" - "strconv" - "strings" -) - -func csQuotePlus(s string) string { - s = strings.Replace(s, "+", "%20", -1) - return s -} - -func csEncode(s string) string { - return csQuotePlus(url.QueryEscape(s)) -} - -// info returns the meta info of a command -// -// command is not a Command so it's easier to Test -func info(command interface{}) (*CommandInfo, error) { - typeof := reflect.TypeOf(command) - - // Going up the pointer chain to find the underlying struct - for typeof.Kind() == reflect.Ptr { - typeof = typeof.Elem() - } - - field, ok := typeof.FieldByName("_") - if !ok { - return nil, fmt.Errorf(`missing meta ("_") field in %#v`, command) - } - - name, nameOk := field.Tag.Lookup("name") - description, _ := field.Tag.Lookup("description") - - if !nameOk { - return nil, fmt.Errorf(`missing "name" key in the tag string of %#v`, command) - } - - info := &CommandInfo{ - Name: name, - Description: description, - } - - return info, nil -} - -// prepareValues uses a command to build a POST request -// -// command is not a Command so it's easier to Test -func prepareValues(prefix string, command interface{}) (url.Values, error) { - params := url.Values{} - - value := reflect.ValueOf(command) - typeof := reflect.TypeOf(command) - - // Going up the pointer chain to find the underlying struct - for typeof.Kind() == reflect.Ptr { - typeof = typeof.Elem() - value = value.Elem() - } - - // Checking for nil commands - if !value.IsValid() { - return nil, fmt.Errorf("cannot serialize the invalid value %#v", command) - } - - for i := 0; i < typeof.NumField(); i++ { - field := typeof.Field(i) - if field.Name == "_" { - continue - } - - val := value.Field(i) - tag := field.Tag - - var err error - var name string - var value interface{} - - if json, ok := tag.Lookup("json"); ok { - n, required := ExtractJSONTag(field.Name, json) - name = prefix + n - - switch val.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - value, err = prepareInt(val.Int(), required) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - value, err = prepareUint(val.Uint(), required) - - case reflect.Float32, reflect.Float64: - value, err = prepareFloat(val.Float(), required) - - case reflect.String: - value, err = prepareString(val.String(), required) - - case reflect.Bool: - value, err = prepareBool(val.Bool(), required) - - case reflect.Map: - if val.Len() == 0 { - if required { - err = fmt.Errorf("field is required, got empty map") - } - } else { - value, err = prepareMap(name, val.Interface()) - } - - case reflect.Ptr: - value, err = preparePtr(field.Type.Elem().Kind(), val, required) - - case reflect.Slice: - value, err = prepareSlice(name, field.Type, val, required) - - case reflect.Struct: - value, err = prepareStruct(val.Interface(), required) - - default: - if required { - err = fmt.Errorf("unsupported type") - } - } - } else { - switch val.Kind() { - case reflect.Struct: - value, err = prepareEmbedStruct(val.Interface()) - default: - log.Printf("[SKIP] %s.%s no json label found", typeof.Name(), field.Name) - } - } - - if err != nil { - return nil, fmt.Errorf("%s.%s (%v) %s", typeof.Name(), field.Name, val.Kind(), err) - } - - switch v := value.(type) { - case *string: - if name != "" && v != nil { - params.Set(name, *v) - } - case url.Values: - for k, xs := range v { - for _, x := range xs { - params.Add(k, x) - } - } - } - } - - return params, nil -} - -func prepareInt(v int64, required bool) (*string, error) { - if v == 0 { - if required { - return nil, fmt.Errorf("field is required, got %d", v) - } - return nil, nil - } - value := strconv.FormatInt(v, 10) - return &value, nil -} - -func prepareUint(v uint64, required bool) (*string, error) { - if v == 0 { - if required { - return nil, fmt.Errorf("field is required, got %d", v) - } - return nil, nil - } - - value := strconv.FormatUint(v, 10) - return &value, nil -} - -func prepareFloat(v float64, required bool) (*string, error) { - if v == 0 { - if required { - return nil, fmt.Errorf("field is required, got %f", v) - } - return nil, nil - } - value := strconv.FormatFloat(v, 'f', -1, 64) - return &value, nil -} - -func prepareString(v string, required bool) (*string, error) { - if v == "" { - if required { - return nil, fmt.Errorf("field is required, got %q", v) - } - return nil, nil - } - return &v, nil -} - -func prepareBool(v bool, required bool) (*string, error) { - value := strconv.FormatBool(v) - if !v { - if required { - return &value, nil - } - return nil, nil - } - - return &value, nil -} - -func prepareList(prefix string, slice interface{}) (url.Values, error) { - params := url.Values{} - value := reflect.ValueOf(slice) - - for i := 0; i < value.Len(); i++ { - ps, err := prepareValues(fmt.Sprintf("%s[%d].", prefix, i), value.Index(i).Interface()) - if err != nil { - return nil, err - } - - for k, xs := range ps { - for _, x := range xs { - params.Add(k, x) - } - } - } - - return params, nil -} - -func prepareMap(prefix string, m interface{}) (url.Values, error) { - value := url.Values{} - v := reflect.ValueOf(m) - - for i, key := range v.MapKeys() { - var keyName string - var keyValue string - - switch key.Kind() { - case reflect.String: - keyName = key.String() - default: - return value, fmt.Errorf("only map[string]string are supported (XXX)") - } - - val := v.MapIndex(key) - switch val.Kind() { - case reflect.String: - keyValue = val.String() - default: - return value, fmt.Errorf("only map[string]string are supported (XXX)") - } - - value.Set(fmt.Sprintf("%s[%d].%s", prefix, i, keyName), keyValue) - } - - return value, nil -} - -func preparePtr(kind reflect.Kind, val reflect.Value, required bool) (*string, error) { - if val.IsNil() { - if required { - return nil, fmt.Errorf("field is required, got empty ptr") - } - return nil, nil - } - - switch kind { - case reflect.Bool: - return prepareBool(val.Elem().Bool(), true) - case reflect.Struct: - return prepareStruct(val.Interface(), required) - default: - return nil, fmt.Errorf("kind %v is not supported as a ptr", kind) - } -} - -func prepareSlice(name string, fieldType reflect.Type, val reflect.Value, required bool) (interface{}, error) { - switch fieldType.Elem().Kind() { - case reflect.Uint8: - switch fieldType { - case reflect.TypeOf(net.IPv4zero): - ip := (net.IP)(val.Bytes()) - if ip == nil || ip.Equal(net.IP{}) { - if required { - return nil, fmt.Errorf("field is required, got zero IPv4 address") - } - } else { - value := ip.String() - return &value, nil - } - - case reflect.TypeOf(MAC48(0, 0, 0, 0, 0, 0)): - mac := val.Interface().(MACAddress) - s := mac.String() - if s == "" { - if required { - return nil, fmt.Errorf("field is required, got empty MAC address") - } - } else { - return &s, nil - } - default: - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - value := base64.StdEncoding.EncodeToString(val.Bytes()) - return &value, nil - } - } - case reflect.String: - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - elems := make([]string, 0, val.Len()) - for i := 0; i < val.Len(); i++ { - // XXX what if the value contains a comma? Double encode? - s := val.Index(i).String() - elems = append(elems, s) - } - value := strings.Join(elems, ",") - return &value, nil - } - default: - switch fieldType.Elem() { - case reflect.TypeOf(CIDR{}), reflect.TypeOf(UUID{}): - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - v := reflect.ValueOf(val.Interface()) - ss := make([]string, val.Len()) - for i := 0; i < v.Len(); i++ { - e := v.Index(i).Interface() - s, ok := e.(fmt.Stringer) - if !ok { - return nil, fmt.Errorf("not a String, %T", e) - } - ss[i] = s.String() - } - value := strings.Join(ss, ",") - return &value, nil - } - default: - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - return prepareList(name, val.Interface()) - } - } - } - - return nil, nil -} - -func prepareStruct(i interface{}, required bool) (*string, error) { - s, ok := i.(fmt.Stringer) - if !ok { - return nil, fmt.Errorf("struct field not a Stringer") - } - - if s == nil { - if required { - return nil, fmt.Errorf("field is required, got %#v", s) - } - } - - return prepareString(s.String(), required) -} - -func prepareEmbedStruct(i interface{}) (url.Values, error) { - return prepareValues("", i) -} - -// ExtractJSONTag returns the variable name or defaultName as well as if the field is required (!omitempty) -func ExtractJSONTag(defaultName, jsonTag string) (string, bool) { - tags := strings.Split(jsonTag, ",") - name := tags[0] - required := true - for _, tag := range tags { - if tag == "omitempty" { - required = false - } - } - - if name == "" || name == "omitempty" { - name = defaultName - } - return name, required -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/service_offerings.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/service_offerings.go deleted file mode 100644 index 8d35514..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/service_offerings.go +++ /dev/null @@ -1,77 +0,0 @@ -package egoscale - -// ServiceOffering corresponds to the Compute Offerings -// -// A service offering correspond to some hardware features (CPU, RAM). -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/service_offerings.html -type ServiceOffering struct { - Authorized bool `json:"authorized,omitempty" doc:"is the account/domain authorized to use this service offering"` - CPUNumber int `json:"cpunumber,omitempty" doc:"the number of CPU"` - CPUSpeed int `json:"cpuspeed,omitempty" doc:"the clock rate CPU speed in Mhz"` - Created string `json:"created,omitempty" doc:"the date this service offering was created"` - DefaultUse bool `json:"defaultuse,omitempty" doc:"is this a default system vm offering"` - DeploymentPlanner string `json:"deploymentplanner,omitempty" doc:"deployment strategy used to deploy VM."` - DiskBytesReadRate int64 `json:"diskBytesReadRate,omitempty" doc:"bytes read rate of the service offering"` - DiskBytesWriteRate int64 `json:"diskBytesWriteRate,omitempty" doc:"bytes write rate of the service offering"` - DiskIopsReadRate int64 `json:"diskIopsReadRate,omitempty" doc:"io requests read rate of the service offering"` - DiskIopsWriteRate int64 `json:"diskIopsWriteRate,omitempty" doc:"io requests write rate of the service offering"` - Displaytext string `json:"displaytext,omitempty" doc:"an alternate display text of the service offering."` - HostTags string `json:"hosttags,omitempty" doc:"the host tag for the service offering"` - HypervisorSnapshotReserve int `json:"hypervisorsnapshotreserve,omitempty" doc:"Hypervisor snapshot reserve space as a percent of a volume (for managed storage using Xen or VMware)"` - ID *UUID `json:"id" doc:"the id of the service offering"` - IsCustomized bool `json:"iscustomized,omitempty" doc:"is true if the offering is customized"` - IsCustomizedIops bool `json:"iscustomizediops,omitempty" doc:"true if disk offering uses custom iops, false otherwise"` - IsSystem bool `json:"issystem,omitempty" doc:"is this a system vm offering"` - IsVolatile bool `json:"isvolatile,omitempty" doc:"true if the vm needs to be volatile, i.e., on every reboot of vm from API root disk is discarded and creates a new root disk"` - LimitCPUUse bool `json:"limitcpuuse,omitempty" doc:"restrict the CPU usage to committed service offering"` - MaxIops int64 `json:"maxiops,omitempty" doc:"the max iops of the disk offering"` - Memory int `json:"memory,omitempty" doc:"the memory in MB"` - MinIops int64 `json:"miniops,omitempty" doc:"the min iops of the disk offering"` - Name string `json:"name,omitempty" doc:"the name of the service offering"` - NetworkRate int `json:"networkrate,omitempty" doc:"data transfer rate in megabits per second allowed."` - OfferHA bool `json:"offerha,omitempty" doc:"the ha support in the service offering"` - Restricted bool `json:"restricted,omitempty" doc:"is this offering restricted"` - ServiceOfferingDetails map[string]string `json:"serviceofferingdetails,omitempty" doc:"additional key/value details tied with this service offering"` - StorageType string `json:"storagetype,omitempty" doc:"the storage type for this service offering"` - SystemVMType string `json:"systemvmtype,omitempty" doc:"is this a the systemvm type for system vm offering"` - Tags string `json:"tags,omitempty" doc:"the tags for the service offering"` -} - -// ListRequest builds the ListSecurityGroups request -func (so ServiceOffering) ListRequest() (ListCommand, error) { - // Restricted cannot be applied here because it really has three states - req := &ListServiceOfferings{ - ID: so.ID, - Name: so.Name, - SystemVMType: so.SystemVMType, - } - - if so.IsSystem { - req.IsSystem = &so.IsSystem - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListServiceOfferings - -// ListServiceOfferings represents a query for service offerings -type ListServiceOfferings struct { - ID *UUID `json:"id,omitempty" doc:"ID of the service offering"` - IsSystem *bool `json:"issystem,omitempty" doc:"is this a system vm offering"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"name of the service offering"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - Restricted *bool `json:"restricted,omitempty" doc:"filter by the restriction flag: true to list only the restricted service offerings, false to list non-restricted service offerings, or nothing for all."` - SystemVMType string `json:"systemvmtype,omitempty" doc:"the system VM type. Possible types are \"consoleproxy\", \"secondarystoragevm\" or \"domainrouter\"."` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to."` - _ bool `name:"listServiceOfferings" description:"Lists all available service offerings."` -} - -// ListServiceOfferingsResponse represents a list of service offerings -type ListServiceOfferingsResponse struct { - Count int `json:"count"` - ServiceOffering []ServiceOffering `json:"serviceoffering"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/serviceofferings_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/serviceofferings_response.go deleted file mode 100644 index a01d4aa..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/serviceofferings_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListServiceOfferings) Response() interface{} { - return new(ListServiceOfferingsResponse) -} - -// ListRequest returns itself -func (ls *ListServiceOfferings) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListServiceOfferings) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListServiceOfferings) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListServiceOfferings) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListServiceOfferingsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListServiceOfferingsResponse was expected, got %T", resp)) - return - } - - for i := range items.ServiceOffering { - if !callback(&items.ServiceOffering[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/snapshots.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/snapshots.go deleted file mode 100644 index 191f4a0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/snapshots.go +++ /dev/null @@ -1,139 +0,0 @@ -package egoscale - -// SnapshotState represents the Snapshot.State enum -// -// See: https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/storage/Snapshot.java -type SnapshotState string - -const ( - // Allocated ... (TODO) - Allocated SnapshotState = "Allocated" - // Creating ... (TODO) - Creating SnapshotState = "Creating" - // CreatedOnPrimary ... (TODO) - CreatedOnPrimary SnapshotState = "CreatedOnPrimary" - // BackingUp ... (TODO) - BackingUp SnapshotState = "BackingUp" - // BackedUp ... (TODO) - BackedUp SnapshotState = "BackedUp" - // Copying ... (TODO) - Copying SnapshotState = "Copying" - // Destroying ... (TODO) - Destroying SnapshotState = "Destroying" - // Destroyed ... (TODO) - Destroyed SnapshotState = "Destroyed" - // Error is a state where the user can't see the snapshot while the snapshot may still exist on the storage - Error SnapshotState = "Error" -) - -// Snapshot represents a volume snapshot -type Snapshot struct { - Account string `json:"account,omitempty" doc:"the account associated with the snapshot"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account ID associated with the snapshot"` - Created string `json:"created,omitempty" doc:"the date the snapshot was created"` - ID *UUID `json:"id,omitempty" doc:"ID of the snapshot"` - IntervalType string `json:"intervaltype,omitempty" doc:"valid types are hourly, daily, weekly, monthy, template, and none."` - Name string `json:"name,omitempty" doc:"name of the snapshot"` - PhysicalSize int64 `json:"physicalsize,omitempty" doc:"physical size of the snapshot on image store"` - Revertable *bool `json:"revertable,omitempty" doc:"indicates whether the underlying storage supports reverting the volume to this snapshot"` - Size int64 `json:"size,omitempty" doc:"the size of original volume"` - SnapshotType string `json:"snapshottype,omitempty" doc:"the type of the snapshot"` - State string `json:"state,omitempty" doc:"the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with snapshot"` - VolumeID *UUID `json:"volumeid,omitempty" doc:"ID of the disk volume"` - VolumeName string `json:"volumename,omitempty" doc:"name of the disk volume"` - VolumeType string `json:"volumetype,omitempty" doc:"type of the disk volume"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"id of the availability zone"` -} - -// ResourceType returns the type of the resource -func (Snapshot) ResourceType() string { - return "Snapshot" -} - -// CreateSnapshot (Async) creates an instant snapshot of a volume -type CreateSnapshot struct { - VolumeID *UUID `json:"volumeid" doc:"The ID of the disk volume"` - QuiesceVM *bool `json:"quiescevm,omitempty" doc:"quiesce vm if true"` - _ bool `name:"createSnapshot" description:"Creates an instant snapshot of a volume."` -} - -// Response returns the struct to unmarshal -func (CreateSnapshot) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (CreateSnapshot) AsyncResponse() interface{} { - return new(Snapshot) -} - -// ListRequest builds the ListSnapshot request -func (ss Snapshot) ListRequest() (ListCommand, error) { - // Restricted cannot be applied here because it really has three states - req := &ListSnapshots{ - ID: ss.ID, - Name: ss.Name, - VolumeID: ss.VolumeID, - SnapshotType: ss.SnapshotType, - ZoneID: ss.ZoneID, - // TODO: tags - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListSnapshots - -// ListSnapshots lists the volume snapshots -type ListSnapshots struct { - ID *UUID `json:"id,omitempty" doc:"lists snapshot by snapshot ID"` - IntervalType string `json:"intervaltype,omitempty" doc:"valid values are HOURLY, DAILY, WEEKLY, and MONTHLY."` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"lists snapshot by snapshot name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - SnapshotType string `json:"snapshottype,omitempty" doc:"valid values are MANUAL or RECURRING."` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - VolumeID *UUID `json:"volumeid,omitempty" doc:"the ID of the disk volume"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"list snapshots by zone id"` - _ bool `name:"listSnapshots" description:"Lists all available snapshots for the account."` -} - -// ListSnapshotsResponse represents a list of volume snapshots -type ListSnapshotsResponse struct { - Count int `json:"count"` - Snapshot []Snapshot `json:"snapshot"` -} - -// DeleteSnapshot (Async) deletes a snapshot of a disk volume -type DeleteSnapshot struct { - ID *UUID `json:"id" doc:"The ID of the snapshot"` - _ bool `name:"deleteSnapshot" description:"Deletes a snapshot of a disk volume."` -} - -// Response returns the struct to unmarshal -func (DeleteSnapshot) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteSnapshot) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// RevertSnapshot (Async) reverts a volume snapshot -type RevertSnapshot struct { - ID *UUID `json:"id" doc:"The ID of the snapshot"` - _ bool `name:"revertSnapshot" description:"revert a volume snapshot."` -} - -// Response returns the struct to unmarshal -func (RevertSnapshot) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RevertSnapshot) AsyncResponse() interface{} { - return new(BooleanResponse) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/snapshots_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/snapshots_response.go deleted file mode 100644 index 2ca9cff..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/snapshots_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListSnapshots) Response() interface{} { - return new(ListSnapshotsResponse) -} - -// ListRequest returns itself -func (ls *ListSnapshots) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListSnapshots) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListSnapshots) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListSnapshots) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListSnapshotsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListSnapshotsResponse was expected, got %T", resp)) - return - } - - for i := range items.Snapshot { - if !callback(&items.Snapshot[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/ssh_keypairs.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/ssh_keypairs.go deleted file mode 100644 index 9f2bedc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/ssh_keypairs.go +++ /dev/null @@ -1,105 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" -) - -// SSHKeyPair represents an SSH key pair -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html#creating-the-ssh-keypair -type SSHKeyPair struct { - Fingerprint string `json:"fingerprint,omitempty" doc:"Fingerprint of the public key"` - Name string `json:"name,omitempty" doc:"Name of the keypair"` - PrivateKey string `json:"privatekey,omitempty" doc:"Private key"` -} - -// Delete removes the given SSH key, by Name -func (ssh SSHKeyPair) Delete(ctx context.Context, client *Client) error { - if ssh.Name == "" { - return fmt.Errorf("an SSH Key Pair may only be deleted using Name") - } - - return client.BooleanRequestWithContext(ctx, &DeleteSSHKeyPair{ - Name: ssh.Name, - }) -} - -// ListRequest builds the ListSSHKeyPairs request -func (ssh SSHKeyPair) ListRequest() (ListCommand, error) { - req := &ListSSHKeyPairs{ - Fingerprint: ssh.Fingerprint, - Name: ssh.Name, - } - - return req, nil -} - -// CreateSSHKeyPair represents a new keypair to be created -type CreateSSHKeyPair struct { - Name string `json:"name" doc:"Name of the keypair"` - _ bool `name:"createSSHKeyPair" description:"Create a new keypair and returns the private key"` -} - -// Response returns the struct to unmarshal -func (CreateSSHKeyPair) Response() interface{} { - return new(SSHKeyPair) -} - -// DeleteSSHKeyPair represents a new keypair to be created -type DeleteSSHKeyPair struct { - Name string `json:"name" doc:"Name of the keypair"` - _ bool `name:"deleteSSHKeyPair" description:"Deletes a keypair by name"` -} - -// Response returns the struct to unmarshal -func (DeleteSSHKeyPair) Response() interface{} { - return new(BooleanResponse) -} - -// RegisterSSHKeyPair represents a new registration of a public key in a keypair -type RegisterSSHKeyPair struct { - Name string `json:"name" doc:"Name of the keypair"` - PublicKey string `json:"publickey" doc:"Public key material of the keypair"` - _ bool `name:"registerSSHKeyPair" description:"Register a public key in a keypair under a certain name"` -} - -// Response returns the struct to unmarshal -func (RegisterSSHKeyPair) Response() interface{} { - return new(SSHKeyPair) -} - -//go:generate go run generate/main.go -interface=Listable ListSSHKeyPairs - -// ListSSHKeyPairs represents a query for a list of SSH KeyPairs -type ListSSHKeyPairs struct { - Fingerprint string `json:"fingerprint,omitempty" doc:"A public key fingerprint to look for"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"A key pair name to look for"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listSSHKeyPairs" description:"List registered keypairs"` -} - -// ListSSHKeyPairsResponse represents a list of SSH key pairs -type ListSSHKeyPairsResponse struct { - Count int `json:"count"` - SSHKeyPair []SSHKeyPair `json:"sshkeypair"` -} - -// ResetSSHKeyForVirtualMachine (Async) represents a change for the key pairs -type ResetSSHKeyForVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - KeyPair string `json:"keypair" doc:"Name of the ssh key pair used to login to the virtual machine"` - _ bool `name:"resetSSHKeyForVirtualMachine" description:"Resets the SSH Key for virtual machine. The virtual machine must be in a \"Stopped\" state."` -} - -// Response returns the struct to unmarshal -func (ResetSSHKeyForVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ResetSSHKeyForVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/sshkeypairs_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/sshkeypairs_response.go deleted file mode 100644 index 31c471d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/sshkeypairs_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListSSHKeyPairs) Response() interface{} { - return new(ListSSHKeyPairsResponse) -} - -// ListRequest returns itself -func (ls *ListSSHKeyPairs) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListSSHKeyPairs) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListSSHKeyPairs) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListSSHKeyPairs) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListSSHKeyPairsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListSSHKeyPairsResponse was expected, got %T", resp)) - return - } - - for i := range items.SSHKeyPair { - if !callback(&items.SSHKeyPair[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/tags.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/tags.go deleted file mode 100644 index 56e0148..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/tags.go +++ /dev/null @@ -1,84 +0,0 @@ -package egoscale - -// ResourceTag is a tag associated with a resource -// -// https://community.exoscale.com/documentation/compute/instance-tags/ -type ResourceTag struct { - Account string `json:"account,omitempty" doc:"the account associated with the tag"` - Customer string `json:"customer,omitempty" doc:"customer associated with the tag"` - Key string `json:"key,omitempty" doc:"tag key name"` - ResourceID *UUID `json:"resourceid,omitempty" doc:"id of the resource"` - ResourceType string `json:"resourcetype,omitempty" doc:"resource type"` - Value string `json:"value,omitempty" doc:"tag value"` -} - -// ListRequest builds the ListZones request -func (tag ResourceTag) ListRequest() (ListCommand, error) { - req := &ListTags{ - Customer: tag.Customer, - Key: tag.Key, - ResourceID: tag.ResourceID, - ResourceType: tag.ResourceType, - Value: tag.Value, - } - - return req, nil -} - -// CreateTags (Async) creates resource tag(s) -type CreateTags struct { - ResourceIDs []UUID `json:"resourceids" doc:"list of resources to create the tags for"` - ResourceType string `json:"resourcetype" doc:"type of the resource"` - Tags []ResourceTag `json:"tags" doc:"Map of tags (key/value pairs)"` - Customer string `json:"customer,omitempty" doc:"identifies client specific tag. When the value is not null, the tag can't be used by cloudStack code internally"` - _ bool `name:"createTags" description:"Creates resource tag(s)"` -} - -// Response returns the struct to unmarshal -func (CreateTags) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (CreateTags) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// DeleteTags (Async) deletes the resource tag(s) -type DeleteTags struct { - ResourceIDs []UUID `json:"resourceids" doc:"Delete tags for resource id(s)"` - ResourceType string `json:"resourcetype" doc:"Delete tag by resource type"` - Tags []ResourceTag `json:"tags,omitempty" doc:"Delete tags matching key/value pairs"` - _ bool `name:"deleteTags" description:"Deleting resource tag(s)"` -} - -// Response returns the struct to unmarshal -func (DeleteTags) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteTags) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListTags - -// ListTags list resource tag(s) -type ListTags struct { - Customer string `json:"customer,omitempty" doc:"list by customer name"` - Key string `json:"key,omitempty" doc:"list by key"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ResourceID *UUID `json:"resourceid,omitempty" doc:"list by resource id"` - ResourceType string `json:"resourcetype,omitempty" doc:"list by resource type"` - Value string `json:"value,omitempty" doc:"list by value"` - _ bool `name:"listTags" description:"List resource tag(s)"` -} - -// ListTagsResponse represents a list of resource tags -type ListTagsResponse struct { - Count int `json:"count"` - Tag []ResourceTag `json:"tag"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/tags_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/tags_response.go deleted file mode 100644 index 870ef49..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/tags_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListTags) Response() interface{} { - return new(ListTagsResponse) -} - -// ListRequest returns itself -func (ls *ListTags) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListTags) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListTags) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListTags) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListTagsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListTagsResponse was expected, got %T", resp)) - return - } - - for i := range items.Tag { - if !callback(&items.Tag[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/templates.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/templates.go deleted file mode 100644 index 51c077a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/templates.go +++ /dev/null @@ -1,120 +0,0 @@ -package egoscale - -// Template represents a machine to be deployed. -type Template struct { - Account string `json:"account,omitempty" doc:"the account name to which the template belongs"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account id to which the template belongs"` - Bootable bool `json:"bootable,omitempty" doc:"true if the ISO is bootable, false otherwise"` - Checksum string `json:"checksum,omitempty" doc:"checksum of the template"` - Created string `json:"created,omitempty" doc:"the date this template was created"` - CrossZones bool `json:"crossZones,omitempty" doc:"true if the template is managed across all Zones, false otherwise"` - Details map[string]string `json:"details,omitempty" doc:"additional key/value details tied with template"` - DisplayText string `json:"displaytext,omitempty" doc:"the template display text"` - Format string `json:"format,omitempty" doc:"the format of the template."` - HostID *UUID `json:"hostid,omitempty" doc:"the ID of the secondary storage host for the template"` - HostName string `json:"hostname,omitempty" doc:"the name of the secondary storage host for the template"` - ID *UUID `json:"id,omitempty" doc:"the template ID"` - IsDynamicallyScalable bool `json:"isdynamicallyscalable,omitempty" doc:"true if template contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"` - IsExtractable bool `json:"isextractable,omitempty" doc:"true if the template is extractable, false otherwise"` - IsFeatured bool `json:"isfeatured,omitempty" doc:"true if this template is a featured template, false otherwise"` - IsPublic bool `json:"ispublic,omitempty" doc:"true if this template is a public template, false otherwise"` - IsReady bool `json:"isready,omitempty" doc:"true if the template is ready to be deployed from, false otherwise."` - Name string `json:"name,omitempty" doc:"the template name"` - OsTypeID *UUID `json:"ostypeid,omitempty" doc:"the ID of the OS type for this template."` - OsTypeName string `json:"ostypename,omitempty" doc:"the name of the OS type for this template."` - PasswordEnabled bool `json:"passwordenabled,omitempty" doc:"true if the reset password feature is enabled, false otherwise"` - Removed string `json:"removed,omitempty" doc:"the date this template was removed"` - Size int64 `json:"size,omitempty" doc:"the size of the template"` - SourceTemplateID *UUID `json:"sourcetemplateid,omitempty" doc:"the template ID of the parent template if present"` - SSHKeyEnabled bool `json:"sshkeyenabled,omitempty" doc:"true if template is sshkey enabled, false otherwise"` - Status string `json:"status,omitempty" doc:"the status of the template"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with tempate"` - TemplateDirectory string `json:"templatedirectory,omitempty" doc:"Template directory"` - TemplateTag string `json:"templatetag,omitempty" doc:"the tag of this template"` - TemplateType string `json:"templatetype,omitempty" doc:"the type of the template"` - URL string `json:"url,omitempty" doc:"Original URL of the template where it was downloaded"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the zone for this template"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the zone for this template"` -} - -// ResourceType returns the type of the resource -func (Template) ResourceType() string { - return "Template" -} - -// ListRequest builds the ListTemplates request -func (template Template) ListRequest() (ListCommand, error) { - req := &ListTemplates{ - ID: template.ID, - Name: template.Name, - ZoneID: template.ZoneID, - } - if template.IsFeatured { - req.TemplateFilter = "featured" - } - if template.Removed != "" { - *req.ShowRemoved = true - } - - for i := range template.Tags { - req.Tags = append(req.Tags, template.Tags[i]) - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListTemplates - -// ListTemplates represents a template query filter -type ListTemplates struct { - TemplateFilter string `json:"templatefilter" doc:"Possible values are \"featured\", \"self\", \"selfexecutable\",\"sharedexecutable\",\"executable\", and \"community\". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured."` - ID *UUID `json:"id,omitempty" doc:"the template ID"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"the template name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ShowRemoved *bool `json:"showremoved,omitempty" doc:"Show removed templates as well"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"list templates by zoneid"` - _ bool `name:"listTemplates" description:"List all public, private, and privileged templates."` -} - -// ListTemplatesResponse represents a list of templates -type ListTemplatesResponse struct { - Count int `json:"count"` - Template []Template `json:"template"` -} - -// OSCategory represents an OS category -type OSCategory struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the OS category"` - Name string `json:"name,omitempty" doc:"the name of the OS category"` -} - -// ListRequest builds the ListOSCategories request -func (osCat OSCategory) ListRequest() (ListCommand, error) { - req := &ListOSCategories{ - Name: osCat.Name, - ID: osCat.ID, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListOSCategories - -// ListOSCategories lists the OS categories -type ListOSCategories struct { - ID *UUID `json:"id,omitempty" doc:"list Os category by id"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"list os category by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listOsCategories" description:"Lists all supported OS categories for this cloud."` -} - -// ListOSCategoriesResponse represents a list of OS categories -type ListOSCategoriesResponse struct { - Count int `json:"count"` - OSCategory []OSCategory `json:"oscategory"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/templates_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/templates_response.go deleted file mode 100644 index b9d61b5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/templates_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListTemplates) Response() interface{} { - return new(ListTemplatesResponse) -} - -// ListRequest returns itself -func (ls *ListTemplates) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListTemplates) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListTemplates) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListTemplates) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListTemplatesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListTemplatesResponse was expected, got %T", resp)) - return - } - - for i := range items.Template { - if !callback(&items.Template[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/users.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/users.go deleted file mode 100644 index 71078a9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/users.go +++ /dev/null @@ -1,63 +0,0 @@ -package egoscale - -// User represents a User -type User struct { - APIKey string `json:"apikey,omitempty" doc:"the api key of the user"` - Account string `json:"account,omitempty" doc:"the account name of the user"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account ID of the user"` - Created string `json:"created,omitempty" doc:"the date and time the user account was created"` - Email string `json:"email,omitempty" doc:"the user email address"` - FirstName string `json:"firstname,omitempty" doc:"the user firstname"` - ID *UUID `json:"id,omitempty" doc:"the user ID"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if user is default, false otherwise"` - LastName string `json:"lastname,omitempty" doc:"the user lastname"` - RoleID *UUID `json:"roleid,omitempty" doc:"the ID of the role"` - RoleName string `json:"rolename,omitempty" doc:"the name of the role"` - RoleType string `json:"roletype,omitempty" doc:"the type of the role"` - SecretKey string `json:"secretkey,omitempty" doc:"the secret key of the user"` - State string `json:"state,omitempty" doc:"the user state"` - Timezone string `json:"timezone,omitempty" doc:"the timezone user was created in"` - UserName string `json:"username,omitempty" doc:"the user name"` -} - -// ListRequest builds the ListUsers request -func (user User) ListRequest() (ListCommand, error) { - req := &ListUsers{ - ID: user.ID, - UserName: user.UserName, - } - - return req, nil -} - -// RegisterUserKeys registers a new set of key of the given user -// -// NB: only the APIKey and SecretKey will be filled -type RegisterUserKeys struct { - ID *UUID `json:"id" doc:"User id"` - _ bool `name:"registerUserKeys" description:"This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user"` -} - -// Response returns the struct to unmarshal -func (RegisterUserKeys) Response() interface{} { - return new(User) -} - -//go:generate go run generate/main.go -interface=Listable ListUsers - -// ListUsers represents the search for Users -type ListUsers struct { - ID *UUID `json:"id,omitempty" doc:"List user by ID."` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - State string `json:"state,omitempty" doc:"List users by state of the user account."` - UserName string `json:"username,omitempty" doc:"List user by the username"` - _ bool `name:"listUsers" description:"Lists user accounts"` -} - -// ListUsersResponse represents a list of users -type ListUsersResponse struct { - Count int `json:"count"` - User []User `json:"user"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/users_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/users_response.go deleted file mode 100644 index 4bd4bf4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/users_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListUsers) Response() interface{} { - return new(ListUsersResponse) -} - -// ListRequest returns itself -func (ls *ListUsers) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListUsers) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListUsers) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListUsers) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListUsersResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListUsersResponse was expected, got %T", resp)) - return - } - - for i := range items.User { - if !callback(&items.User[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/uuid.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/uuid.go deleted file mode 100644 index 839f4d2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/uuid.go +++ /dev/null @@ -1,79 +0,0 @@ -package egoscale - -import ( - "encoding/json" - "fmt" - - uuid "github.com/satori/go.uuid" -) - -// UUID holds a UUID v4 -type UUID struct { - uuid.UUID -} - -// DeepCopy create a true copy of the receiver. -func (u *UUID) DeepCopy() *UUID { - if u == nil { - return nil - } - - out := [uuid.Size]byte{} - copy(out[:], u.Bytes()) - - return &UUID{ - (uuid.UUID)(out), - } -} - -// DeepCopyInto copies the receiver into out. -// -// In must be non nil. -func (u *UUID) DeepCopyInto(out *UUID) { - o := [uuid.Size]byte{} - copy(o[:], u.Bytes()) - - out.UUID = (uuid.UUID)(o) -} - -// Equal returns true if itself is equal to other. -func (u UUID) Equal(other UUID) bool { - return uuid.Equal(u.UUID, other.UUID) -} - -// UnmarshalJSON unmarshals the raw JSON into the UUID. -func (u *UUID) UnmarshalJSON(b []byte) error { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - - new, err := ParseUUID(s) - if err == nil { - u.UUID = new.UUID - } - return err -} - -// MarshalJSON converts the UUID to a string representation. -func (u UUID) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("%q", u.String())), nil -} - -// ParseUUID parses a string into a UUID. -func ParseUUID(s string) (*UUID, error) { - u, err := uuid.FromString(s) - if err != nil { - return nil, err - } - return &UUID{u}, nil -} - -// MustParseUUID acts like ParseUUID but panic in case of a failure. -func MustParseUUID(s string) *UUID { - u, e := ParseUUID(s) - if e != nil { - panic(e) - } - return u -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/version.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/version.go deleted file mode 100644 index dad9ea9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package egoscale - -// Version of the library -const Version = "0.14.0" diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/virtual_machines.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/virtual_machines.go deleted file mode 100644 index a88b1cb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/virtual_machines.go +++ /dev/null @@ -1,612 +0,0 @@ -package egoscale - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "io/ioutil" - "net" - "net/url" -) - -// VirtualMachineState holds the state of the instance -// -// https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/vm/VirtualMachine.java -type VirtualMachineState string - -const ( - // VirtualMachineStarting VM is being started. At this state, you should find host id filled which means it's being started on that host - VirtualMachineStarting VirtualMachineState = "Starting" - // VirtualMachineRunning VM is running. host id has the host that it is running on - VirtualMachineRunning VirtualMachineState = "Running" - // VirtualMachineStopping VM is being stopped. host id has the host that it is being stopped on - VirtualMachineStopping VirtualMachineState = "Stopping" - // VirtualMachineStopped VM is stopped. host id should be null - VirtualMachineStopped VirtualMachineState = "Stopped" - // VirtualMachineDestroyed VM is marked for destroy - VirtualMachineDestroyed VirtualMachineState = "Destroyed" - // VirtualMachineExpunging "VM is being expunged - VirtualMachineExpunging VirtualMachineState = "Expunging" - // VirtualMachineMigrating VM is being live migrated. host id holds destination host, last host id holds source host - VirtualMachineMigrating VirtualMachineState = "Migrating" - // VirtualMachineMoving VM is being migrated offline (volume is being moved). - VirtualMachineMoving VirtualMachineState = "Moving" - // VirtualMachineError VM is in error - VirtualMachineError VirtualMachineState = "Error" - // VirtualMachineUnknown VM state is unknown - VirtualMachineUnknown VirtualMachineState = "Unknown" - // VirtualMachineShutdowned VM is shutdowned from inside - VirtualMachineShutdowned VirtualMachineState = "Shutdowned" -) - -// VirtualMachine represents a virtual machine -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html -type VirtualMachine struct { - Account string `json:"account,omitempty" doc:"the account associated with the virtual machine"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account ID associated with the virtual machine"` - AffinityGroup []AffinityGroup `json:"affinitygroup,omitempty" doc:"list of affinity groups associated with the virtual machine"` - ClusterID *UUID `json:"clusterid,omitempty" doc:"the ID of the vm's cluster"` - ClusterName string `json:"clustername,omitempty" doc:"the name of the vm's cluster"` - CPUNumber int `json:"cpunumber,omitempty" doc:"the number of cpu this virtual machine is running with"` - CPUSpeed int `json:"cpuspeed,omitempty" doc:"the speed of each cpu"` - CPUUsed string `json:"cpuused,omitempty" doc:"the amount of the vm's CPU currently used"` - Created string `json:"created,omitempty" doc:"the date when this virtual machine was created"` - Details map[string]string `json:"details,omitempty" doc:"Vm details in key/value pairs."` - DiskIoRead int64 `json:"diskioread,omitempty" doc:"the read (io) of disk on the vm"` - DiskIoWrite int64 `json:"diskiowrite,omitempty" doc:"the write (io) of disk on the vm"` - DiskKbsRead int64 `json:"diskkbsread,omitempty" doc:"the read (bytes) of disk on the vm"` - DiskKbsWrite int64 `json:"diskkbswrite,omitempty" doc:"the write (bytes) of disk on the vm"` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"the ID of the disk offering of the virtual machine"` - DiskOfferingName string `json:"diskofferingname,omitempty" doc:"the name of the disk offering of the virtual machine"` - DisplayName string `json:"displayname,omitempty" doc:"user generated name. The name of the virtual machine is returned if no displayname exists."` - ForVirtualNetwork bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the service offering"` - Group string `json:"group,omitempty" doc:"the group name of the virtual machine"` - GroupID *UUID `json:"groupid,omitempty" doc:"the group ID of the virtual machine"` - HAEnable bool `json:"haenable,omitempty" doc:"true if high-availability is enabled, false otherwise"` - HostName string `json:"hostname,omitempty" doc:"the name of the host for the virtual machine"` - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - InstanceName string `json:"instancename,omitempty" doc:"instance name of the user vm; this parameter is returned to the ROOT admin only"` - IsoDisplayText string `json:"isodisplaytext,omitempty" doc:"an alternate display text of the ISO attached to the virtual machine"` - IsoID *UUID `json:"isoid,omitempty" doc:"the ID of the ISO attached to the virtual machine"` - IsoName string `json:"isoname,omitempty" doc:"the name of the ISO attached to the virtual machine"` - KeyPair string `json:"keypair,omitempty" doc:"ssh key-pair"` - Memory int `json:"memory,omitempty" doc:"the memory allocated for the virtual machine"` - Name string `json:"name,omitempty" doc:"the name of the virtual machine"` - NetworkKbsRead int64 `json:"networkkbsread,omitempty" doc:"the incoming network traffic on the vm"` - NetworkKbsWrite int64 `json:"networkkbswrite,omitempty" doc:"the outgoing network traffic on the host"` - Nic []Nic `json:"nic,omitempty" doc:"the list of nics associated with vm"` - OSCategoryID *UUID `json:"oscategoryid,omitempty" doc:"Os category ID of the virtual machine"` - OSCategoryName string `json:"oscategoryname,omitempty" doc:"Os category name of the virtual machine"` - OSTypeID *UUID `json:"ostypeid,omitempty" doc:"OS type id of the vm"` - Password string `json:"password,omitempty" doc:"the password (if exists) of the virtual machine"` - PasswordEnabled bool `json:"passwordenabled,omitempty" doc:"true if the password rest feature is enabled, false otherwise"` - PCIDevices []PCIDevice `json:"pcidevices,omitempty" doc:"list of PCI devices"` - PodID *UUID `json:"podid,omitempty" doc:"the ID of the vm's pod"` - PodName string `json:"podname,omitempty" doc:"the name of the vm's pod"` - PublicIP string `json:"publicip,omitempty" doc:"public IP address id associated with vm via Static nat rule"` - PublicIPID *UUID `json:"publicipid,omitempty" doc:"public IP address id associated with vm via Static nat rule"` - RootDeviceID int64 `json:"rootdeviceid,omitempty" doc:"device ID of the root volume"` - RootDeviceType string `json:"rootdevicetype,omitempty" doc:"device type of the root volume"` - SecurityGroup []SecurityGroup `json:"securitygroup,omitempty" doc:"list of security groups associated with the virtual machine"` - ServiceOfferingID *UUID `json:"serviceofferingid,omitempty" doc:"the ID of the service offering of the virtual machine"` - ServiceOfferingName string `json:"serviceofferingname,omitempty" doc:"the name of the service offering of the virtual machine"` - ServiceState string `json:"servicestate,omitempty" doc:"State of the Service from LB rule"` - State string `json:"state,omitempty" doc:"the state of the virtual machine"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with vm"` - TemplateDisplayText string `json:"templatedisplaytext,omitempty" doc:"an alternate display text of the template for the virtual machine"` - TemplateID *UUID `json:"templateid,omitempty" doc:"the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."` - TemplateName string `json:"templatename,omitempty" doc:"the name of the template for the virtual machine"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the availablility zone for the virtual machine"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the availability zone for the virtual machine"` -} - -// ResourceType returns the type of the resource -func (VirtualMachine) ResourceType() string { - return "UserVM" -} - -// Delete destroys the VM -func (vm VirtualMachine) Delete(ctx context.Context, client *Client) error { - _, err := client.RequestWithContext(ctx, &DestroyVirtualMachine{ - ID: vm.ID, - }) - - return err -} - -// ListRequest builds the ListVirtualMachines request -func (vm VirtualMachine) ListRequest() (ListCommand, error) { - // XXX: AffinityGroupID, SecurityGroupID - - req := &ListVirtualMachines{ - GroupID: vm.GroupID, - ID: vm.ID, - Name: vm.Name, - State: vm.State, - TemplateID: vm.TemplateID, - ZoneID: vm.ZoneID, - } - - nic := vm.DefaultNic() - if nic != nil { - req.IPAddress = nic.IPAddress - } - - for i := range vm.Tags { - req.Tags = append(req.Tags, vm.Tags[i]) - } - - return req, nil -} - -// DefaultNic returns the default nic -func (vm VirtualMachine) DefaultNic() *Nic { - for i, nic := range vm.Nic { - if nic.IsDefault { - return &vm.Nic[i] - } - } - - return nil -} - -// IP returns the default nic IP address -func (vm VirtualMachine) IP() *net.IP { - nic := vm.DefaultNic() - if nic != nil { - ip := nic.IPAddress - return &ip - } - - return nil -} - -// NicsByType returns the corresponding interfaces base on the given type -func (vm VirtualMachine) NicsByType(nicType string) []Nic { - nics := make([]Nic, 0) - for _, nic := range vm.Nic { - if nic.Type == nicType { - // XXX The API forgets to specify it - n := nic - n.VirtualMachineID = vm.ID - nics = append(nics, n) - } - } - return nics -} - -// NicByNetworkID returns the corresponding interface based on the given NetworkID -// -// A VM cannot be connected twice to a same network. -func (vm VirtualMachine) NicByNetworkID(networkID UUID) *Nic { - for _, nic := range vm.Nic { - if nic.NetworkID.Equal(networkID) { - n := nic - n.VirtualMachineID = vm.ID - return &n - } - } - return nil -} - -// NicByID returns the corresponding interface base on its ID -func (vm VirtualMachine) NicByID(nicID UUID) *Nic { - for _, nic := range vm.Nic { - if nic.ID.Equal(nicID) { - n := nic - n.VirtualMachineID = vm.ID - return &n - } - } - - return nil -} - -// IPToNetwork represents a mapping between ip and networks -type IPToNetwork struct { - IP net.IP `json:"ip,omitempty"` - Ipv6 net.IP `json:"ipv6,omitempty"` - NetworkID *UUID `json:"networkid,omitempty"` -} - -// PCIDevice represents a PCI card present in the host -type PCIDevice struct { - PCIVendorName string `json:"pcivendorname,omitempty" doc:"Device vendor name of pci card"` - DeviceID string `json:"deviceid,omitempty" doc:"Device model ID of pci card"` - RemainingCapacity int `json:"remainingcapacity,omitempty" doc:"Remaining capacity in terms of no. of more VMs that can be deployped with this vGPU type"` - MaxCapacity int `json:"maxcapacity,omitempty" doc:"Maximum vgpu can be created with this vgpu type on the given pci group"` - PCIVendorID string `json:"pcivendorid,omitempty" doc:"Device vendor ID of pci card"` - PCIDeviceName string `json:"pcidevicename,omitempty" doc:"Device model name of pci card"` -} - -// Password represents an encrypted password -// -// TODO: method to decrypt it, https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=34014652 -type Password struct { - EncryptedPassword string `json:"encryptedpassword"` -} - -// VirtualMachineUserData represents the base64 encoded user-data -type VirtualMachineUserData struct { - UserData string `json:"userdata" doc:"Base 64 encoded VM user data"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"the ID of the virtual machine"` -} - -// Decode decodes as a readable string the content of the user-data (base64 · gzip) -func (userdata VirtualMachineUserData) Decode() (string, error) { - data, err := base64.StdEncoding.DecodeString(userdata.UserData) - if err != nil { - return "", err - } - // 0x1f8b is the magic number for gzip - if len(data) < 2 || data[0] != 0x1f || data[1] != 0x8b { - return string(data), nil - } - gr, err := gzip.NewReader(bytes.NewBuffer(data)) - if err != nil { - return "", err - } - defer gr.Close() // nolint: errcheck - - str, err := ioutil.ReadAll(gr) - if err != nil { - return "", err - } - return string(str), nil -} - -// DeployVirtualMachine (Async) represents the machine creation -// -// Regarding the UserData field, the client is responsible to base64 (and probably gzip) it. Doing it within this library would make the integration with other tools, e.g. Terraform harder. -type DeployVirtualMachine struct { - AffinityGroupIDs []UUID `json:"affinitygroupids,omitempty" doc:"comma separated list of affinity groups id that are going to be applied to the virtual machine. Mutually exclusive with affinitygroupnames parameter"` - AffinityGroupNames []string `json:"affinitygroupnames,omitempty" doc:"comma separated list of affinity groups names that are going to be applied to the virtual machine.Mutually exclusive with affinitygroupids parameter"` - Details map[string]string `json:"details,omitempty" doc:"used to specify the custom parameters."` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskofferingid is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateid parameter passed is from a Template object, the diskofferingid refers to a DATA Disk Volume created. If the templateid parameter passed is from an ISO object, the diskofferingid refers to a ROOT Disk Volume created."` - DisplayName string `json:"displayname,omitempty" doc:"an optional user generated name for the virtual machine"` - Group string `json:"group,omitempty" doc:"an optional group for the virtual machine"` - IP4 *bool `json:"ip4,omitempty" doc:"True to set an IPv4 to the default interface"` - IP6 *bool `json:"ip6,omitempty" doc:"True to set an IPv6 to the default interface"` - IP6Address net.IP `json:"ip6address,omitempty" doc:"the ipv6 address for default vm's network"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"the ip address for default vm's network"` - Keyboard string `json:"keyboard,omitempty" doc:"an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us"` - KeyPair string `json:"keypair,omitempty" doc:"name of the ssh key pair used to login to the virtual machine"` - Name string `json:"name,omitempty" doc:"host name for the virtual machine"` - NetworkIDs []UUID `json:"networkids,omitempty" doc:"list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter"` - RootDiskSize int64 `json:"rootdisksize,omitempty" doc:"Optional field to resize root disk on deploy. Value is in GB. Only applies to template-based deployments. Analogous to details[0].rootdisksize, which takes precedence over this parameter if both are provided"` - SecurityGroupIDs []UUID `json:"securitygroupids,omitempty" doc:"comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter"` - SecurityGroupNames []string `json:"securitygroupnames,omitempty" doc:"comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter"` - ServiceOfferingID *UUID `json:"serviceofferingid" doc:"the ID of the service offering for the virtual machine"` - Size int64 `json:"size,omitempty" doc:"the arbitrary size for the DATADISK volume. Mutually exclusive with diskofferingid"` - StartVM *bool `json:"startvm,omitempty" doc:"true if start vm after creating. Default value is true"` - TemplateID *UUID `json:"templateid" doc:"the ID of the template for the virtual machine"` - UserData string `json:"userdata,omitempty" doc:"an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding."` - ZoneID *UUID `json:"zoneid" doc:"availability zone for the virtual machine"` - _ bool `name:"deployVirtualMachine" description:"Creates and automatically starts a virtual machine based on a service offering, disk offering, and template."` -} - -func (req DeployVirtualMachine) onBeforeSend(_ url.Values) error { - // Either AffinityGroupIDs or AffinityGroupNames must be set - if len(req.AffinityGroupIDs) > 0 && len(req.AffinityGroupNames) > 0 { - return fmt.Errorf("either AffinityGroupIDs or AffinityGroupNames must be set") - } - - // Either SecurityGroupIDs or SecurityGroupNames must be set - if len(req.SecurityGroupIDs) > 0 && len(req.SecurityGroupNames) > 0 { - return fmt.Errorf("either SecurityGroupIDs or SecurityGroupNames must be set") - } - - return nil -} - -// Response returns the struct to unmarshal -func (DeployVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeployVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// StartVirtualMachine (Async) represents the creation of the virtual machine -type StartVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"startVirtualMachine" description:"Starts a virtual machine."` -} - -// Response returns the struct to unmarshal -func (StartVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (StartVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// StopVirtualMachine (Async) represents the stopping of the virtual machine -type StopVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - Forced *bool `json:"forced,omitempty" doc:"Force stop the VM (vm is marked as Stopped even when command fails to be send to the backend). The caller knows the VM is stopped."` - _ bool `name:"stopVirtualMachine" description:"Stops a virtual machine."` -} - -// Response returns the struct to unmarshal -func (StopVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (StopVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RebootVirtualMachine (Async) represents the rebooting of the virtual machine -type RebootVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"rebootVirtualMachine" description:"Reboots a virtual machine."` -} - -// Response returns the struct to unmarshal -func (RebootVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RebootVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RestoreVirtualMachine (Async) represents the restoration of the virtual machine -type RestoreVirtualMachine struct { - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - TemplateID *UUID `json:"templateid,omitempty" doc:"an optional template Id to restore vm from the new template. This can be an ISO id in case of restore vm deployed using ISO"` - RootDiskSize int64 `json:"rootdisksize,omitempty" doc:"Optional field to resize root disk on restore. Value is in GB. Only applies to template-based deployments."` - _ bool `name:"restoreVirtualMachine" description:"Restore a VM to original template/ISO or new template/ISO"` -} - -// Response returns the struct to unmarshal -func (RestoreVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RestoreVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RecoverVirtualMachine represents the restoration of the virtual machine -type RecoverVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"recoverVirtualMachine" description:"Recovers a virtual machine."` -} - -// Response returns the struct to unmarshal -func (RecoverVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// DestroyVirtualMachine (Async) represents the destruction of the virtual machine -type DestroyVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"destroyVirtualMachine" description:"Destroys a virtual machine."` -} - -// Response returns the struct to unmarshal -func (DestroyVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DestroyVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// UpdateVirtualMachine represents the update of the virtual machine -type UpdateVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - Details map[string]string `json:"details,omitempty" doc:"Details in key/value pairs."` - DisplayName string `json:"displayname,omitempty" doc:"user generated name"` - Group string `json:"group,omitempty" doc:"group of the virtual machine"` - Name string `json:"name,omitempty" doc:"new host name of the vm. The VM has to be stopped/started for this update to take affect"` - SecurityGroupIDs []UUID `json:"securitygroupids,omitempty" doc:"list of security group ids to be applied on the virtual machine."` - UserData string `json:"userdata,omitempty" doc:"an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding."` - _ bool `name:"updateVirtualMachine" description:"Updates properties of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. Therefore, stop the VM manually before issuing this call."` -} - -// Response returns the struct to unmarshal -func (UpdateVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// ExpungeVirtualMachine represents the annihilation of a VM -type ExpungeVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"expungeVirtualMachine" description:"Expunge a virtual machine. Once expunged, it cannot be recoverd."` -} - -// Response returns the struct to unmarshal -func (ExpungeVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ExpungeVirtualMachine) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// ScaleVirtualMachine (Async) scales the virtual machine to a new service offering. -// -// ChangeServiceForVirtualMachine does the same thing but returns the -// new Virtual Machine which is more consistent with the rest of the API. -type ScaleVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - ServiceOfferingID *UUID `json:"serviceofferingid" doc:"the ID of the service offering for the virtual machine"` - Details map[string]string `json:"details,omitempty" doc:"name value pairs of custom parameters for cpu,memory and cpunumber. example details[i].name=value"` - _ bool `name:"scaleVirtualMachine" description:"Scales the virtual machine to a new service offering."` -} - -// Response returns the struct to unmarshal -func (ScaleVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ScaleVirtualMachine) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// ChangeServiceForVirtualMachine changes the service offering for a virtual machine. The virtual machine must be in a "Stopped" state for this command to take effect. -type ChangeServiceForVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - ServiceOfferingID *UUID `json:"serviceofferingid" doc:"the service offering ID to apply to the virtual machine"` - Details map[string]string `json:"details,omitempty" doc:"name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value"` - _ bool `name:"changeServiceForVirtualMachine" description:"Changes the service offering for a virtual machine. The virtual machine must be in a \"Stopped\" state for this command to take effect."` -} - -// Response returns the struct to unmarshal -func (ChangeServiceForVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// ResetPasswordForVirtualMachine resets the password for virtual machine. The virtual machine must be in a "Stopped" state... -type ResetPasswordForVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"resetPasswordForVirtualMachine" description:"Resets the password for virtual machine. The virtual machine must be in a \"Stopped\" state and the template must already support this feature for this command to take effect."` -} - -// Response returns the struct to unmarshal -func (ResetPasswordForVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ResetPasswordForVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// GetVMPassword asks for an encrypted password -type GetVMPassword struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"getVMPassword" description:"Returns an encrypted password for the VM"` -} - -// Response returns the struct to unmarshal -func (GetVMPassword) Response() interface{} { - return new(Password) -} - -//go:generate go run generate/main.go -interface=Listable ListVirtualMachines - -// ListVirtualMachines represents a search for a VM -type ListVirtualMachines struct { - AffinityGroupID *UUID `json:"affinitygroupid,omitempty" doc:"list vms by affinity group"` - Details []string `json:"details,omitempty" doc:"comma separated list of host details requested, value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp]. If no parameter is passed in, the details will be defaulted to all"` - ForVirtualNetwork *bool `json:"forvirtualnetwork,omitempty" doc:"list by network type; true if need to list vms using Virtual Network, false otherwise"` - GroupID *UUID `json:"groupid,omitempty" doc:"the group ID"` - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - IDs []string `json:"ids,omitempty" doc:"the IDs of the virtual machines, mutually exclusive with id"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"an IP address to filter the result"` - IsoID *UUID `json:"isoid,omitempty" doc:"list vms by iso"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"name of the virtual machine"` - NetworkID *UUID `json:"networkid,omitempty" doc:"list by network id"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ServiceOfferindID *UUID `json:"serviceofferingid,omitempty" doc:"list by the service offering"` - State string `json:"state,omitempty" doc:"state of the virtual machine"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - TemplateID *UUID `json:"templateid,omitempty" doc:"list vms by template"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the availability zone ID"` - _ bool `name:"listVirtualMachines" description:"List the virtual machines owned by the account."` -} - -// ListVirtualMachinesResponse represents a list of virtual machines -type ListVirtualMachinesResponse struct { - Count int `json:"count"` - VirtualMachine []VirtualMachine `json:"virtualmachine"` -} - -// AddNicToVirtualMachine (Async) adds a NIC to a VM -type AddNicToVirtualMachine struct { - NetworkID *UUID `json:"networkid" doc:"Network ID"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Static IP address lease for the corresponding NIC and network which should be in the range defined in the network"` - _ bool `name:"addNicToVirtualMachine" description:"Adds VM to specified network by creating a NIC"` -} - -// Response returns the struct to unmarshal -func (AddNicToVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AddNicToVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RemoveNicFromVirtualMachine (Async) removes a NIC from a VM -type RemoveNicFromVirtualMachine struct { - NicID *UUID `json:"nicid" doc:"NIC ID"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - _ bool `name:"removeNicFromVirtualMachine" description:"Removes VM from specified network by deleting a NIC"` -} - -// Response returns the struct to unmarshal -func (RemoveNicFromVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RemoveNicFromVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// UpdateDefaultNicForVirtualMachine (Async) adds a NIC to a VM -type UpdateDefaultNicForVirtualMachine struct { - NicID *UUID `json:"nicid" doc:"NIC ID"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - _ bool `name:"updateDefaultNicForVirtualMachine" description:"Changes the default NIC on a VM"` -} - -// Response returns the struct to unmarshal -func (UpdateDefaultNicForVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateDefaultNicForVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// GetVirtualMachineUserData returns the user-data of the given VM -type GetVirtualMachineUserData struct { - VirtualMachineID *UUID `json:"virtualmachineid" doc:"The ID of the virtual machine"` - _ bool `name:"getVirtualMachineUserData" description:"Returns user data associated with the VM"` -} - -// Response returns the struct to unmarshal -func (GetVirtualMachineUserData) Response() interface{} { - return new(VirtualMachineUserData) -} - -// UpdateVMNicIP updates the default IP address of a VM Nic -type UpdateVMNicIP struct { - _ bool `name:"updateVmNicIp" description:"Update the default Ip of a VM Nic"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Static IP address lease for the corresponding NIC and network which should be in the range defined in the network. If absent, the call removes the lease associated with the nic."` - NicID *UUID `json:"nicid" doc:"the ID of the nic."` -} - -// Response returns the struct to unmarshal -func (UpdateVMNicIP) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateVMNicIP) AsyncResponse() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/virtualmachines_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/virtualmachines_response.go deleted file mode 100644 index 9aafb01..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/virtualmachines_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListVirtualMachines) Response() interface{} { - return new(ListVirtualMachinesResponse) -} - -// ListRequest returns itself -func (ls *ListVirtualMachines) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListVirtualMachines) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListVirtualMachines) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListVirtualMachines) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListVirtualMachinesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListVirtualMachinesResponse was expected, got %T", resp)) - return - } - - for i := range items.VirtualMachine { - if !callback(&items.VirtualMachine[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/volumes.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/volumes.go deleted file mode 100644 index f942890..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/volumes.go +++ /dev/null @@ -1,113 +0,0 @@ -package egoscale - -// Volume represents a volume linked to a VM -type Volume struct { - Account string `json:"account,omitempty" doc:"the account associated with the disk volume"` - Attached string `json:"attached,omitempty" doc:"the date the volume was attached to a VM instance"` - ChainInfo string `json:"chaininfo,omitempty" doc:"the chain info of the volume"` - ClusterID *UUID `json:"clusterid,omitempty" doc:"ID of the cluster"` - ClusterName string `json:"clustername,omitempty" doc:"name of the cluster"` - Created string `json:"created,omitempty" doc:"the date the disk volume was created"` - Destroyed bool `json:"destroyed,omitempty" doc:"the boolean state of whether the volume is destroyed or not"` - DeviceID int64 `json:"deviceid,omitempty" doc:"the ID of the device on user vm the volume is attahed to. This tag is not returned when the volume is detached."` - DiskBytesReadRate int64 `json:"diskBytesReadRate,omitempty" doc:"bytes read rate of the disk volume"` - DiskBytesWriteRate int64 `json:"diskBytesWriteRate,omitempty" doc:"bytes write rate of the disk volume"` - DiskIopsReadRate int64 `json:"diskIopsReadRate,omitempty" doc:"io requests read rate of the disk volume"` - DiskIopsWriteRate int64 `json:"diskIopsWriteRate,omitempty" doc:"io requests write rate of the disk volume"` - DiskOfferingDisplayText string `json:"diskofferingdisplaytext,omitempty" doc:"the display text of the disk offering"` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"ID of the disk offering"` - DiskOfferingName string `json:"diskofferingname,omitempty" doc:"name of the disk offering"` - DisplayVolume bool `json:"displayvolume,omitempty" doc:"an optional field whether to the display the volume to the end user or not."` - Hypervisor string `json:"hypervisor,omitempty" doc:"Hypervisor the volume belongs to"` - ID *UUID `json:"id,omitempty" doc:"ID of the disk volume"` - IsExtractable *bool `json:"isextractable,omitempty" doc:"true if the volume is extractable, false otherwise"` - IsoDisplayText string `json:"isodisplaytext,omitempty" doc:"an alternate display text of the ISO attached to the virtual machine"` - IsoID *UUID `json:"isoid,omitempty" doc:"the ID of the ISO attached to the virtual machine"` - IsoName string `json:"isoname,omitempty" doc:"the name of the ISO attached to the virtual machine"` - MaxIops int64 `json:"maxiops,omitempty" doc:"max iops of the disk volume"` - MinIops int64 `json:"miniops,omitempty" doc:"min iops of the disk volume"` - Name string `json:"name,omitempty" doc:"name of the disk volume"` - Path string `json:"path,omitempty" doc:"the path of the volume"` - PodID *UUID `json:"podid,omitempty" doc:"ID of the pod"` - PodName string `json:"podname,omitempty" doc:"name of the pod"` - QuiesceVM bool `json:"quiescevm,omitempty" doc:"need quiesce vm or not when taking snapshot"` - ServiceOfferingDisplayText string `json:"serviceofferingdisplaytext,omitempty" doc:"the display text of the service offering for root disk"` - ServiceOfferingID *UUID `json:"serviceofferingid,omitempty" doc:"ID of the service offering for root disk"` - ServiceOfferingName string `json:"serviceofferingname,omitempty" doc:"name of the service offering for root disk"` - Size uint64 `json:"size,omitempty" doc:"size of the disk volume"` - SnapshotID *UUID `json:"snapshotid,omitempty" doc:"ID of the snapshot from which this volume was created"` - State string `json:"state,omitempty" doc:"the state of the disk volume"` - Status string `json:"status,omitempty" doc:"the status of the volume"` - Storage string `json:"storage,omitempty" doc:"name of the primary storage hosting the disk volume"` - StorageID *UUID `json:"storageid,omitempty" doc:"id of the primary storage hosting the disk volume; returned to admin user only"` - StorageType string `json:"storagetype,omitempty" doc:"shared or local storage"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with volume"` - TemplateDisplayText string `json:"templatedisplaytext,omitempty" doc:"an alternate display text of the template for the virtual machine"` - TemplateID *UUID `json:"templateid,omitempty" doc:"the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."` // no *UUID because of the -1 thingy... - TemplateName string `json:"templatename,omitempty" doc:"the name of the template for the virtual machine"` - Type string `json:"type,omitempty" doc:"type of the disk volume (ROOT or DATADISK)"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"id of the virtual machine"` - VMDisplayName string `json:"vmdisplayname,omitempty" doc:"display name of the virtual machine"` - VMName string `json:"vmname,omitempty" doc:"name of the virtual machine"` - VMState string `json:"vmstate,omitempty" doc:"state of the virtual machine"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"ID of the availability zone"` - ZoneName string `json:"zonename,omitempty" doc:"name of the availability zone"` -} - -// ResourceType returns the type of the resource -func (Volume) ResourceType() string { - return "Volume" -} - -// ListRequest builds the ListVolumes request -func (vol Volume) ListRequest() (ListCommand, error) { - req := &ListVolumes{ - Name: vol.Name, - Type: vol.Type, - VirtualMachineID: vol.VirtualMachineID, - ZoneID: vol.ZoneID, - } - - return req, nil -} - -// ResizeVolume (Async) resizes a volume -type ResizeVolume struct { - ID *UUID `json:"id" doc:"the ID of the disk volume"` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"new disk offering id"` - Size int64 `json:"size,omitempty" doc:"New volume size in G (must be larger than current size since shrinking the disk is not supported)"` - _ bool `name:"resizeVolume" description:"Resizes a volume"` -} - -// Response returns the struct to unmarshal -func (ResizeVolume) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ResizeVolume) AsyncResponse() interface{} { - return new(Volume) -} - -//go:generate go run generate/main.go -interface=Listable ListVolumes - -// ListVolumes represents a query listing volumes -type ListVolumes struct { - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"List volumes by disk offering"` - ID *UUID `json:"id,omitempty" doc:"The ID of the disk volume"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"The name of the disk volume"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - Type string `json:"type,omitempty" doc:"The type of disk volume"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"The ID of the virtual machine"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"The ID of the availability zone"` - _ bool `name:"listVolumes" description:"Lists all volumes."` -} - -// ListVolumesResponse represents a list of volumes -type ListVolumesResponse struct { - Count int `json:"count"` - Volume []Volume `json:"volume"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/volumes_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/volumes_response.go deleted file mode 100644 index c7486bc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/volumes_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListVolumes) Response() interface{} { - return new(ListVolumesResponse) -} - -// ListRequest returns itself -func (ls *ListVolumes) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListVolumes) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListVolumes) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListVolumes) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListVolumesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListVolumesResponse was expected, got %T", resp)) - return - } - - for i := range items.Volume { - if !callback(&items.Volume[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/zones.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/zones.go deleted file mode 100644 index 7632460..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/zones.go +++ /dev/null @@ -1,62 +0,0 @@ -package egoscale - -import ( - "net" -) - -// Zone represents a data center -// -// TODO: represent correctly the capacity field. -type Zone struct { - AllocationState string `json:"allocationstate,omitempty" doc:"the allocation state of the cluster"` - Description string `json:"description,omitempty" doc:"Zone description"` - DhcpProvider string `json:"dhcpprovider,omitempty" doc:"the dhcp Provider for the Zone"` - DisplayText string `json:"displaytext,omitempty" doc:"the display text of the zone"` - DNS1 net.IP `json:"dns1,omitempty" doc:"the first DNS for the Zone"` - DNS2 net.IP `json:"dns2,omitempty" doc:"the second DNS for the Zone"` - GuestCIDRAddress *CIDR `json:"guestcidraddress,omitempty" doc:"the guest CIDR address for the Zone"` - ID *UUID `json:"id,omitempty" doc:"Zone id"` - InternalDNS1 net.IP `json:"internaldns1,omitempty" doc:"the first internal DNS for the Zone"` - InternalDNS2 net.IP `json:"internaldns2,omitempty" doc:"the second internal DNS for the Zone"` - IP6DNS1 net.IP `json:"ip6dns1,omitempty" doc:"the first IPv6 DNS for the Zone"` - IP6DNS2 net.IP `json:"ip6dns2,omitempty" doc:"the second IPv6 DNS for the Zone"` - LocalStorageEnabled *bool `json:"localstorageenabled,omitempty" doc:"true if local storage offering enabled, false otherwise"` - Name string `json:"name,omitempty" doc:"Zone name"` - NetworkType string `json:"networktype,omitempty" doc:"the network type of the zone; can be Basic or Advanced"` - ResourceDetails map[string]string `json:"resourcedetails,omitempty" doc:"Meta data associated with the zone (key/value pairs)"` - SecurityGroupsEnabled *bool `json:"securitygroupsenabled,omitempty" doc:"true if security groups support is enabled, false otherwise"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with zone."` - Vlan string `json:"vlan,omitempty" doc:"the vlan range of the zone"` - ZoneToken string `json:"zonetoken,omitempty" doc:"Zone Token"` -} - -// ListRequest builds the ListZones request -func (zone Zone) ListRequest() (ListCommand, error) { - req := &ListZones{ - ID: zone.ID, - Name: zone.Name, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListZones - -// ListZones represents a query for zones -type ListZones struct { - Available *bool `json:"available,omitempty" doc:"true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false."` - ID *UUID `json:"id,omitempty" doc:"the ID of the zone"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"the name of the zone"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ShowCapacities *bool `json:"showcapacities,omitempty" doc:"flag to display the capacity of the zones"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List zones by resource tags (key/value pairs)"` - _ bool `name:"listZones" description:"Lists zones"` -} - -// ListZonesResponse represents a list of zones -type ListZonesResponse struct { - Count int `json:"count"` - Zone []Zone `json:"zone"` -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/zones_response.go b/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/zones_response.go deleted file mode 100644 index 0fe7d06..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/exoscale/egoscale/zones_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListZones) Response() interface{} { - return new(ListZonesResponse) -} - -// ListRequest returns itself -func (ls *ListZones) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListZones) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListZones) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListZones) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListZonesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListZonesResponse was expected, got %T", resp)) - return - } - - for i := range items.Zone { - if !callback(&items.Zone[i], nil) { - break - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/LICENSE deleted file mode 100644 index 34504e4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 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. \ No newline at end of file diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/field.go b/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/field.go deleted file mode 100644 index e697832..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/field.go +++ /dev/null @@ -1,141 +0,0 @@ -package structs - -import ( - "errors" - "fmt" - "reflect" -) - -var ( - errNotExported = errors.New("field is not exported") - errNotSettable = errors.New("field is not settable") -) - -// Field represents a single struct field that encapsulates high level -// functions around the field. -type Field struct { - value reflect.Value - field reflect.StructField - defaultTag string -} - -// Tag returns the value associated with key in the tag string. If there is no -// such key in the tag, Tag returns the empty string. -func (f *Field) Tag(key string) string { - return f.field.Tag.Get(key) -} - -// Value returns the underlying value of the field. It panics if the field -// is not exported. -func (f *Field) Value() interface{} { - return f.value.Interface() -} - -// IsEmbedded returns true if the given field is an anonymous field (embedded) -func (f *Field) IsEmbedded() bool { - return f.field.Anonymous -} - -// IsExported returns true if the given field is exported. -func (f *Field) IsExported() bool { - return f.field.PkgPath == "" -} - -// IsZero returns true if the given field is not initialized (has a zero value). -// It panics if the field is not exported. -func (f *Field) IsZero() bool { - zero := reflect.Zero(f.value.Type()).Interface() - current := f.Value() - - return reflect.DeepEqual(current, zero) -} - -// Name returns the name of the given field -func (f *Field) Name() string { - return f.field.Name -} - -// Kind returns the fields kind, such as "string", "map", "bool", etc .. -func (f *Field) Kind() reflect.Kind { - return f.value.Kind() -} - -// Set sets the field to given value v. It returns an error if the field is not -// settable (not addressable or not exported) or if the given value's type -// doesn't match the fields type. -func (f *Field) Set(val interface{}) error { - // we can't set unexported fields, so be sure this field is exported - if !f.IsExported() { - return errNotExported - } - - // do we get here? not sure... - if !f.value.CanSet() { - return errNotSettable - } - - given := reflect.ValueOf(val) - - if f.value.Kind() != given.Kind() { - return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind()) - } - - f.value.Set(given) - return nil -} - -// Zero sets the field to its zero value. It returns an error if the field is not -// settable (not addressable or not exported). -func (f *Field) Zero() error { - zero := reflect.Zero(f.value.Type()).Interface() - return f.Set(zero) -} - -// Fields returns a slice of Fields. This is particular handy to get the fields -// of a nested struct . A struct tag with the content of "-" ignores the -// checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field *http.Request `structs:"-"` -// -// It panics if field is not exported or if field's kind is not struct -func (f *Field) Fields() []*Field { - return getFields(f.value, f.defaultTag) -} - -// Field returns the field from a nested struct. It panics if the nested struct -// is not exported or if the field was not found. -func (f *Field) Field(name string) *Field { - field, ok := f.FieldOk(name) - if !ok { - panic("field not found") - } - - return field -} - -// FieldOk returns the field from a nested struct. The boolean returns whether -// the field was found (true) or not (false). -func (f *Field) FieldOk(name string) (*Field, bool) { - value := &f.value - // value must be settable so we need to make sure it holds the address of the - // variable and not a copy, so we can pass the pointer to strctVal instead of a - // copy (which is not assigned to any variable, hence not settable). - // see "https://blog.golang.org/laws-of-reflection#TOC_8." - if f.value.Kind() != reflect.Ptr { - a := f.value.Addr() - value = &a - } - v := strctVal(value.Interface()) - t := v.Type() - - field, ok := t.FieldByName(name) - if !ok { - return nil, false - } - - return &Field{ - field: field, - value: v.FieldByName(name), - }, true -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/structs.go b/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/structs.go deleted file mode 100644 index 3a87706..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/structs.go +++ /dev/null @@ -1,584 +0,0 @@ -// Package structs contains various utilities functions to work with structs. -package structs - -import ( - "fmt" - - "reflect" -) - -var ( - // DefaultTagName is the default tag name for struct fields which provides - // a more granular to tweak certain structs. Lookup the necessary functions - // for more info. - DefaultTagName = "structs" // struct's field default tag name -) - -// Struct encapsulates a struct type to provide several high level functions -// around the struct. -type Struct struct { - raw interface{} - value reflect.Value - TagName string -} - -// New returns a new *Struct with the struct s. It panics if the s's kind is -// not struct. -func New(s interface{}) *Struct { - return &Struct{ - raw: s, - value: strctVal(s), - TagName: DefaultTagName, - } -} - -// Map converts the given struct to a map[string]interface{}, where the keys -// of the map are the field names and the values of the map the associated -// values of the fields. The default key string is the struct field name but -// can be changed in the struct field's tag value. The "structs" key in the -// struct's field tag value is the key name. Example: -// -// // Field appears in map as key "myName". -// Name string `structs:"myName"` -// -// A tag value with the content of "-" ignores that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A tag value with the content of "string" uses the stringer to get the value. Example: -// -// // The value will be output of Animal's String() func. -// // Map will panic if Animal does not implement String(). -// Field *Animal `structs:"field,string"` -// -// A tag value with the option of "flatten" used in a struct field is to flatten its fields -// in the output map. Example: -// -// // The FieldStruct's fields will be flattened into the output map. -// FieldStruct time.Time `structs:",flatten"` -// -// A tag value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// A tag value with the option of "omitempty" ignores that particular field if -// the field value is empty. Example: -// -// // Field appears in map as key "myName", but the field is -// // skipped if empty. -// Field string `structs:"myName,omitempty"` -// -// // Field appears in map as key "Field" (the default), but -// // the field is skipped if empty. -// Field string `structs:",omitempty"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. -func (s *Struct) Map() map[string]interface{} { - out := make(map[string]interface{}) - s.FillMap(out) - return out -} - -// FillMap is the same as Map. Instead of returning the output, it fills the -// given map. -func (s *Struct) FillMap(out map[string]interface{}) { - if out == nil { - return - } - - fields := s.structFields() - - for _, field := range fields { - name := field.Name - val := s.value.FieldByName(name) - isSubStruct := false - var finalVal interface{} - - tagName, tagOpts := parseTag(field.Tag.Get(s.TagName)) - if tagName != "" { - name = tagName - } - - // if the value is a zero value and the field is marked as omitempty do - // not include - if tagOpts.Has("omitempty") { - zero := reflect.Zero(val.Type()).Interface() - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - continue - } - } - - if !tagOpts.Has("omitnested") { - finalVal = s.nested(val) - - v := reflect.ValueOf(val.Interface()) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Map, reflect.Struct: - isSubStruct = true - } - } else { - finalVal = val.Interface() - } - - if tagOpts.Has("string") { - s, ok := val.Interface().(fmt.Stringer) - if ok { - out[name] = s.String() - } - continue - } - - if isSubStruct && (tagOpts.Has("flatten")) { - for k := range finalVal.(map[string]interface{}) { - out[k] = finalVal.(map[string]interface{})[k] - } - } else { - out[name] = finalVal - } - } -} - -// Values converts the given s struct's field values to a []interface{}. A -// struct tag with the content of "-" ignores the that particular field. -// Example: -// -// // Field is ignored by this package. -// Field int `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Fields is not processed further by this package. -// Field time.Time `structs:",omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// A tag value with the option of "omitempty" ignores that particular field and -// is not added to the values if the field value is empty. Example: -// -// // Field is skipped if empty -// Field string `structs:",omitempty"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. -func (s *Struct) Values() []interface{} { - fields := s.structFields() - - var t []interface{} - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - // if the value is a zero value and the field is marked as omitempty do - // not include - if tagOpts.Has("omitempty") { - zero := reflect.Zero(val.Type()).Interface() - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - continue - } - } - - if tagOpts.Has("string") { - s, ok := val.Interface().(fmt.Stringer) - if ok { - t = append(t, s.String()) - } - continue - } - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - // look out for embedded structs, and convert them to a - // []interface{} to be added to the final values slice - t = append(t, Values(val.Interface())...) - } else { - t = append(t, val.Interface()) - } - } - - return t -} - -// Fields returns a slice of Fields. A struct tag with the content of "-" -// ignores the checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// It panics if s's kind is not struct. -func (s *Struct) Fields() []*Field { - return getFields(s.value, s.TagName) -} - -// Names returns a slice of field names. A struct tag with the content of "-" -// ignores the checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// It panics if s's kind is not struct. -func (s *Struct) Names() []string { - fields := getFields(s.value, s.TagName) - - names := make([]string, len(fields)) - - for i, field := range fields { - names[i] = field.Name() - } - - return names -} - -func getFields(v reflect.Value, tagName string) []*Field { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - t := v.Type() - - var fields []*Field - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - - if tag := field.Tag.Get(tagName); tag == "-" { - continue - } - - f := &Field{ - field: field, - value: v.FieldByName(field.Name), - } - - fields = append(fields, f) - - } - - return fields -} - -// Field returns a new Field struct that provides several high level functions -// around a single struct field entity. It panics if the field is not found. -func (s *Struct) Field(name string) *Field { - f, ok := s.FieldOk(name) - if !ok { - panic("field not found") - } - - return f -} - -// FieldOk returns a new Field struct that provides several high level functions -// around a single struct field entity. The boolean returns true if the field -// was found. -func (s *Struct) FieldOk(name string) (*Field, bool) { - t := s.value.Type() - - field, ok := t.FieldByName(name) - if !ok { - return nil, false - } - - return &Field{ - field: field, - value: s.value.FieldByName(name), - defaultTag: s.TagName, - }, true -} - -// IsZero returns true if all fields in a struct is a zero value (not -// initialized) A struct tag with the content of "-" ignores the checking of -// that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. It panics if s's kind is not struct. -func (s *Struct) IsZero() bool { - fields := s.structFields() - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - ok := IsZero(val.Interface()) - if !ok { - return false - } - - continue - } - - // zero value of the given field, such as "" for string, 0 for int - zero := reflect.Zero(val.Type()).Interface() - - // current value of the given field - current := val.Interface() - - if !reflect.DeepEqual(current, zero) { - return false - } - } - - return true -} - -// HasZero returns true if a field in a struct is not initialized (zero value). -// A struct tag with the content of "-" ignores the checking of that particular -// field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. It panics if s's kind is not struct. -func (s *Struct) HasZero() bool { - fields := s.structFields() - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - ok := HasZero(val.Interface()) - if ok { - return true - } - - continue - } - - // zero value of the given field, such as "" for string, 0 for int - zero := reflect.Zero(val.Type()).Interface() - - // current value of the given field - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - return true - } - } - - return false -} - -// Name returns the structs's type name within its package. For more info refer -// to Name() function. -func (s *Struct) Name() string { - return s.value.Type().Name() -} - -// structFields returns the exported struct fields for a given s struct. This -// is a convenient helper method to avoid duplicate code in some of the -// functions. -func (s *Struct) structFields() []reflect.StructField { - t := s.value.Type() - - var f []reflect.StructField - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - // we can't access the value of unexported fields - if field.PkgPath != "" { - continue - } - - // don't check if it's omitted - if tag := field.Tag.Get(s.TagName); tag == "-" { - continue - } - - f = append(f, field) - } - - return f -} - -func strctVal(s interface{}) reflect.Value { - v := reflect.ValueOf(s) - - // if pointer get the underlying element≤ - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - if v.Kind() != reflect.Struct { - panic("not struct") - } - - return v -} - -// Map converts the given struct to a map[string]interface{}. For more info -// refer to Struct types Map() method. It panics if s's kind is not struct. -func Map(s interface{}) map[string]interface{} { - return New(s).Map() -} - -// FillMap is the same as Map. Instead of returning the output, it fills the -// given map. -func FillMap(s interface{}, out map[string]interface{}) { - New(s).FillMap(out) -} - -// Values converts the given struct to a []interface{}. For more info refer to -// Struct types Values() method. It panics if s's kind is not struct. -func Values(s interface{}) []interface{} { - return New(s).Values() -} - -// Fields returns a slice of *Field. For more info refer to Struct types -// Fields() method. It panics if s's kind is not struct. -func Fields(s interface{}) []*Field { - return New(s).Fields() -} - -// Names returns a slice of field names. For more info refer to Struct types -// Names() method. It panics if s's kind is not struct. -func Names(s interface{}) []string { - return New(s).Names() -} - -// IsZero returns true if all fields is equal to a zero value. For more info -// refer to Struct types IsZero() method. It panics if s's kind is not struct. -func IsZero(s interface{}) bool { - return New(s).IsZero() -} - -// HasZero returns true if any field is equal to a zero value. For more info -// refer to Struct types HasZero() method. It panics if s's kind is not struct. -func HasZero(s interface{}) bool { - return New(s).HasZero() -} - -// IsStruct returns true if the given variable is a struct or a pointer to -// struct. -func IsStruct(s interface{}) bool { - v := reflect.ValueOf(s) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - // uninitialized zero value of a struct - if v.Kind() == reflect.Invalid { - return false - } - - return v.Kind() == reflect.Struct -} - -// Name returns the structs's type name within its package. It returns an -// empty string for unnamed types. It panics if s's kind is not struct. -func Name(s interface{}) string { - return New(s).Name() -} - -// nested retrieves recursively all types for the given value and returns the -// nested value. -func (s *Struct) nested(val reflect.Value) interface{} { - var finalVal interface{} - - v := reflect.ValueOf(val.Interface()) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - n := New(val.Interface()) - n.TagName = s.TagName - m := n.Map() - - // do not add the converted value if there are no exported fields, ie: - // time.Time - if len(m) == 0 { - finalVal = val.Interface() - } else { - finalVal = m - } - case reflect.Map: - // get the element type of the map - mapElem := val.Type() - switch val.Type().Kind() { - case reflect.Ptr, reflect.Array, reflect.Map, - reflect.Slice, reflect.Chan: - mapElem = val.Type().Elem() - if mapElem.Kind() == reflect.Ptr { - mapElem = mapElem.Elem() - } - } - - // only iterate over struct types, ie: map[string]StructType, - // map[string][]StructType, - if mapElem.Kind() == reflect.Struct || - (mapElem.Kind() == reflect.Slice && - mapElem.Elem().Kind() == reflect.Struct) { - m := make(map[string]interface{}, val.Len()) - for _, k := range val.MapKeys() { - m[k.String()] = s.nested(val.MapIndex(k)) - } - finalVal = m - break - } - - // TODO(arslan): should this be optional? - finalVal = val.Interface() - case reflect.Slice, reflect.Array: - if val.Type().Kind() == reflect.Interface { - finalVal = val.Interface() - break - } - - // TODO(arslan): should this be optional? - // do not iterate of non struct types, just pass the value. Ie: []int, - // []string, co... We only iterate further if it's a struct. - // i.e []foo or []*foo - if val.Type().Elem().Kind() != reflect.Struct && - !(val.Type().Elem().Kind() == reflect.Ptr && - val.Type().Elem().Elem().Kind() == reflect.Struct) { - finalVal = val.Interface() - break - } - - slices := make([]interface{}, val.Len()) - for x := 0; x < val.Len(); x++ { - slices[x] = s.nested(val.Index(x)) - } - finalVal = slices - default: - finalVal = val.Interface() - } - - return finalVal -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/tags.go b/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/tags.go deleted file mode 100644 index 136a31e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/fatih/structs/tags.go +++ /dev/null @@ -1,32 +0,0 @@ -package structs - -import "strings" - -// tagOptions contains a slice of tag options -type tagOptions []string - -// Has returns true if the given option is available in tagOptions -func (t tagOptions) Has(opt string) bool { - for _, tagOpt := range t { - if tagOpt == opt { - return true - } - } - - return false -} - -// parseTag splits a struct field's tag into its name and a list of options -// which comes after a name. A tag is in the form of: "name,option1,option2". -// The name can be neglectected. -func parseTag(tag string) (string, tagOptions) { - // tag is one of followings: - // "" - // "name" - // "name,opt" - // "name,opt,opt2" - // ",opt" - - res := strings.Split(tag, ",") - return res[0], res[1:] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/LICENSE.MIT b/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/LICENSE.MIT deleted file mode 100644 index c9a5b2e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/LICENSE.MIT +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2015 Conrad Irwin - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/error.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/error.go deleted file mode 100644 index 60062a4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/error.go +++ /dev/null @@ -1,217 +0,0 @@ -// Package errors provides errors that have stack-traces. -// -// This is particularly useful when you want to understand the -// state of execution when an error was returned unexpectedly. -// -// It provides the type *Error which implements the standard -// golang error interface, so you can use this library interchangably -// with code that is expecting a normal error return. -// -// For example: -// -// package crashy -// -// import "github.com/go-errors/errors" -// -// var Crashed = errors.Errorf("oh dear") -// -// func Crash() error { -// return errors.New(Crashed) -// } -// -// This can be called as follows: -// -// package main -// -// import ( -// "crashy" -// "fmt" -// "github.com/go-errors/errors" -// ) -// -// func main() { -// err := crashy.Crash() -// if err != nil { -// if errors.Is(err, crashy.Crashed) { -// fmt.Println(err.(*errors.Error).ErrorStack()) -// } else { -// panic(err) -// } -// } -// } -// -// This package was original written to allow reporting to Bugsnag, -// but after I found similar packages by Facebook and Dropbox, it -// was moved to one canonical location so everyone can benefit. -package errors - -import ( - "bytes" - "fmt" - "reflect" - "runtime" -) - -// The maximum number of stackframes on any error. -var MaxStackDepth = 50 - -// Error is an error with an attached stacktrace. It can be used -// wherever the builtin error interface is expected. -type Error struct { - Err error - stack []uintptr - frames []StackFrame - prefix string -} - -// New makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The stacktrace will point to the line of code that -// called New. -func New(e interface{}) *Error { - var err error - - switch e := e.(type) { - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - - stack := make([]uintptr, MaxStackDepth) - length := runtime.Callers(2, stack[:]) - return &Error{ - Err: err, - stack: stack[:length], - } -} - -// Wrap makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The skip parameter indicates how far up the stack -// to start the stacktrace. 0 is from the current call, 1 from its caller, etc. -func Wrap(e interface{}, skip int) *Error { - var err error - - switch e := e.(type) { - case *Error: - return e - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - - stack := make([]uintptr, MaxStackDepth) - length := runtime.Callers(2+skip, stack[:]) - return &Error{ - Err: err, - stack: stack[:length], - } -} - -// WrapPrefix makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the -// error message when calling Error(). The skip parameter indicates how far -// up the stack to start the stacktrace. 0 is from the current call, -// 1 from its caller, etc. -func WrapPrefix(e interface{}, prefix string, skip int) *Error { - - err := Wrap(e, 1+skip) - - if err.prefix != "" { - prefix = fmt.Sprintf("%s: %s", prefix, err.prefix) - } - - return &Error{ - Err: err.Err, - stack: err.stack, - prefix: prefix, - } - -} - -// Is detects whether the error is equal to a given error. Errors -// are considered equal by this function if they are the same object, -// or if they both contain the same error inside an errors.Error. -func Is(e error, original error) bool { - - if e == original { - return true - } - - if e, ok := e.(*Error); ok { - return Is(e.Err, original) - } - - if original, ok := original.(*Error); ok { - return Is(e, original.Err) - } - - return false -} - -// Errorf creates a new error with the given message. You can use it -// as a drop-in replacement for fmt.Errorf() to provide descriptive -// errors in return values. -func Errorf(format string, a ...interface{}) *Error { - return Wrap(fmt.Errorf(format, a...), 1) -} - -// Error returns the underlying error's message. -func (err *Error) Error() string { - - msg := err.Err.Error() - if err.prefix != "" { - msg = fmt.Sprintf("%s: %s", err.prefix, msg) - } - - return msg -} - -// Stack returns the callstack formatted the same way that go does -// in runtime/debug.Stack() -func (err *Error) Stack() []byte { - buf := bytes.Buffer{} - - for _, frame := range err.StackFrames() { - buf.WriteString(frame.String()) - } - - return buf.Bytes() -} - -// Callers satisfies the bugsnag ErrorWithCallerS() interface -// so that the stack can be read out. -func (err *Error) Callers() []uintptr { - return err.stack -} - -// ErrorStack returns a string that contains both the -// error message and the callstack. -func (err *Error) ErrorStack() string { - return err.TypeName() + " " + err.Error() + "\n" + string(err.Stack()) -} - -// StackFrames returns an array of frames containing information about the -// stack. -func (err *Error) StackFrames() []StackFrame { - if err.frames == nil { - err.frames = make([]StackFrame, len(err.stack)) - - for i, pc := range err.stack { - err.frames[i] = NewStackFrame(pc) - } - } - - return err.frames -} - -// TypeName returns the type this error. e.g. *errors.stringError. -func (err *Error) TypeName() string { - if _, ok := err.Err.(uncaughtPanic); ok { - return "panic" - } - return reflect.TypeOf(err.Err).String() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/parse_panic.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/parse_panic.go deleted file mode 100644 index cc37052..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/parse_panic.go +++ /dev/null @@ -1,127 +0,0 @@ -package errors - -import ( - "strconv" - "strings" -) - -type uncaughtPanic struct{ message string } - -func (p uncaughtPanic) Error() string { - return p.message -} - -// ParsePanic allows you to get an error object from the output of a go program -// that panicked. This is particularly useful with https://github.com/mitchellh/panicwrap. -func ParsePanic(text string) (*Error, error) { - lines := strings.Split(text, "\n") - - state := "start" - - var message string - var stack []StackFrame - - for i := 0; i < len(lines); i++ { - line := lines[i] - - if state == "start" { - if strings.HasPrefix(line, "panic: ") { - message = strings.TrimPrefix(line, "panic: ") - state = "seek" - } else { - return nil, Errorf("bugsnag.panicParser: Invalid line (no prefix): %s", line) - } - - } else if state == "seek" { - if strings.HasPrefix(line, "goroutine ") && strings.HasSuffix(line, "[running]:") { - state = "parsing" - } - - } else if state == "parsing" { - if line == "" { - state = "done" - break - } - createdBy := false - if strings.HasPrefix(line, "created by ") { - line = strings.TrimPrefix(line, "created by ") - createdBy = true - } - - i++ - - if i >= len(lines) { - return nil, Errorf("bugsnag.panicParser: Invalid line (unpaired): %s", line) - } - - frame, err := parsePanicFrame(line, lines[i], createdBy) - if err != nil { - return nil, err - } - - stack = append(stack, *frame) - if createdBy { - state = "done" - break - } - } - } - - if state == "done" || state == "parsing" { - return &Error{Err: uncaughtPanic{message}, frames: stack}, nil - } - return nil, Errorf("could not parse panic: %v", text) -} - -// The lines we're passing look like this: -// -// main.(*foo).destruct(0xc208067e98) -// /0/go/src/github.com/bugsnag/bugsnag-go/pan/main.go:22 +0x151 -func parsePanicFrame(name string, line string, createdBy bool) (*StackFrame, error) { - idx := strings.LastIndex(name, "(") - if idx == -1 && !createdBy { - return nil, Errorf("bugsnag.panicParser: Invalid line (no call): %s", name) - } - if idx != -1 { - name = name[:idx] - } - pkg := "" - - if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { - pkg += name[:lastslash] + "/" - name = name[lastslash+1:] - } - if period := strings.Index(name, "."); period >= 0 { - pkg += name[:period] - name = name[period+1:] - } - - name = strings.Replace(name, "·", ".", -1) - - if !strings.HasPrefix(line, "\t") { - return nil, Errorf("bugsnag.panicParser: Invalid line (no tab): %s", line) - } - - idx = strings.LastIndex(line, ":") - if idx == -1 { - return nil, Errorf("bugsnag.panicParser: Invalid line (no line number): %s", line) - } - file := line[1:idx] - - number := line[idx+1:] - if idx = strings.Index(number, " +"); idx > -1 { - number = number[:idx] - } - - lno, err := strconv.ParseInt(number, 10, 32) - if err != nil { - return nil, Errorf("bugsnag.panicParser: Invalid line (bad line number): %s", line) - } - - return &StackFrame{ - File: file, - LineNumber: int(lno), - Package: pkg, - Name: name, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/stackframe.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/stackframe.go deleted file mode 100644 index 750ab9a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-errors/errors/stackframe.go +++ /dev/null @@ -1,102 +0,0 @@ -package errors - -import ( - "bytes" - "fmt" - "io/ioutil" - "runtime" - "strings" -) - -// A StackFrame contains all necessary information about to generate a line -// in a callstack. -type StackFrame struct { - // The path to the file containing this ProgramCounter - File string - // The LineNumber in that file - LineNumber int - // The Name of the function that contains this ProgramCounter - Name string - // The Package that contains this function - Package string - // The underlying ProgramCounter - ProgramCounter uintptr -} - -// NewStackFrame popoulates a stack frame object from the program counter. -func NewStackFrame(pc uintptr) (frame StackFrame) { - - frame = StackFrame{ProgramCounter: pc} - if frame.Func() == nil { - return - } - frame.Package, frame.Name = packageAndName(frame.Func()) - - // pc -1 because the program counters we use are usually return addresses, - // and we want to show the line that corresponds to the function call - frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1) - return - -} - -// Func returns the function that contained this frame. -func (frame *StackFrame) Func() *runtime.Func { - if frame.ProgramCounter == 0 { - return nil - } - return runtime.FuncForPC(frame.ProgramCounter) -} - -// String returns the stackframe formatted in the same way as go does -// in runtime/debug.Stack() -func (frame *StackFrame) String() string { - str := fmt.Sprintf("%s:%d (0x%x)\n", frame.File, frame.LineNumber, frame.ProgramCounter) - - source, err := frame.SourceLine() - if err != nil { - return str - } - - return str + fmt.Sprintf("\t%s: %s\n", frame.Name, source) -} - -// SourceLine gets the line of code (from File and Line) of the original source if possible. -func (frame *StackFrame) SourceLine() (string, error) { - data, err := ioutil.ReadFile(frame.File) - - if err != nil { - return "", New(err) - } - - lines := bytes.Split(data, []byte{'\n'}) - if frame.LineNumber <= 0 || frame.LineNumber >= len(lines) { - return "???", nil - } - // -1 because line-numbers are 1 based, but our array is 0 based - return string(bytes.Trim(lines[frame.LineNumber-1], " \t")), nil -} - -func packageAndName(fn *runtime.Func) (string, string) { - name := fn.Name() - pkg := "" - - // The name includes the path name to the package, which is unnecessary - // since the file name is already included. Plus, it has center dots. - // That is, we see - // runtime/debug.*T·ptrmethod - // and want - // *T.ptrmethod - // Since the package path might contains dots (e.g. code.google.com/...), - // we first remove the path prefix if there is one. - if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { - pkg += name[:lastslash] + "/" - name = name[lastslash+1:] - } - if period := strings.Index(name, "."); period >= 0 { - pkg += name[:period] - name = name[period+1:] - } - - name = strings.Replace(name, "·", ".", -1) - return pkg, name -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/LICENSE deleted file mode 100644 index d361bbc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -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 2014 Unknwon - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/error.go deleted file mode 100644 index 80afe74..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/error.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "fmt" -) - -type ErrDelimiterNotFound struct { - Line string -} - -func IsErrDelimiterNotFound(err error) bool { - _, ok := err.(ErrDelimiterNotFound) - return ok -} - -func (err ErrDelimiterNotFound) Error() string { - return fmt.Sprintf("key-value delimiter not found: %s", err.Line) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/file.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/file.go deleted file mode 100644 index 1a3186b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/file.go +++ /dev/null @@ -1,414 +0,0 @@ -// Copyright 2017 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "strings" - "sync" -) - -// File represents a combination of a or more INI file(s) in memory. -type File struct { - options LoadOptions - dataSources []dataSource - - // Should make things safe, but sometimes doesn't matter. - BlockMode bool - lock sync.RWMutex - - // To keep data in order. - sectionList []string - // Actual data is stored here. - sections map[string]*Section - - NameMapper - ValueMapper -} - -// newFile initializes File object with given data sources. -func newFile(dataSources []dataSource, opts LoadOptions) *File { - return &File{ - BlockMode: true, - dataSources: dataSources, - sections: make(map[string]*Section), - sectionList: make([]string, 0, 10), - options: opts, - } -} - -// Empty returns an empty file object. -func Empty() *File { - // Ignore error here, we sure our data is good. - f, _ := Load([]byte("")) - return f -} - -// NewSection creates a new section. -func (f *File) NewSection(name string) (*Section, error) { - if len(name) == 0 { - return nil, errors.New("error creating new section: empty section name") - } else if f.options.Insensitive && name != DEFAULT_SECTION { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if inSlice(name, f.sectionList) { - return f.sections[name], nil - } - - f.sectionList = append(f.sectionList, name) - f.sections[name] = newSection(f, name) - return f.sections[name], nil -} - -// NewRawSection creates a new section with an unparseable body. -func (f *File) NewRawSection(name, body string) (*Section, error) { - section, err := f.NewSection(name) - if err != nil { - return nil, err - } - - section.isRawSection = true - section.rawBody = body - return section, nil -} - -// NewSections creates a list of sections. -func (f *File) NewSections(names ...string) (err error) { - for _, name := range names { - if _, err = f.NewSection(name); err != nil { - return err - } - } - return nil -} - -// GetSection returns section by given name. -func (f *File) GetSection(name string) (*Section, error) { - if len(name) == 0 { - name = DEFAULT_SECTION - } - if f.options.Insensitive { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.RLock() - defer f.lock.RUnlock() - } - - sec := f.sections[name] - if sec == nil { - return nil, fmt.Errorf("section '%s' does not exist", name) - } - return sec, nil -} - -// Section assumes named section exists and returns a zero-value when not. -func (f *File) Section(name string) *Section { - sec, err := f.GetSection(name) - if err != nil { - // Note: It's OK here because the only possible error is empty section name, - // but if it's empty, this piece of code won't be executed. - sec, _ = f.NewSection(name) - return sec - } - return sec -} - -// Section returns list of Section. -func (f *File) Sections() []*Section { - if f.BlockMode { - f.lock.RLock() - defer f.lock.RUnlock() - } - - sections := make([]*Section, len(f.sectionList)) - for i, name := range f.sectionList { - sections[i] = f.sections[name] - } - return sections -} - -// ChildSections returns a list of child sections of given section name. -func (f *File) ChildSections(name string) []*Section { - return f.Section(name).ChildSections() -} - -// SectionStrings returns list of section names. -func (f *File) SectionStrings() []string { - list := make([]string, len(f.sectionList)) - copy(list, f.sectionList) - return list -} - -// DeleteSection deletes a section. -func (f *File) DeleteSection(name string) { - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if len(name) == 0 { - name = DEFAULT_SECTION - } - - for i, s := range f.sectionList { - if s == name { - f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...) - delete(f.sections, name) - return - } - } -} - -func (f *File) reload(s dataSource) error { - r, err := s.ReadCloser() - if err != nil { - return err - } - defer r.Close() - - return f.parse(r) -} - -// Reload reloads and parses all data sources. -func (f *File) Reload() (err error) { - for _, s := range f.dataSources { - if err = f.reload(s); err != nil { - // In loose mode, we create an empty default section for nonexistent files. - if os.IsNotExist(err) && f.options.Loose { - f.parse(bytes.NewBuffer(nil)) - continue - } - return err - } - } - return nil -} - -// Append appends one or more data sources and reloads automatically. -func (f *File) Append(source interface{}, others ...interface{}) error { - ds, err := parseDataSource(source) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - for _, s := range others { - ds, err = parseDataSource(s) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - } - return f.Reload() -} - -func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { - equalSign := "=" - if PrettyFormat || PrettyEqual { - equalSign = " = " - } - - // Use buffer to make sure target is safe until finish encoding. - buf := bytes.NewBuffer(nil) - for i, sname := range f.sectionList { - sec := f.Section(sname) - if len(sec.Comment) > 0 { - // Support multiline comments - lines := strings.Split(sec.Comment, LineBreak) - for i := range lines { - if lines[i][0] != '#' && lines[i][0] != ';' { - lines[i] = "; " + lines[i] - } else { - lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:]) - } - - if _, err := buf.WriteString(lines[i] + LineBreak); err != nil { - return nil, err - } - } - } - - if i > 0 || DefaultHeader { - if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil { - return nil, err - } - } else { - // Write nothing if default section is empty - if len(sec.keyList) == 0 { - continue - } - } - - if sec.isRawSection { - if _, err := buf.WriteString(sec.rawBody); err != nil { - return nil, err - } - - if PrettySection { - // Put a line between sections - if _, err := buf.WriteString(LineBreak); err != nil { - return nil, err - } - } - continue - } - - // Count and generate alignment length and buffer spaces using the - // longest key. Keys may be modifed if they contain certain characters so - // we need to take that into account in our calculation. - alignLength := 0 - if PrettyFormat { - for _, kname := range sec.keyList { - keyLength := len(kname) - // First case will surround key by ` and second by """ - if strings.ContainsAny(kname, "\"=:") { - keyLength += 2 - } else if strings.Contains(kname, "`") { - keyLength += 6 - } - - if keyLength > alignLength { - alignLength = keyLength - } - } - } - alignSpaces := bytes.Repeat([]byte(" "), alignLength) - - KEY_LIST: - for _, kname := range sec.keyList { - key := sec.Key(kname) - if len(key.Comment) > 0 { - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - - // Support multiline comments - lines := strings.Split(key.Comment, LineBreak) - for i := range lines { - if lines[i][0] != '#' && lines[i][0] != ';' { - lines[i] = "; " + lines[i] - } else { - lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:]) - } - - if _, err := buf.WriteString(lines[i] + LineBreak); err != nil { - return nil, err - } - } - } - - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - - switch { - case key.isAutoIncrement: - kname = "-" - case strings.ContainsAny(kname, "\"=:"): - kname = "`" + kname + "`" - case strings.Contains(kname, "`"): - kname = `"""` + kname + `"""` - } - - for _, val := range key.ValueWithShadows() { - if _, err := buf.WriteString(kname); err != nil { - return nil, err - } - - if key.isBooleanType { - if kname != sec.keyList[len(sec.keyList)-1] { - buf.WriteString(LineBreak) - } - continue KEY_LIST - } - - // Write out alignment spaces before "=" sign - if PrettyFormat { - buf.Write(alignSpaces[:alignLength-len(kname)]) - } - - // In case key value contains "\n", "`", "\"", "#" or ";" - if strings.ContainsAny(val, "\n`") { - val = `"""` + val + `"""` - } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") { - val = "`" + val + "`" - } - if _, err := buf.WriteString(equalSign + val + LineBreak); err != nil { - return nil, err - } - } - - for _, val := range key.nestedValues { - if _, err := buf.WriteString(indent + " " + val + LineBreak); err != nil { - return nil, err - } - } - } - - if PrettySection { - // Put a line between sections - if _, err := buf.WriteString(LineBreak); err != nil { - return nil, err - } - } - } - - return buf, nil -} - -// WriteToIndent writes content into io.Writer with given indention. -// If PrettyFormat has been set to be true, -// it will align "=" sign with spaces under each section. -func (f *File) WriteToIndent(w io.Writer, indent string) (int64, error) { - buf, err := f.writeToBuffer(indent) - if err != nil { - return 0, err - } - return buf.WriteTo(w) -} - -// WriteTo writes file content into io.Writer. -func (f *File) WriteTo(w io.Writer) (int64, error) { - return f.WriteToIndent(w, "") -} - -// SaveToIndent writes content to file system with given value indention. -func (f *File) SaveToIndent(filename, indent string) error { - // Note: Because we are truncating with os.Create, - // so it's safer to save to a temporary file location and rename afte done. - buf, err := f.writeToBuffer(indent) - if err != nil { - return err - } - - return ioutil.WriteFile(filename, buf.Bytes(), 0666) -} - -// SaveTo writes content to file system. -func (f *File) SaveTo(filename string) error { - return f.SaveToIndent(filename, "") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/ini.go deleted file mode 100644 index cb55997..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/ini.go +++ /dev/null @@ -1,211 +0,0 @@ -// +build go1.6 - -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -// Package ini provides INI file read and write functionality in Go. -package ini - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "regexp" - "runtime" -) - -const ( - // Name for default section. You can use this constant or the string literal. - // In most of cases, an empty string is all you need to access the section. - DEFAULT_SECTION = "DEFAULT" - - // Maximum allowed depth when recursively substituing variable names. - _DEPTH_VALUES = 99 - _VERSION = "1.38.2" -) - -// Version returns current package version literal. -func Version() string { - return _VERSION -} - -var ( - // Delimiter to determine or compose a new line. - // This variable will be changed to "\r\n" automatically on Windows - // at package init time. - LineBreak = "\n" - - // Variable regexp pattern: %(variable)s - varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`) - - // Indicate whether to align "=" sign with spaces to produce pretty output - // or reduce all possible spaces for compact format. - PrettyFormat = true - - // Place spaces around "=" sign even when PrettyFormat is false - PrettyEqual = false - - // Explicitly write DEFAULT section header - DefaultHeader = false - - // Indicate whether to put a line between sections - PrettySection = true -) - -func init() { - if runtime.GOOS == "windows" { - LineBreak = "\r\n" - } -} - -func inSlice(str string, s []string) bool { - for _, v := range s { - if str == v { - return true - } - } - return false -} - -// dataSource is an interface that returns object which can be read and closed. -type dataSource interface { - ReadCloser() (io.ReadCloser, error) -} - -// sourceFile represents an object that contains content on the local file system. -type sourceFile struct { - name string -} - -func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) { - return os.Open(s.name) -} - -// sourceData represents an object that contains content in memory. -type sourceData struct { - data []byte -} - -func (s *sourceData) ReadCloser() (io.ReadCloser, error) { - return ioutil.NopCloser(bytes.NewReader(s.data)), nil -} - -// sourceReadCloser represents an input stream with Close method. -type sourceReadCloser struct { - reader io.ReadCloser -} - -func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) { - return s.reader, nil -} - -func parseDataSource(source interface{}) (dataSource, error) { - switch s := source.(type) { - case string: - return sourceFile{s}, nil - case []byte: - return &sourceData{s}, nil - case io.ReadCloser: - return &sourceReadCloser{s}, nil - default: - return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s) - } -} - -type LoadOptions struct { - // Loose indicates whether the parser should ignore nonexistent files or return error. - Loose bool - // Insensitive indicates whether the parser forces all section and key names to lowercase. - Insensitive bool - // IgnoreContinuation indicates whether to ignore continuation lines while parsing. - IgnoreContinuation bool - // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value. - IgnoreInlineComment bool - // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs. - SkipUnrecognizableLines bool - // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing. - // This type of keys are mostly used in my.cnf. - AllowBooleanKeys bool - // AllowShadows indicates whether to keep track of keys with same name under same section. - AllowShadows bool - // AllowNestedValues indicates whether to allow AWS-like nested values. - // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values - AllowNestedValues bool - // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values. - // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure - // Relevant quote: Values can also span multiple lines, as long as they are indented deeper - // than the first line of the value. - AllowPythonMultilineValues bool - // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value. - // Docs: https://docs.python.org/2/library/configparser.html - // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names. - // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment. - SpaceBeforeInlineComment bool - // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format - // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value" - UnescapeValueDoubleQuotes bool - // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format - // when value is NOT surrounded by any quotes. - // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all. - UnescapeValueCommentSymbols bool - // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise - // conform to key/value pairs. Specify the names of those blocks here. - UnparseableSections []string -} - -func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) { - sources := make([]dataSource, len(others)+1) - sources[0], err = parseDataSource(source) - if err != nil { - return nil, err - } - for i := range others { - sources[i+1], err = parseDataSource(others[i]) - if err != nil { - return nil, err - } - } - f := newFile(sources, opts) - if err = f.Reload(); err != nil { - return nil, err - } - return f, nil -} - -// Load loads and parses from INI data sources. -// Arguments can be mixed of file name with string type, or raw data in []byte. -// It will return error if list contains nonexistent files. -func Load(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{}, source, others...) -} - -// LooseLoad has exactly same functionality as Load function -// except it ignores nonexistent files instead of returning error. -func LooseLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Loose: true}, source, others...) -} - -// InsensitiveLoad has exactly same functionality as Load function -// except it forces all section and key names to be lowercased. -func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Insensitive: true}, source, others...) -} - -// ShadowLoad has exactly same functionality as Load function -// except it allows have shadow keys. -func ShadowLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{AllowShadows: true}, source, others...) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/key.go deleted file mode 100644 index 7c8566a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/key.go +++ /dev/null @@ -1,751 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "strconv" - "strings" - "time" -) - -// Key represents a key under a section. -type Key struct { - s *Section - Comment string - name string - value string - isAutoIncrement bool - isBooleanType bool - - isShadow bool - shadows []*Key - - nestedValues []string -} - -// newKey simply return a key object with given values. -func newKey(s *Section, name, val string) *Key { - return &Key{ - s: s, - name: name, - value: val, - } -} - -func (k *Key) addShadow(val string) error { - if k.isShadow { - return errors.New("cannot add shadow to another shadow key") - } else if k.isAutoIncrement || k.isBooleanType { - return errors.New("cannot add shadow to auto-increment or boolean key") - } - - shadow := newKey(k.s, k.name, val) - shadow.isShadow = true - k.shadows = append(k.shadows, shadow) - return nil -} - -// AddShadow adds a new shadow key to itself. -func (k *Key) AddShadow(val string) error { - if !k.s.f.options.AllowShadows { - return errors.New("shadow key is not allowed") - } - return k.addShadow(val) -} - -func (k *Key) addNestedValue(val string) error { - if k.isAutoIncrement || k.isBooleanType { - return errors.New("cannot add nested value to auto-increment or boolean key") - } - - k.nestedValues = append(k.nestedValues, val) - return nil -} - -func (k *Key) AddNestedValue(val string) error { - if !k.s.f.options.AllowNestedValues { - return errors.New("nested value is not allowed") - } - return k.addNestedValue(val) -} - -// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv -type ValueMapper func(string) string - -// Name returns name of key. -func (k *Key) Name() string { - return k.name -} - -// Value returns raw value of key for performance purpose. -func (k *Key) Value() string { - return k.value -} - -// ValueWithShadows returns raw values of key and its shadows if any. -func (k *Key) ValueWithShadows() []string { - if len(k.shadows) == 0 { - return []string{k.value} - } - vals := make([]string, len(k.shadows)+1) - vals[0] = k.value - for i := range k.shadows { - vals[i+1] = k.shadows[i].value - } - return vals -} - -// NestedValues returns nested values stored in the key. -// It is possible returned value is nil if no nested values stored in the key. -func (k *Key) NestedValues() []string { - return k.nestedValues -} - -// transformValue takes a raw value and transforms to its final string. -func (k *Key) transformValue(val string) string { - if k.s.f.ValueMapper != nil { - val = k.s.f.ValueMapper(val) - } - - // Fail-fast if no indicate char found for recursive value - if !strings.Contains(val, "%") { - return val - } - for i := 0; i < _DEPTH_VALUES; i++ { - vr := varPattern.FindString(val) - if len(vr) == 0 { - break - } - - // Take off leading '%(' and trailing ')s'. - noption := strings.TrimLeft(vr, "%(") - noption = strings.TrimRight(noption, ")s") - - // Search in the same section. - nk, err := k.s.GetKey(noption) - if err != nil || k == nk { - // Search again in default section. - nk, _ = k.s.f.Section("").GetKey(noption) - } - - // Substitute by new value and take off leading '%(' and trailing ')s'. - val = strings.Replace(val, vr, nk.value, -1) - } - return val -} - -// String returns string representation of value. -func (k *Key) String() string { - return k.transformValue(k.value) -} - -// Validate accepts a validate function which can -// return modifed result as key value. -func (k *Key) Validate(fn func(string) string) string { - return fn(k.String()) -} - -// parseBool returns the boolean value represented by the string. -// -// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On, -// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off. -// Any other value returns an error. -func parseBool(str string) (value bool, err error) { - switch str { - case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On": - return true, nil - case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off": - return false, nil - } - return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) -} - -// Bool returns bool type value. -func (k *Key) Bool() (bool, error) { - return parseBool(k.String()) -} - -// Float64 returns float64 type value. -func (k *Key) Float64() (float64, error) { - return strconv.ParseFloat(k.String(), 64) -} - -// Int returns int type value. -func (k *Key) Int() (int, error) { - return strconv.Atoi(k.String()) -} - -// Int64 returns int64 type value. -func (k *Key) Int64() (int64, error) { - return strconv.ParseInt(k.String(), 10, 64) -} - -// Uint returns uint type valued. -func (k *Key) Uint() (uint, error) { - u, e := strconv.ParseUint(k.String(), 10, 64) - return uint(u), e -} - -// Uint64 returns uint64 type value. -func (k *Key) Uint64() (uint64, error) { - return strconv.ParseUint(k.String(), 10, 64) -} - -// Duration returns time.Duration type value. -func (k *Key) Duration() (time.Duration, error) { - return time.ParseDuration(k.String()) -} - -// TimeFormat parses with given format and returns time.Time type value. -func (k *Key) TimeFormat(format string) (time.Time, error) { - return time.Parse(format, k.String()) -} - -// Time parses with RFC3339 format and returns time.Time type value. -func (k *Key) Time() (time.Time, error) { - return k.TimeFormat(time.RFC3339) -} - -// MustString returns default value if key value is empty. -func (k *Key) MustString(defaultVal string) string { - val := k.String() - if len(val) == 0 { - k.value = defaultVal - return defaultVal - } - return val -} - -// MustBool always returns value without error, -// it returns false if error occurs. -func (k *Key) MustBool(defaultVal ...bool) bool { - val, err := k.Bool() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatBool(defaultVal[0]) - return defaultVal[0] - } - return val -} - -// MustFloat64 always returns value without error, -// it returns 0.0 if error occurs. -func (k *Key) MustFloat64(defaultVal ...float64) float64 { - val, err := k.Float64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64) - return defaultVal[0] - } - return val -} - -// MustInt always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt(defaultVal ...int) int { - val, err := k.Int() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(int64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustInt64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt64(defaultVal ...int64) int64 { - val, err := k.Int64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustUint always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint(defaultVal ...uint) uint { - val, err := k.Uint() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(uint64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustUint64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint64(defaultVal ...uint64) uint64 { - val, err := k.Uint64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustDuration always returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { - val, err := k.Duration() - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].String() - return defaultVal[0] - } - return val -} - -// MustTimeFormat always parses with given format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { - val, err := k.TimeFormat(format) - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].Format(format) - return defaultVal[0] - } - return val -} - -// MustTime always parses with RFC3339 format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTime(defaultVal ...time.Time) time.Time { - return k.MustTimeFormat(time.RFC3339, defaultVal...) -} - -// In always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) In(defaultVal string, candidates []string) string { - val := k.String() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InFloat64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { - val := k.MustFloat64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt(defaultVal int, candidates []int) int { - val := k.MustInt() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { - val := k.MustInt64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint(defaultVal uint, candidates []uint) uint { - val := k.MustUint() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { - val := k.MustUint64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTimeFormat always parses with given format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { - val := k.MustTimeFormat(format) - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTime always parses with RFC3339 format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { - return k.InTimeFormat(time.RFC3339, defaultVal, candidates) -} - -// RangeFloat64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { - val := k.MustFloat64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt(defaultVal, min, max int) int { - val := k.MustInt() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { - val := k.MustInt64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeTimeFormat checks if value with given format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { - val := k.MustTimeFormat(format) - if val.Unix() < min.Unix() || val.Unix() > max.Unix() { - return defaultVal - } - return val -} - -// RangeTime checks if value with RFC3339 format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { - return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) -} - -// Strings returns list of string divided by given delimiter. -func (k *Key) Strings(delim string) []string { - str := k.String() - if len(str) == 0 { - return []string{} - } - - runes := []rune(str) - vals := make([]string, 0, 2) - var buf bytes.Buffer - escape := false - idx := 0 - for { - if escape { - escape = false - if runes[idx] != '\\' && !strings.HasPrefix(string(runes[idx:]), delim) { - buf.WriteRune('\\') - } - buf.WriteRune(runes[idx]) - } else { - if runes[idx] == '\\' { - escape = true - } else if strings.HasPrefix(string(runes[idx:]), delim) { - idx += len(delim) - 1 - vals = append(vals, strings.TrimSpace(buf.String())) - buf.Reset() - } else { - buf.WriteRune(runes[idx]) - } - } - idx += 1 - if idx == len(runes) { - break - } - } - - if buf.Len() > 0 { - vals = append(vals, strings.TrimSpace(buf.String())) - } - - return vals -} - -// StringsWithShadows returns list of string divided by given delimiter. -// Shadows will also be appended if any. -func (k *Key) StringsWithShadows(delim string) []string { - vals := k.ValueWithShadows() - results := make([]string, 0, len(vals)*2) - for i := range vals { - if len(vals) == 0 { - continue - } - - results = append(results, strings.Split(vals[i], delim)...) - } - - for i := range results { - results[i] = k.transformValue(strings.TrimSpace(results[i])) - } - return results -} - -// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Float64s(delim string) []float64 { - vals, _ := k.parseFloat64s(k.Strings(delim), true, false) - return vals -} - -// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Ints(delim string) []int { - vals, _ := k.parseInts(k.Strings(delim), true, false) - return vals -} - -// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Int64s(delim string) []int64 { - vals, _ := k.parseInt64s(k.Strings(delim), true, false) - return vals -} - -// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uints(delim string) []uint { - vals, _ := k.parseUints(k.Strings(delim), true, false) - return vals -} - -// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uint64s(delim string) []uint64 { - vals, _ := k.parseUint64s(k.Strings(delim), true, false) - return vals -} - -// TimesFormat parses with given format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) TimesFormat(format, delim string) []time.Time { - vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false) - return vals -} - -// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) Times(delim string) []time.Time { - return k.TimesFormat(time.RFC3339, delim) -} - -// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then -// it will not be included to result list. -func (k *Key) ValidFloat64s(delim string) []float64 { - vals, _ := k.parseFloat64s(k.Strings(delim), false, false) - return vals -} - -// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will -// not be included to result list. -func (k *Key) ValidInts(delim string) []int { - vals, _ := k.parseInts(k.Strings(delim), false, false) - return vals -} - -// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer, -// then it will not be included to result list. -func (k *Key) ValidInt64s(delim string) []int64 { - vals, _ := k.parseInt64s(k.Strings(delim), false, false) - return vals -} - -// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer, -// then it will not be included to result list. -func (k *Key) ValidUints(delim string) []uint { - vals, _ := k.parseUints(k.Strings(delim), false, false) - return vals -} - -// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned -// integer, then it will not be included to result list. -func (k *Key) ValidUint64s(delim string) []uint64 { - vals, _ := k.parseUint64s(k.Strings(delim), false, false) - return vals -} - -// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimesFormat(format, delim string) []time.Time { - vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false) - return vals -} - -// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimes(delim string) []time.Time { - return k.ValidTimesFormat(time.RFC3339, delim) -} - -// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictFloat64s(delim string) ([]float64, error) { - return k.parseFloat64s(k.Strings(delim), false, true) -} - -// StrictInts returns list of int divided by given delimiter or error on first invalid input. -func (k *Key) StrictInts(delim string) ([]int, error) { - return k.parseInts(k.Strings(delim), false, true) -} - -// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictInt64s(delim string) ([]int64, error) { - return k.parseInt64s(k.Strings(delim), false, true) -} - -// StrictUints returns list of uint divided by given delimiter or error on first invalid input. -func (k *Key) StrictUints(delim string) ([]uint, error) { - return k.parseUints(k.Strings(delim), false, true) -} - -// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictUint64s(delim string) ([]uint64, error) { - return k.parseUint64s(k.Strings(delim), false, true) -} - -// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) { - return k.parseTimesFormat(format, k.Strings(delim), false, true) -} - -// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimes(delim string) ([]time.Time, error) { - return k.StrictTimesFormat(time.RFC3339, delim) -} - -// parseFloat64s transforms strings to float64s. -func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) { - vals := make([]float64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseFloat(str, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseInts transforms strings to ints. -func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) { - vals := make([]int, 0, len(strs)) - for _, str := range strs { - val, err := strconv.Atoi(str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseInt64s transforms strings to int64s. -func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) { - vals := make([]int64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseInt(str, 10, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseUints transforms strings to uints. -func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) { - vals := make([]uint, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 10, 0) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, uint(val)) - } - } - return vals, nil -} - -// parseUint64s transforms strings to uint64s. -func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) { - vals := make([]uint64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 10, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseTimesFormat transforms strings to times in given format. -func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { - vals := make([]time.Time, 0, len(strs)) - for _, str := range strs { - val, err := time.Parse(format, str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// SetValue changes key value. -func (k *Key) SetValue(v string) { - if k.s.f.BlockMode { - k.s.f.lock.Lock() - defer k.s.f.lock.Unlock() - } - - k.value = v - k.s.keysHash[k.name] = v -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/parser.go deleted file mode 100644 index 3daf54c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/parser.go +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright 2015 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bufio" - "bytes" - "fmt" - "io" - "regexp" - "strconv" - "strings" - "unicode" -) - -var pythonMultiline = regexp.MustCompile("^(\\s+)([^\n]+)") - -type tokenType int - -const ( - _TOKEN_INVALID tokenType = iota - _TOKEN_COMMENT - _TOKEN_SECTION - _TOKEN_KEY -) - -type parser struct { - buf *bufio.Reader - isEOF bool - count int - comment *bytes.Buffer -} - -func newParser(r io.Reader) *parser { - return &parser{ - buf: bufio.NewReader(r), - count: 1, - comment: &bytes.Buffer{}, - } -} - -// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format. -// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding -func (p *parser) BOM() error { - mask, err := p.buf.Peek(2) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 2 { - return nil - } - - switch { - case mask[0] == 254 && mask[1] == 255: - fallthrough - case mask[0] == 255 && mask[1] == 254: - p.buf.Read(mask) - case mask[0] == 239 && mask[1] == 187: - mask, err := p.buf.Peek(3) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 3 { - return nil - } - if mask[2] == 191 { - p.buf.Read(mask) - } - } - return nil -} - -func (p *parser) readUntil(delim byte) ([]byte, error) { - data, err := p.buf.ReadBytes(delim) - if err != nil { - if err == io.EOF { - p.isEOF = true - } else { - return nil, err - } - } - return data, nil -} - -func cleanComment(in []byte) ([]byte, bool) { - i := bytes.IndexAny(in, "#;") - if i == -1 { - return nil, false - } - return in[i:], true -} - -func readKeyName(in []byte) (string, int, error) { - line := string(in) - - // Check if key name surrounded by quotes. - var keyQuote string - if line[0] == '"' { - if len(line) > 6 && string(line[0:3]) == `"""` { - keyQuote = `"""` - } else { - keyQuote = `"` - } - } else if line[0] == '`' { - keyQuote = "`" - } - - // Get out key name - endIdx := -1 - if len(keyQuote) > 0 { - startIdx := len(keyQuote) - // FIXME: fail case -> """"""name"""=value - pos := strings.Index(line[startIdx:], keyQuote) - if pos == -1 { - return "", -1, fmt.Errorf("missing closing key quote: %s", line) - } - pos += startIdx - - // Find key-value delimiter - i := strings.IndexAny(line[pos+startIdx:], "=:") - if i < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - endIdx = pos + i - return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil - } - - endIdx = strings.IndexAny(line, "=:") - if endIdx < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil -} - -func (p *parser) readMultilines(line, val, valQuote string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := string(data) - - pos := strings.LastIndex(next, valQuote) - if pos > -1 { - val += next[:pos] - - comment, has := cleanComment([]byte(next[pos:])) - if has { - p.comment.Write(bytes.TrimSpace(comment)) - } - break - } - val += next - if p.isEOF { - return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next) - } - } - return val, nil -} - -func (p *parser) readContinuationLines(val string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := strings.TrimSpace(string(data)) - - if len(next) == 0 { - break - } - val += next - if val[len(val)-1] != '\\' { - break - } - val = val[:len(val)-1] - } - return val, nil -} - -// hasSurroundedQuote check if and only if the first and last characters -// are quotes \" or \'. -// It returns false if any other parts also contain same kind of quotes. -func hasSurroundedQuote(in string, quote byte) bool { - return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote && - strings.IndexByte(in[1:], quote) == len(in)-2 -} - -func (p *parser) readValue(in []byte, - parserBufferSize int, - ignoreContinuation, ignoreInlineComment, unescapeValueDoubleQuotes, unescapeValueCommentSymbols, allowPythonMultilines, spaceBeforeInlineComment bool) (string, error) { - - line := strings.TrimLeftFunc(string(in), unicode.IsSpace) - if len(line) == 0 { - return "", nil - } - - var valQuote string - if len(line) > 3 && string(line[0:3]) == `"""` { - valQuote = `"""` - } else if line[0] == '`' { - valQuote = "`" - } else if unescapeValueDoubleQuotes && line[0] == '"' { - valQuote = `"` - } - - if len(valQuote) > 0 { - startIdx := len(valQuote) - pos := strings.LastIndex(line[startIdx:], valQuote) - // Check for multi-line value - if pos == -1 { - return p.readMultilines(line, line[startIdx:], valQuote) - } - - if unescapeValueDoubleQuotes && valQuote == `"` { - return strings.Replace(line[startIdx:pos+startIdx], `\"`, `"`, -1), nil - } - return line[startIdx : pos+startIdx], nil - } - - lastChar := line[len(line)-1] - // Won't be able to reach here if value only contains whitespace - line = strings.TrimSpace(line) - trimmedLastChar := line[len(line)-1] - - // Check continuation lines when desired - if !ignoreContinuation && trimmedLastChar == '\\' { - return p.readContinuationLines(line[:len(line)-1]) - } - - // Check if ignore inline comment - if !ignoreInlineComment { - var i int - if spaceBeforeInlineComment { - i = strings.Index(line, " #") - if i == -1 { - i = strings.Index(line, " ;") - } - - } else { - i = strings.IndexAny(line, "#;") - } - - if i > -1 { - p.comment.WriteString(line[i:]) - line = strings.TrimSpace(line[:i]) - } - - } - - // Trim single and double quotes - if hasSurroundedQuote(line, '\'') || - hasSurroundedQuote(line, '"') { - line = line[1 : len(line)-1] - } else if len(valQuote) == 0 && unescapeValueCommentSymbols { - if strings.Contains(line, `\;`) { - line = strings.Replace(line, `\;`, ";", -1) - } - if strings.Contains(line, `\#`) { - line = strings.Replace(line, `\#`, "#", -1) - } - } else if allowPythonMultilines && lastChar == '\n' { - parserBufferPeekResult, _ := p.buf.Peek(parserBufferSize) - peekBuffer := bytes.NewBuffer(parserBufferPeekResult) - - identSize := -1 - val := line - - for { - peekData, peekErr := peekBuffer.ReadBytes('\n') - if peekErr != nil { - if peekErr == io.EOF { - return val, nil - } - return "", peekErr - } - - peekMatches := pythonMultiline.FindStringSubmatch(string(peekData)) - if len(peekMatches) != 3 { - return val, nil - } - - currentIdentSize := len(peekMatches[1]) - // NOTE: Return if not a python-ini multi-line value. - if currentIdentSize < 0 { - return val, nil - } - identSize = currentIdentSize - - // NOTE: Just advance the parser reader (buffer) in-sync with the peek buffer. - _, err := p.readUntil('\n') - if err != nil { - return "", err - } - - val += fmt.Sprintf("\n%s", peekMatches[2]) - } - - // NOTE: If it was a Python multi-line value, - // return the appended value. - if identSize > 0 { - return val, nil - } - } - - return line, nil -} - -// parse parses data through an io.Reader. -func (f *File) parse(reader io.Reader) (err error) { - p := newParser(reader) - if err = p.BOM(); err != nil { - return fmt.Errorf("BOM: %v", err) - } - - // Ignore error because default section name is never empty string. - name := DEFAULT_SECTION - if f.options.Insensitive { - name = strings.ToLower(DEFAULT_SECTION) - } - section, _ := f.NewSection(name) - - // This "last" is not strictly equivalent to "previous one" if current key is not the first nested key - var isLastValueEmpty bool - var lastRegularKey *Key - - var line []byte - var inUnparseableSection bool - - // NOTE: Iterate and increase `currentPeekSize` until - // the size of the parser buffer is found. - // TODO(unknwon): When Golang 1.10 is the lowest version supported, replace with `parserBufferSize := p.buf.Size()`. - parserBufferSize := 0 - // NOTE: Peek 1kb at a time. - currentPeekSize := 1024 - - if f.options.AllowPythonMultilineValues { - for { - peekBytes, _ := p.buf.Peek(currentPeekSize) - peekBytesLength := len(peekBytes) - - if parserBufferSize >= peekBytesLength { - break - } - - currentPeekSize *= 2 - parserBufferSize = peekBytesLength - } - } - - for !p.isEOF { - line, err = p.readUntil('\n') - if err != nil { - return err - } - - if f.options.AllowNestedValues && - isLastValueEmpty && len(line) > 0 { - if line[0] == ' ' || line[0] == '\t' { - lastRegularKey.addNestedValue(string(bytes.TrimSpace(line))) - continue - } - } - - line = bytes.TrimLeftFunc(line, unicode.IsSpace) - if len(line) == 0 { - continue - } - - // Comments - if line[0] == '#' || line[0] == ';' { - // Note: we do not care ending line break, - // it is needed for adding second line, - // so just clean it once at the end when set to value. - p.comment.Write(line) - continue - } - - // Section - if line[0] == '[' { - // Read to the next ']' (TODO: support quoted strings) - closeIdx := bytes.LastIndexByte(line, ']') - if closeIdx == -1 { - return fmt.Errorf("unclosed section: %s", line) - } - - name := string(line[1:closeIdx]) - section, err = f.NewSection(name) - if err != nil { - return err - } - - comment, has := cleanComment(line[closeIdx+1:]) - if has { - p.comment.Write(comment) - } - - section.Comment = strings.TrimSpace(p.comment.String()) - - // Reset aotu-counter and comments - p.comment.Reset() - p.count = 1 - - inUnparseableSection = false - for i := range f.options.UnparseableSections { - if f.options.UnparseableSections[i] == name || - (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) { - inUnparseableSection = true - continue - } - } - continue - } - - if inUnparseableSection { - section.isRawSection = true - section.rawBody += string(line) - continue - } - - kname, offset, err := readKeyName(line) - if err != nil { - // Treat as boolean key when desired, and whole line is key name. - if IsErrDelimiterNotFound(err) { - switch { - case f.options.AllowBooleanKeys: - kname, err := p.readValue(line, - parserBufferSize, - f.options.IgnoreContinuation, - f.options.IgnoreInlineComment, - f.options.UnescapeValueDoubleQuotes, - f.options.UnescapeValueCommentSymbols, - f.options.AllowPythonMultilineValues, - f.options.SpaceBeforeInlineComment) - if err != nil { - return err - } - key, err := section.NewBooleanKey(kname) - if err != nil { - return err - } - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - continue - - case f.options.SkipUnrecognizableLines: - continue - } - } - return err - } - - // Auto increment. - isAutoIncr := false - if kname == "-" { - isAutoIncr = true - kname = "#" + strconv.Itoa(p.count) - p.count++ - } - - value, err := p.readValue(line[offset:], - parserBufferSize, - f.options.IgnoreContinuation, - f.options.IgnoreInlineComment, - f.options.UnescapeValueDoubleQuotes, - f.options.UnescapeValueCommentSymbols, - f.options.AllowPythonMultilineValues, - f.options.SpaceBeforeInlineComment) - if err != nil { - return err - } - isLastValueEmpty = len(value) == 0 - - key, err := section.NewKey(kname, value) - if err != nil { - return err - } - key.isAutoIncrement = isAutoIncr - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - lastRegularKey = key - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/section.go deleted file mode 100644 index 340a1ef..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/section.go +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "errors" - "fmt" - "strings" -) - -// Section represents a config section. -type Section struct { - f *File - Comment string - name string - keys map[string]*Key - keyList []string - keysHash map[string]string - - isRawSection bool - rawBody string -} - -func newSection(f *File, name string) *Section { - return &Section{ - f: f, - name: name, - keys: make(map[string]*Key), - keyList: make([]string, 0, 10), - keysHash: make(map[string]string), - } -} - -// Name returns name of Section. -func (s *Section) Name() string { - return s.name -} - -// Body returns rawBody of Section if the section was marked as unparseable. -// It still follows the other rules of the INI format surrounding leading/trailing whitespace. -func (s *Section) Body() string { - return strings.TrimSpace(s.rawBody) -} - -// SetBody updates body content only if section is raw. -func (s *Section) SetBody(body string) { - if !s.isRawSection { - return - } - s.rawBody = body -} - -// NewKey creates a new key to given section. -func (s *Section) NewKey(name, val string) (*Key, error) { - if len(name) == 0 { - return nil, errors.New("error creating new key: empty key name") - } else if s.f.options.Insensitive { - name = strings.ToLower(name) - } - - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - if inSlice(name, s.keyList) { - if s.f.options.AllowShadows { - if err := s.keys[name].addShadow(val); err != nil { - return nil, err - } - } else { - s.keys[name].value = val - s.keysHash[name] = val - } - return s.keys[name], nil - } - - s.keyList = append(s.keyList, name) - s.keys[name] = newKey(s, name, val) - s.keysHash[name] = val - return s.keys[name], nil -} - -// NewBooleanKey creates a new boolean type key to given section. -func (s *Section) NewBooleanKey(name string) (*Key, error) { - key, err := s.NewKey(name, "true") - if err != nil { - return nil, err - } - - key.isBooleanType = true - return key, nil -} - -// GetKey returns key in section by given name. -func (s *Section) GetKey(name string) (*Key, error) { - // FIXME: change to section level lock? - if s.f.BlockMode { - s.f.lock.RLock() - } - if s.f.options.Insensitive { - name = strings.ToLower(name) - } - key := s.keys[name] - if s.f.BlockMode { - s.f.lock.RUnlock() - } - - if key == nil { - // Check if it is a child-section. - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - return sec.GetKey(name) - } else { - break - } - } - return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) - } - return key, nil -} - -// HasKey returns true if section contains a key with given name. -func (s *Section) HasKey(name string) bool { - key, _ := s.GetKey(name) - return key != nil -} - -// Haskey is a backwards-compatible name for HasKey. -// TODO: delete me in v2 -func (s *Section) Haskey(name string) bool { - return s.HasKey(name) -} - -// HasValue returns true if section contains given raw value. -func (s *Section) HasValue(value string) bool { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - for _, k := range s.keys { - if value == k.value { - return true - } - } - return false -} - -// Key assumes named Key exists in section and returns a zero-value when not. -func (s *Section) Key(name string) *Key { - key, err := s.GetKey(name) - if err != nil { - // It's OK here because the only possible error is empty key name, - // but if it's empty, this piece of code won't be executed. - key, _ = s.NewKey(name, "") - return key - } - return key -} - -// Keys returns list of keys of section. -func (s *Section) Keys() []*Key { - keys := make([]*Key, len(s.keyList)) - for i := range s.keyList { - keys[i] = s.Key(s.keyList[i]) - } - return keys -} - -// ParentKeys returns list of keys of parent section. -func (s *Section) ParentKeys() []*Key { - var parentKeys []*Key - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - parentKeys = append(parentKeys, sec.Keys()...) - } else { - break - } - - } - return parentKeys -} - -// KeyStrings returns list of key names of section. -func (s *Section) KeyStrings() []string { - list := make([]string, len(s.keyList)) - copy(list, s.keyList) - return list -} - -// KeysHash returns keys hash consisting of names and values. -func (s *Section) KeysHash() map[string]string { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - hash := map[string]string{} - for key, value := range s.keysHash { - hash[key] = value - } - return hash -} - -// DeleteKey deletes a key from section. -func (s *Section) DeleteKey(name string) { - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - for i, k := range s.keyList { - if k == name { - s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) - delete(s.keys, name) - return - } - } -} - -// ChildSections returns a list of child sections of current section. -// For example, "[parent.child1]" and "[parent.child12]" are child sections -// of section "[parent]". -func (s *Section) ChildSections() []*Section { - prefix := s.name + "." - children := make([]*Section, 0, 3) - for _, name := range s.f.sectionList { - if strings.HasPrefix(name, prefix) { - children = append(children, s.f.sections[name]) - } - } - return children -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/struct.go deleted file mode 100644 index 9719dc6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-ini/ini/struct.go +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "time" - "unicode" -) - -// NameMapper represents a ini tag name mapper. -type NameMapper func(string) string - -// Built-in name getters. -var ( - // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE. - AllCapsUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - } - newstr = append(newstr, unicode.ToUpper(chr)) - } - return string(newstr) - } - // TitleUnderscore converts to format title_underscore. - TitleUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - chr -= ('A' - 'a') - } - newstr = append(newstr, chr) - } - return string(newstr) - } -) - -func (s *Section) parseFieldName(raw, actual string) string { - if len(actual) > 0 { - return actual - } - if s.f.NameMapper != nil { - return s.f.NameMapper(raw) - } - return raw -} - -func parseDelim(actual string) string { - if len(actual) > 0 { - return actual - } - return "," -} - -var reflectTime = reflect.TypeOf(time.Now()).Kind() - -// setSliceWithProperType sets proper values to slice based on its type. -func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { - var strs []string - if allowShadow { - strs = key.StringsWithShadows(delim) - } else { - strs = key.Strings(delim) - } - - numVals := len(strs) - if numVals == 0 { - return nil - } - - var vals interface{} - var err error - - sliceOf := field.Type().Elem().Kind() - switch sliceOf { - case reflect.String: - vals = strs - case reflect.Int: - vals, err = key.parseInts(strs, true, false) - case reflect.Int64: - vals, err = key.parseInt64s(strs, true, false) - case reflect.Uint: - vals, err = key.parseUints(strs, true, false) - case reflect.Uint64: - vals, err = key.parseUint64s(strs, true, false) - case reflect.Float64: - vals, err = key.parseFloat64s(strs, true, false) - case reflectTime: - vals, err = key.parseTimesFormat(time.RFC3339, strs, true, false) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - if err != nil && isStrict { - return err - } - - slice := reflect.MakeSlice(field.Type(), numVals, numVals) - for i := 0; i < numVals; i++ { - switch sliceOf { - case reflect.String: - slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i])) - case reflect.Int: - slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i])) - case reflect.Int64: - slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i])) - case reflect.Uint: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i])) - case reflect.Uint64: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i])) - case reflect.Float64: - slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i])) - case reflectTime: - slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i])) - } - } - field.Set(slice) - return nil -} - -func wrapStrictError(err error, isStrict bool) error { - if isStrict { - return err - } - return nil -} - -// setWithProperType sets proper value to field based on its type, -// but it does not return error for failing parsing, -// because we want to use default value that is already assigned to strcut. -func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { - switch t.Kind() { - case reflect.String: - if len(key.String()) == 0 { - return nil - } - field.SetString(key.String()) - case reflect.Bool: - boolVal, err := key.Bool() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetBool(boolVal) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int64(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - intVal, err := key.Int64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetInt(intVal) - // byte is an alias for uint8, so supporting uint8 breaks support for byte - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - uintVal, err := key.Uint64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetUint(uintVal) - - case reflect.Float32, reflect.Float64: - floatVal, err := key.Float64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetFloat(floatVal) - case reflectTime: - timeVal, err := key.Time() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.Set(reflect.ValueOf(timeVal)) - case reflect.Slice: - return setSliceWithProperType(key, field, delim, allowShadow, isStrict) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) { - opts := strings.SplitN(tag, ",", 3) - rawName = opts[0] - if len(opts) > 1 { - omitEmpty = opts[1] == "omitempty" - } - if len(opts) > 2 { - allowShadow = opts[2] == "allowshadow" - } - return rawName, omitEmpty, allowShadow -} - -func (s *Section) mapTo(val reflect.Value, isStrict bool) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - rawName, _, allowShadow := parseTagOptions(tag) - fieldName := s.parseFieldName(tpField.Name, rawName) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous - isStruct := tpField.Type.Kind() == reflect.Struct - if isAnonymous { - field.Set(reflect.New(tpField.Type.Elem())) - } - - if isAnonymous || isStruct { - if sec, err := s.f.GetSection(fieldName); err == nil { - if err = sec.mapTo(field, isStrict); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - continue - } - } - - if key, err := s.GetKey(fieldName); err == nil { - delim := parseDelim(tpField.Tag.Get("delim")) - if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - } - } - return nil -} - -// MapTo maps section to given struct. -func (s *Section) MapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val, false) -} - -// MapTo maps section to given struct in strict mode, -// which returns all possible error including value parsing error. -func (s *Section) StrictMapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val, true) -} - -// MapTo maps file to given struct. -func (f *File) MapTo(v interface{}) error { - return f.Section("").MapTo(v) -} - -// MapTo maps file to given struct in strict mode, -// which returns all possible error including value parsing error. -func (f *File) StrictMapTo(v interface{}) error { - return f.Section("").StrictMapTo(v) -} - -// MapTo maps data sources to given struct with name mapper. -func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.MapTo(v) -} - -// StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode, -// which returns all possible error including value parsing error. -func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.StrictMapTo(v) -} - -// MapTo maps data sources to given struct. -func MapTo(v, source interface{}, others ...interface{}) error { - return MapToWithMapper(v, nil, source, others...) -} - -// StrictMapTo maps data sources to given struct in strict mode, -// which returns all possible error including value parsing error. -func StrictMapTo(v, source interface{}, others ...interface{}) error { - return StrictMapToWithMapper(v, nil, source, others...) -} - -// reflectSliceWithProperType does the opposite thing as setSliceWithProperType. -func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { - slice := field.Slice(0, field.Len()) - if field.Len() == 0 { - return nil - } - - var buf bytes.Buffer - sliceOf := field.Type().Elem().Kind() - for i := 0; i < field.Len(); i++ { - switch sliceOf { - case reflect.String: - buf.WriteString(slice.Index(i).String()) - case reflect.Int, reflect.Int64: - buf.WriteString(fmt.Sprint(slice.Index(i).Int())) - case reflect.Uint, reflect.Uint64: - buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) - case reflect.Float64: - buf.WriteString(fmt.Sprint(slice.Index(i).Float())) - case reflectTime: - buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - buf.WriteString(delim) - } - key.SetValue(buf.String()[:buf.Len()-1]) - return nil -} - -// reflectWithProperType does the opposite thing as setWithProperType. -func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { - switch t.Kind() { - case reflect.String: - key.SetValue(field.String()) - case reflect.Bool: - key.SetValue(fmt.Sprint(field.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - key.SetValue(fmt.Sprint(field.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - key.SetValue(fmt.Sprint(field.Uint())) - case reflect.Float32, reflect.Float64: - key.SetValue(fmt.Sprint(field.Float())) - case reflectTime: - key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) - case reflect.Slice: - return reflectSliceWithProperType(key, field, delim) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -// CR: copied from encoding/json/encode.go with modifications of time.Time support. -// TODO: add more test coverage. -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() - case reflectTime: - t, ok := v.Interface().(time.Time) - return ok && t.IsZero() - } - return false -} - -func (s *Section) reflectFrom(val reflect.Value) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - opts := strings.SplitN(tag, ",", 2) - if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) { - continue - } - - fieldName := s.parseFieldName(tpField.Name, opts[0]) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) || - (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") { - // Note: The only error here is section doesn't exist. - sec, err := s.f.GetSection(fieldName) - if err != nil { - // Note: fieldName can never be empty here, ignore error. - sec, _ = s.f.NewSection(fieldName) - } - - // Add comment from comment tag - if len(sec.Comment) == 0 { - sec.Comment = tpField.Tag.Get("comment") - } - - if err = sec.reflectFrom(field); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - continue - } - - // Note: Same reason as secion. - key, err := s.GetKey(fieldName) - if err != nil { - key, _ = s.NewKey(fieldName, "") - } - - // Add comment from comment tag - if len(key.Comment) == 0 { - key.Comment = tpField.Tag.Get("comment") - } - - if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - - } - return nil -} - -// ReflectFrom reflects secion from given struct. -func (s *Section) ReflectFrom(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot reflect from non-pointer struct") - } - - return s.reflectFrom(val) -} - -// ReflectFrom reflects file from given struct. -func (f *File) ReflectFrom(v interface{}) error { - return f.Section("").ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct with name mapper. -func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { - cfg.NameMapper = mapper - return cfg.ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct. -func ReflectFrom(cfg *File, v interface{}) error { - return ReflectFromWithMapper(cfg, v, nil) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/LICENSE deleted file mode 100644 index 6ae89ae..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2018 Jeevanandam M., https://myjeeva.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/client.go deleted file mode 100644 index a10a520..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/client.go +++ /dev/null @@ -1,890 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "compress/gzip" - "crypto/tls" - "crypto/x509" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "net/url" - "reflect" - "regexp" - "strings" - "sync" - "time" -) - -const ( - // MethodGet HTTP method - MethodGet = "GET" - - // MethodPost HTTP method - MethodPost = "POST" - - // MethodPut HTTP method - MethodPut = "PUT" - - // MethodDelete HTTP method - MethodDelete = "DELETE" - - // MethodPatch HTTP method - MethodPatch = "PATCH" - - // MethodHead HTTP method - MethodHead = "HEAD" - - // MethodOptions HTTP method - MethodOptions = "OPTIONS" -) - -var ( - hdrUserAgentKey = http.CanonicalHeaderKey("User-Agent") - hdrAcceptKey = http.CanonicalHeaderKey("Accept") - hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type") - hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length") - hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding") - hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization") - - plainTextType = "text/plain; charset=utf-8" - jsonContentType = "application/json; charset=utf-8" - formContentType = "application/x-www-form-urlencoded" - - jsonCheck = regexp.MustCompile(`(?i:(application|text)/(problem\+json|json))`) - xmlCheck = regexp.MustCompile(`(?i:(application|text)/(problem\+xml|xml))`) - - hdrUserAgentValue = "go-resty v%s - https://github.com/go-resty/resty" - bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }} -) - -// Client type is used for HTTP/RESTful global values -// for all request raised from the client -type Client struct { - HostURL string - QueryParam url.Values - FormData url.Values - Header http.Header - UserInfo *User - Token string - Cookies []*http.Cookie - Error reflect.Type - Debug bool - DisableWarn bool - AllowGetMethodPayload bool - Log *log.Logger - RetryCount int - RetryWaitTime time.Duration - RetryMaxWaitTime time.Duration - RetryConditions []RetryConditionFunc - JSONMarshal func(v interface{}) ([]byte, error) - JSONUnmarshal func(data []byte, v interface{}) error - - httpClient *http.Client - setContentLength bool - isHTTPMode bool - outputDirectory string - scheme string - proxyURL *url.URL - closeConnection bool - notParseResponse bool - debugBodySizeLimit int64 - logPrefix string - pathParams map[string]string - beforeRequest []func(*Client, *Request) error - udBeforeRequest []func(*Client, *Request) error - preReqHook func(*Client, *Request) error - afterResponse []func(*Client, *Response) error -} - -// User type is to hold an username and password information -type User struct { - Username, Password string -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Client methods -//___________________________________ - -// SetHostURL method is to set Host URL in the client instance. It will be used with request -// raised from this client with relative URL -// // Setting HTTP address -// resty.SetHostURL("http://myjeeva.com") -// -// // Setting HTTPS address -// resty.SetHostURL("https://myjeeva.com") -// -func (c *Client) SetHostURL(url string) *Client { - c.HostURL = strings.TrimRight(url, "/") - return c -} - -// SetHeader method sets a single header field and its value in the client instance. -// These headers will be applied to all requests raised from this client instance. -// Also it can be overridden at request level header options, see `resty.R().SetHeader` -// or `resty.R().SetHeaders`. -// -// Example: To set `Content-Type` and `Accept` as `application/json` -// -// resty. -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") -// -func (c *Client) SetHeader(header, value string) *Client { - c.Header.Set(header, value) - return c -} - -// SetHeaders method sets multiple headers field and its values at one go in the client instance. -// These headers will be applied to all requests raised from this client instance. Also it can be -// overridden at request level headers options, see `resty.R().SetHeaders` or `resty.R().SetHeader`. -// -// Example: To set `Content-Type` and `Accept` as `application/json` -// -// resty.SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) -// -func (c *Client) SetHeaders(headers map[string]string) *Client { - for h, v := range headers { - c.Header.Set(h, v) - } - - return c -} - -// SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default. -// Example: sometimes we don't want to save cookies in api contacting, we can remove the default -// CookieJar in resty client. -// -// resty.SetCookieJar(nil) -// -func (c *Client) SetCookieJar(jar http.CookieJar) *Client { - c.httpClient.Jar = jar - return c -} - -// SetCookie method appends a single cookie in the client instance. -// These cookies will be added to all the request raised from this client instance. -// resty.SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// Path: "/", -// Domain: "sample.com", -// MaxAge: 36000, -// HttpOnly: true, -// Secure: false, -// }) -// -func (c *Client) SetCookie(hc *http.Cookie) *Client { - c.Cookies = append(c.Cookies, hc) - return c -} - -// SetCookies method sets an array of cookies in the client instance. -// These cookies will be added to all the request raised from this client instance. -// cookies := make([]*http.Cookie, 0) -// -// cookies = append(cookies, &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// Path: "/", -// Domain: "sample.com", -// MaxAge: 36000, -// HttpOnly: true, -// Secure: false, -// }) -// -// cookies = append(cookies, &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// Path: "/", -// Domain: "sample.com", -// MaxAge: 36000, -// HttpOnly: true, -// Secure: false, -// }) -// -// // Setting a cookies into resty -// resty.SetCookies(cookies) -// -func (c *Client) SetCookies(cs []*http.Cookie) *Client { - c.Cookies = append(c.Cookies, cs...) - return c -} - -// SetQueryParam method sets single parameter and its value in the client instance. -// It will be formed as query string for the request. For example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from -// this client instance. Also it can be overridden at request level Query Param options, -// see `resty.R().SetQueryParam` or `resty.R().SetQueryParams`. -// resty. -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") -// -func (c *Client) SetQueryParam(param, value string) *Client { - c.QueryParam.Set(param, value) - return c -} - -// SetQueryParams method sets multiple parameters and their values at one go in the client instance. -// It will be formed as query string for the request. For example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from this -// client instance. Also it can be overridden at request level Query Param options, -// see `resty.R().SetQueryParams` or `resty.R().SetQueryParam`. -// resty.SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) -// -func (c *Client) SetQueryParams(params map[string]string) *Client { - for p, v := range params { - c.SetQueryParam(p, v) - } - - return c -} - -// SetFormData method sets Form parameters and their values in the client instance. -// It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as -// `application/x-www-form-urlencoded`. These form data will be added to all the request raised from -// this client instance. Also it can be overridden at request level form data, see `resty.R().SetFormData`. -// resty.SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) -// -func (c *Client) SetFormData(data map[string]string) *Client { - for k, v := range data { - c.FormData.Set(k, v) - } - - return c -} - -// SetBasicAuth method sets the basic authentication header in the HTTP request. Example: -// Authorization: Basic -// -// Example: To set the header for username "go-resty" and password "welcome" -// resty.SetBasicAuth("go-resty", "welcome") -// -// This basic auth information gets added to all the request rasied from this client instance. -// Also it can be overridden or set one at the request level is supported, see `resty.R().SetBasicAuth`. -// -func (c *Client) SetBasicAuth(username, password string) *Client { - c.UserInfo = &User{Username: username, Password: password} - return c -} - -// SetAuthToken method sets bearer auth token header in the HTTP request. Example: -// Authorization: Bearer -// -// Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F -// -// resty.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") -// -// This bearer auth token gets added to all the request rasied from this client instance. -// Also it can be overridden or set one at the request level is supported, see `resty.R().SetAuthToken`. -// -func (c *Client) SetAuthToken(token string) *Client { - c.Token = token - return c -} - -// R method creates a request instance, its used for Get, Post, Put, Delete, Patch, Head and Options. -func (c *Client) R() *Request { - r := &Request{ - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - - client: c, - multipartFiles: []*File{}, - multipartFields: []*multipartField{}, - pathParams: map[string]string{}, - } - - return r -} - -// NewRequest is an alias for R(). Creates a request instance, its used for -// Get, Post, Put, Delete, Patch, Head and Options. -func (c *Client) NewRequest() *Request { - return c.R() -} - -// OnBeforeRequest method appends request middleware into the before request chain. -// Its gets applied after default `go-resty` request middlewares and before request -// been sent from `go-resty` to host server. -// resty.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { -// // Now you have access to Client and Request instance -// // manipulate it as per your need -// -// return nil // if its success otherwise return error -// }) -// -func (c *Client) OnBeforeRequest(m func(*Client, *Request) error) *Client { - c.udBeforeRequest = append(c.udBeforeRequest, m) - return c -} - -// OnAfterResponse method appends response middleware into the after response chain. -// Once we receive response from host server, default `go-resty` response middleware -// gets applied and then user assigened response middlewares applied. -// resty.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { -// // Now you have access to Client and Response instance -// // manipulate it as per your need -// -// return nil // if its success otherwise return error -// }) -// -func (c *Client) OnAfterResponse(m func(*Client, *Response) error) *Client { - c.afterResponse = append(c.afterResponse, m) - return c -} - -// SetPreRequestHook method sets the given pre-request function into resty client. -// It is called right before the request is fired. -// -// Note: Only one pre-request hook can be registered. Use `resty.OnBeforeRequest` for mutilple. -func (c *Client) SetPreRequestHook(h func(*Client, *Request) error) *Client { - if c.preReqHook != nil { - c.Log.Printf("Overwriting an existing pre-request hook: %s", functionName(h)) - } - c.preReqHook = h - return c -} - -// SetDebug method enables the debug mode on `go-resty` client. Client logs details of every request and response. -// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. -// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. -// resty.SetDebug(true) -// -func (c *Client) SetDebug(d bool) *Client { - c.Debug = d - return c -} - -// SetDebugBodyLimit sets the maximum size for which the response body will be logged in debug mode. -// resty.SetDebugBodyLimit(1000000) -// -func (c *Client) SetDebugBodyLimit(sl int64) *Client { - c.debugBodySizeLimit = sl - return c -} - -// SetDisableWarn method disables the warning message on `go-resty` client. -// For example: go-resty warns the user when BasicAuth used on HTTP mode. -// resty.SetDisableWarn(true) -// -func (c *Client) SetDisableWarn(d bool) *Client { - c.DisableWarn = d - return c -} - -// SetAllowGetMethodPayload method allows the GET method with payload on `go-resty` client. -// For example: go-resty allows the user sends request with a payload on HTTP GET method. -// resty.SetAllowGetMethodPayload(true) -// -func (c *Client) SetAllowGetMethodPayload(a bool) *Client { - c.AllowGetMethodPayload = a - return c -} - -// SetLogger method sets given writer for logging go-resty request and response details. -// Default is os.Stderr -// file, _ := os.OpenFile("/Users/jeeva/go-resty.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) -// -// resty.SetLogger(file) -// -func (c *Client) SetLogger(w io.Writer) *Client { - c.Log = getLogger(w) - return c -} - -// SetContentLength method enables the HTTP header `Content-Length` value for every request. -// By default go-resty won't set `Content-Length`. -// resty.SetContentLength(true) -// -// Also you have an option to enable for particular request. See `resty.R().SetContentLength` -// -func (c *Client) SetContentLength(l bool) *Client { - c.setContentLength = l - return c -} - -// SetTimeout method sets timeout for request raised from client. -// resty.SetTimeout(time.Duration(1 * time.Minute)) -// -func (c *Client) SetTimeout(timeout time.Duration) *Client { - c.httpClient.Timeout = timeout - return c -} - -// SetError method is to register the global or client common `Error` object into go-resty. -// It is used for automatic unmarshalling if response status code is greater than 399 and -// content type either JSON or XML. Can be pointer or non-pointer. -// resty.SetError(&Error{}) -// // OR -// resty.SetError(Error{}) -// -func (c *Client) SetError(err interface{}) *Client { - c.Error = typeOf(err) - return c -} - -// SetRedirectPolicy method sets the client redirect poilicy. go-resty provides ready to use -// redirect policies. Wanna create one for yourself refer `redirect.go`. -// -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) -// -// // Need multiple redirect policies together -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net")) -// -func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client { - for _, p := range policies { - if _, ok := p.(RedirectPolicy); !ok { - c.Log.Printf("ERORR: %v does not implement resty.RedirectPolicy (missing Apply method)", - functionName(p)) - } - } - - c.httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { - for _, p := range policies { - if err := p.(RedirectPolicy).Apply(req, via); err != nil { - return err - } - } - return nil // looks good, go ahead - } - - return c -} - -// SetRetryCount method enables retry on `go-resty` client and allows you -// to set no. of retry count. Resty uses a Backoff mechanism. -func (c *Client) SetRetryCount(count int) *Client { - c.RetryCount = count - return c -} - -// SetRetryWaitTime method sets default wait time to sleep before retrying -// request. -// Default is 100 milliseconds. -func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client { - c.RetryWaitTime = waitTime - return c -} - -// SetRetryMaxWaitTime method sets max wait time to sleep before retrying -// request. -// Default is 2 seconds. -func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client { - c.RetryMaxWaitTime = maxWaitTime - return c -} - -// AddRetryCondition method adds a retry condition function to array of functions -// that are checked to determine if the request is retried. The request will -// retry if any of the functions return true and error is nil. -func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client { - c.RetryConditions = append(c.RetryConditions, condition) - return c -} - -// SetHTTPMode method sets go-resty mode to 'http' -func (c *Client) SetHTTPMode() *Client { - return c.SetMode("http") -} - -// SetRESTMode method sets go-resty mode to 'rest' -func (c *Client) SetRESTMode() *Client { - return c.SetMode("rest") -} - -// SetMode method sets go-resty client mode to given value such as 'http' & 'rest'. -// 'rest': -// - No Redirect -// - Automatic response unmarshal if it is JSON or XML -// 'http': -// - Up to 10 Redirects -// - No automatic unmarshall. Response will be treated as `response.String()` -// -// If you want more redirects, use FlexibleRedirectPolicy -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) -// -func (c *Client) SetMode(mode string) *Client { - // HTTP - if mode == "http" { - c.isHTTPMode = true - c.SetRedirectPolicy(FlexibleRedirectPolicy(10)) - c.afterResponse = []func(*Client, *Response) error{ - responseLogger, - saveResponseIntoFile, - } - return c - } - - // RESTful - c.isHTTPMode = false - c.SetRedirectPolicy(NoRedirectPolicy()) - c.afterResponse = []func(*Client, *Response) error{ - responseLogger, - parseResponseBody, - saveResponseIntoFile, - } - return c -} - -// Mode method returns the current client mode. Typically its a "http" or "rest". -// Default is "rest" -func (c *Client) Mode() string { - if c.isHTTPMode { - return "http" - } - return "rest" -} - -// SetTLSClientConfig method sets TLSClientConfig for underling client Transport. -// -// Example: -// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial -// resty.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) -// -// // or One can disable security check (https) -// resty.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) -// Note: This method overwrites existing `TLSClientConfig`. -// -func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { - transport, err := c.getTransport() - if err != nil { - c.Log.Printf("ERROR %v", err) - return c - } - transport.TLSClientConfig = config - return c -} - -// SetProxy method sets the Proxy URL and Port for resty client. -// resty.SetProxy("http://proxyserver:8888") -// -// Alternatives: At request level proxy, see `Request.SetProxy`. OR Without this `SetProxy` method, -// you can also set Proxy via environment variable. By default `Go` uses setting from `HTTP_PROXY`. -// -func (c *Client) SetProxy(proxyURL string) *Client { - transport, err := c.getTransport() - if err != nil { - c.Log.Printf("ERROR %v", err) - return c - } - - if pURL, err := url.Parse(proxyURL); err == nil { - c.proxyURL = pURL - transport.Proxy = http.ProxyURL(c.proxyURL) - } else { - c.Log.Printf("ERROR %v", err) - c.RemoveProxy() - } - return c -} - -// RemoveProxy method removes the proxy configuration from resty client -// resty.RemoveProxy() -// -func (c *Client) RemoveProxy() *Client { - transport, err := c.getTransport() - if err != nil { - c.Log.Printf("ERROR %v", err) - return c - } - c.proxyURL = nil - transport.Proxy = nil - return c -} - -// SetCertificates method helps to set client certificates into resty conveniently. -// -func (c *Client) SetCertificates(certs ...tls.Certificate) *Client { - config, err := c.getTLSConfig() - if err != nil { - c.Log.Printf("ERROR %v", err) - return c - } - config.Certificates = append(config.Certificates, certs...) - return c -} - -// SetRootCertificate method helps to add one or more root certificates into resty client -// resty.SetRootCertificate("/path/to/root/pemFile.pem") -// -func (c *Client) SetRootCertificate(pemFilePath string) *Client { - rootPemData, err := ioutil.ReadFile(pemFilePath) - if err != nil { - c.Log.Printf("ERROR %v", err) - return c - } - - config, err := c.getTLSConfig() - if err != nil { - c.Log.Printf("ERROR %v", err) - return c - } - if config.RootCAs == nil { - config.RootCAs = x509.NewCertPool() - } - - config.RootCAs.AppendCertsFromPEM(rootPemData) - - return c -} - -// SetOutputDirectory method sets output directory for saving HTTP response into file. -// If the output directory not exists then resty creates one. This setting is optional one, -// if you're planning using absoule path in `Request.SetOutput` and can used together. -// resty.SetOutputDirectory("/save/http/response/here") -// -func (c *Client) SetOutputDirectory(dirPath string) *Client { - c.outputDirectory = dirPath - return c -} - -// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` -// compatible interface implementation in the resty client. -// -// NOTE: -// -// - If transport is not type of `*http.Transport` then you may not be able to -// take advantage of some of the `resty` client settings. -// -// - It overwrites the resty client transport instance and it's configurations. -// -// transport := &http.Transport{ -// // somthing like Proxying to httptest.Server, etc... -// Proxy: func(req *http.Request) (*url.URL, error) { -// return url.Parse(server.URL) -// }, -// } -// -// resty.SetTransport(transport) -// -func (c *Client) SetTransport(transport http.RoundTripper) *Client { - if transport != nil { - c.httpClient.Transport = transport - } - return c -} - -// SetScheme method sets custom scheme in the resty client. It's way to override default. -// resty.SetScheme("http") -// -func (c *Client) SetScheme(scheme string) *Client { - if !IsStringEmpty(scheme) { - c.scheme = scheme - } - - return c -} - -// SetCloseConnection method sets variable `Close` in http request struct with the given -// value. More info: https://golang.org/src/net/http/request.go -func (c *Client) SetCloseConnection(close bool) *Client { - c.closeConnection = close - return c -} - -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, -// otherwise you might get into connection leaks, no connection reuse. -// -// Please Note: Response middlewares are not applicable, if you use this option. Basically you have -// taken over the control of response parsing from `Resty`. -func (c *Client) SetDoNotParseResponse(parse bool) *Client { - c.notParseResponse = parse - return c -} - -// SetLogPrefix method sets the Resty logger prefix value. -func (c *Client) SetLogPrefix(prefix string) *Client { - c.logPrefix = prefix - c.Log.SetPrefix(prefix) - return c -} - -// SetPathParams method sets multiple URL path key-value pairs at one go in the -// resty client instance. -// resty.SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details -// It replace the value of the key while composing request URL. Also it can be -// overridden at request level Path Params options, see `Request.SetPathParams`. -func (c *Client) SetPathParams(params map[string]string) *Client { - for p, v := range params { - c.pathParams[p] = v - } - return c -} - -// IsProxySet method returns the true if proxy is set on client otherwise false. -func (c *Client) IsProxySet() bool { - return c.proxyURL != nil -} - -// GetClient method returns the current http.Client used by the resty client. -func (c *Client) GetClient() *http.Client { - return c.httpClient -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Client Unexported methods -//___________________________________ - -// executes the given `Request` object and returns response -func (c *Client) execute(req *Request) (*Response, error) { - defer releaseBuffer(req.bodyBuf) - // Apply Request middleware - var err error - - // user defined on before request methods - // to modify the *resty.Request object - for _, f := range c.udBeforeRequest { - if err = f(c, req); err != nil { - return nil, err - } - } - - // resty middlewares - for _, f := range c.beforeRequest { - if err = f(c, req); err != nil { - return nil, err - } - } - - // call pre-request if defined - if c.preReqHook != nil { - if err = c.preReqHook(c, req); err != nil { - return nil, err - } - } - - if hostHeader := req.Header.Get("Host"); hostHeader != "" { - req.RawRequest.Host = hostHeader - } - - req.Time = time.Now() - resp, err := c.httpClient.Do(req.RawRequest) - - response := &Response{ - Request: req, - RawResponse: resp, - receivedAt: time.Now(), - } - - if err != nil || req.notParseResponse || c.notParseResponse { - return response, err - } - - if !req.isSaveResponse { - defer closeq(resp.Body) - body := resp.Body - - // GitHub #142 - if strings.EqualFold(resp.Header.Get(hdrContentEncodingKey), "gzip") && resp.ContentLength > 0 { - if _, ok := body.(*gzip.Reader); !ok { - body, err = gzip.NewReader(body) - if err != nil { - return response, err - } - defer closeq(body) - } - } - - if response.body, err = ioutil.ReadAll(body); err != nil { - return response, err - } - - response.size = int64(len(response.body)) - } - - // Apply Response middleware - for _, f := range c.afterResponse { - if err = f(c, response); err != nil { - break - } - } - - return response, err -} - -// enables a log prefix -func (c *Client) enableLogPrefix() { - c.Log.SetFlags(log.LstdFlags) - c.Log.SetPrefix(c.logPrefix) -} - -// disables a log prefix -func (c *Client) disableLogPrefix() { - c.Log.SetFlags(0) - c.Log.SetPrefix("") -} - -// getting TLS client config if not exists then create one -func (c *Client) getTLSConfig() (*tls.Config, error) { - transport, err := c.getTransport() - if err != nil { - return nil, err - } - if transport.TLSClientConfig == nil { - transport.TLSClientConfig = &tls.Config{} - } - return transport.TLSClientConfig, nil -} - -// returns `*http.Transport` currently in use or error -// in case currently used `transport` is not an `*http.Transport` -func (c *Client) getTransport() (*http.Transport, error) { - if c.httpClient.Transport == nil { - c.SetTransport(new(http.Transport)) - } - - if transport, ok := c.httpClient.Transport.(*http.Transport); ok { - return transport, nil - } - return nil, errors.New("current transport is not an *http.Transport instance") -} - -// -// File -// - -// File represent file information for multipart request -type File struct { - Name string - ParamName string - io.Reader -} - -// String returns string value of current file details -func (f *File) String() string { - return fmt.Sprintf("ParamName: %v; FileName: %v", f.ParamName, f.Name) -} - -// multipartField represent custom data part for multipart request -type multipartField struct { - Param string - FileName string - ContentType string - io.Reader -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/default.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/default.go deleted file mode 100644 index 6f6d918..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/default.go +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "crypto/tls" - "encoding/json" - "io" - "math" - "net/http" - "net/http/cookiejar" - "net/url" - "os" - "time" - - "golang.org/x/net/publicsuffix" -) - -// DefaultClient of resty -var DefaultClient *Client - -// New method creates a new go-resty client. -func New() *Client { - cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) - return createClient(&http.Client{Jar: cookieJar}) -} - -// NewWithClient method create a new go-resty client with given `http.Client`. -func NewWithClient(hc *http.Client) *Client { - return createClient(hc) -} - -// R creates a new resty request object, it is used form a HTTP/RESTful request -// such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS. -func R() *Request { - return DefaultClient.R() -} - -// NewRequest is an alias for R(). Creates a new resty request object, it is used form a HTTP/RESTful request -// such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS. -func NewRequest() *Request { - return R() -} - -// SetHostURL sets Host URL. See `Client.SetHostURL for more information. -func SetHostURL(url string) *Client { - return DefaultClient.SetHostURL(url) -} - -// SetHeader sets single header. See `Client.SetHeader` for more information. -func SetHeader(header, value string) *Client { - return DefaultClient.SetHeader(header, value) -} - -// SetHeaders sets multiple headers. See `Client.SetHeaders` for more information. -func SetHeaders(headers map[string]string) *Client { - return DefaultClient.SetHeaders(headers) -} - -// SetCookieJar sets custom http.CookieJar. See `Client.SetCookieJar` for more information. -func SetCookieJar(jar http.CookieJar) *Client { - return DefaultClient.SetCookieJar(jar) -} - -// SetCookie sets single cookie object. See `Client.SetCookie` for more information. -func SetCookie(hc *http.Cookie) *Client { - return DefaultClient.SetCookie(hc) -} - -// SetCookies sets multiple cookie object. See `Client.SetCookies` for more information. -func SetCookies(cs []*http.Cookie) *Client { - return DefaultClient.SetCookies(cs) -} - -// SetQueryParam method sets single parameter and its value. See `Client.SetQueryParam` for more information. -func SetQueryParam(param, value string) *Client { - return DefaultClient.SetQueryParam(param, value) -} - -// SetQueryParams method sets multiple parameters and its value. See `Client.SetQueryParams` for more information. -func SetQueryParams(params map[string]string) *Client { - return DefaultClient.SetQueryParams(params) -} - -// SetFormData method sets Form parameters and its values. See `Client.SetFormData` for more information. -func SetFormData(data map[string]string) *Client { - return DefaultClient.SetFormData(data) -} - -// SetBasicAuth method sets the basic authentication header. See `Client.SetBasicAuth` for more information. -func SetBasicAuth(username, password string) *Client { - return DefaultClient.SetBasicAuth(username, password) -} - -// SetAuthToken method sets bearer auth token header. See `Client.SetAuthToken` for more information. -func SetAuthToken(token string) *Client { - return DefaultClient.SetAuthToken(token) -} - -// OnBeforeRequest method sets request middleware. See `Client.OnBeforeRequest` for more information. -func OnBeforeRequest(m func(*Client, *Request) error) *Client { - return DefaultClient.OnBeforeRequest(m) -} - -// OnAfterResponse method sets response middleware. See `Client.OnAfterResponse` for more information. -func OnAfterResponse(m func(*Client, *Response) error) *Client { - return DefaultClient.OnAfterResponse(m) -} - -// SetPreRequestHook method sets the pre-request hook. See `Client.SetPreRequestHook` for more information. -func SetPreRequestHook(h func(*Client, *Request) error) *Client { - return DefaultClient.SetPreRequestHook(h) -} - -// SetDebug method enables the debug mode. See `Client.SetDebug` for more information. -func SetDebug(d bool) *Client { - return DefaultClient.SetDebug(d) -} - -// SetDebugBodyLimit method sets the response body limit for debug mode. See `Client.SetDebugBodyLimit` for more information. -func SetDebugBodyLimit(sl int64) *Client { - return DefaultClient.SetDebugBodyLimit(sl) -} - -// SetAllowGetMethodPayload method allows the GET method with payload. See `Client.SetAllowGetMethodPayload` for more information. -func SetAllowGetMethodPayload(a bool) *Client { - return DefaultClient.SetAllowGetMethodPayload(a) -} - -// SetRetryCount method sets the retry count. See `Client.SetRetryCount` for more information. -func SetRetryCount(count int) *Client { - return DefaultClient.SetRetryCount(count) -} - -// SetRetryWaitTime method sets the retry wait time. See `Client.SetRetryWaitTime` for more information. -func SetRetryWaitTime(waitTime time.Duration) *Client { - return DefaultClient.SetRetryWaitTime(waitTime) -} - -// SetRetryMaxWaitTime method sets the retry max wait time. See `Client.SetRetryMaxWaitTime` for more information. -func SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client { - return DefaultClient.SetRetryMaxWaitTime(maxWaitTime) -} - -// AddRetryCondition method appends check function for retry. See `Client.AddRetryCondition` for more information. -func AddRetryCondition(condition RetryConditionFunc) *Client { - return DefaultClient.AddRetryCondition(condition) -} - -// SetDisableWarn method disables warning comes from `go-resty` client. See `Client.SetDisableWarn` for more information. -func SetDisableWarn(d bool) *Client { - return DefaultClient.SetDisableWarn(d) -} - -// SetLogger method sets given writer for logging. See `Client.SetLogger` for more information. -func SetLogger(w io.Writer) *Client { - return DefaultClient.SetLogger(w) -} - -// SetContentLength method enables `Content-Length` value. See `Client.SetContentLength` for more information. -func SetContentLength(l bool) *Client { - return DefaultClient.SetContentLength(l) -} - -// SetError method is to register the global or client common `Error` object. See `Client.SetError` for more information. -func SetError(err interface{}) *Client { - return DefaultClient.SetError(err) -} - -// SetRedirectPolicy method sets the client redirect poilicy. See `Client.SetRedirectPolicy` for more information. -func SetRedirectPolicy(policies ...interface{}) *Client { - return DefaultClient.SetRedirectPolicy(policies...) -} - -// SetHTTPMode method sets go-resty mode into HTTP. See `Client.SetMode` for more information. -func SetHTTPMode() *Client { - return DefaultClient.SetHTTPMode() -} - -// SetRESTMode method sets go-resty mode into RESTful. See `Client.SetMode` for more information. -func SetRESTMode() *Client { - return DefaultClient.SetRESTMode() -} - -// Mode method returns the current client mode. See `Client.Mode` for more information. -func Mode() string { - return DefaultClient.Mode() -} - -// SetTLSClientConfig method sets TLSClientConfig for underling client Transport. See `Client.SetTLSClientConfig` for more information. -func SetTLSClientConfig(config *tls.Config) *Client { - return DefaultClient.SetTLSClientConfig(config) -} - -// SetTimeout method sets timeout for request. See `Client.SetTimeout` for more information. -func SetTimeout(timeout time.Duration) *Client { - return DefaultClient.SetTimeout(timeout) -} - -// SetProxy method sets Proxy for request. See `Client.SetProxy` for more information. -func SetProxy(proxyURL string) *Client { - return DefaultClient.SetProxy(proxyURL) -} - -// RemoveProxy method removes the proxy configuration. See `Client.RemoveProxy` for more information. -func RemoveProxy() *Client { - return DefaultClient.RemoveProxy() -} - -// SetCertificates method helps to set client certificates into resty conveniently. -// See `Client.SetCertificates` for more information and example. -func SetCertificates(certs ...tls.Certificate) *Client { - return DefaultClient.SetCertificates(certs...) -} - -// SetRootCertificate method helps to add one or more root certificates into resty client. -// See `Client.SetRootCertificate` for more information. -func SetRootCertificate(pemFilePath string) *Client { - return DefaultClient.SetRootCertificate(pemFilePath) -} - -// SetOutputDirectory method sets output directory. See `Client.SetOutputDirectory` for more information. -func SetOutputDirectory(dirPath string) *Client { - return DefaultClient.SetOutputDirectory(dirPath) -} - -// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` -// compatible interface implementation in the resty client. -// See `Client.SetTransport` for more information. -func SetTransport(transport http.RoundTripper) *Client { - return DefaultClient.SetTransport(transport) -} - -// SetScheme method sets custom scheme in the resty client. -// See `Client.SetScheme` for more information. -func SetScheme(scheme string) *Client { - return DefaultClient.SetScheme(scheme) -} - -// SetCloseConnection method sets close connection value in the resty client. -// See `Client.SetCloseConnection` for more information. -func SetCloseConnection(close bool) *Client { - return DefaultClient.SetCloseConnection(close) -} - -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// See `Client.SetDoNotParseResponse` for more information. -func SetDoNotParseResponse(parse bool) *Client { - return DefaultClient.SetDoNotParseResponse(parse) -} - -// SetPathParams method sets the Request path parameter key-value pairs. See -// `Client.SetPathParams` for more information. -func SetPathParams(params map[string]string) *Client { - return DefaultClient.SetPathParams(params) -} - -// IsProxySet method returns the true if proxy is set on client otherwise false. -// See `Client.IsProxySet` for more information. -func IsProxySet() bool { - return DefaultClient.IsProxySet() -} - -// GetClient method returns the current `http.Client` used by the default resty client. -func GetClient() *http.Client { - return DefaultClient.httpClient -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Unexported methods -//___________________________________ - -func createClient(hc *http.Client) *Client { - c := &Client{ - HostURL: "", - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - UserInfo: nil, - Token: "", - Cookies: make([]*http.Cookie, 0), - Debug: false, - Log: getLogger(os.Stderr), - RetryCount: 0, - RetryWaitTime: defaultWaitTime, - RetryMaxWaitTime: defaultMaxWaitTime, - JSONMarshal: json.Marshal, - JSONUnmarshal: json.Unmarshal, - httpClient: hc, - debugBodySizeLimit: math.MaxInt32, - pathParams: make(map[string]string), - } - - // Log Prefix - c.SetLogPrefix("RESTY ") - - // Default redirect policy - c.SetRedirectPolicy(NoRedirectPolicy()) - - // default before request middlewares - c.beforeRequest = []func(*Client, *Request) error{ - parseRequestURL, - parseRequestHeader, - parseRequestBody, - createHTTPRequest, - addCredentials, - requestLogger, - } - - // user defined request middlewares - c.udBeforeRequest = []func(*Client, *Request) error{} - - // default after response middlewares - c.afterResponse = []func(*Client, *Response) error{ - responseLogger, - parseResponseBody, - saveResponseIntoFile, - } - - return c -} - -func init() { - DefaultClient = New() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/middleware.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/middleware.go deleted file mode 100644 index 73c7b4b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/middleware.go +++ /dev/null @@ -1,453 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "mime/multipart" - "net/http" - "net/url" - "os" - "path/filepath" - "reflect" - "strings" - "time" -) - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request Middleware(s) -//___________________________________ - -func parseRequestURL(c *Client, r *Request) error { - // GitHub #103 Path Params - if len(r.pathParams) > 0 { - for p, v := range r.pathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", v, -1) - } - } - if len(c.pathParams) > 0 { - for p, v := range c.pathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", v, -1) - } - } - - // Parsing request URL - reqURL, err := url.Parse(r.URL) - if err != nil { - return err - } - - // If Request.URL is relative path then added c.HostURL into - // the request URL otherwise Request.URL will be used as-is - if !reqURL.IsAbs() { - r.URL = reqURL.String() - if len(r.URL) > 0 && r.URL[0] != '/' { - r.URL = "/" + r.URL - } - - reqURL, err = url.Parse(c.HostURL + r.URL) - if err != nil { - return err - } - } - - // Adding Query Param - query := make(url.Values) - for k, v := range c.QueryParam { - for _, iv := range v { - query.Add(k, iv) - } - } - - for k, v := range r.QueryParam { - // remove query param from client level by key - // since overrides happens for that key in the request - query.Del(k) - - for _, iv := range v { - query.Add(k, iv) - } - } - - // GitHub #123 Preserve query string order partially. - // Since not feasible in `SetQuery*` resty methods, because - // standard package `url.Encode(...)` sorts the query params - // alphabetically - if len(query) > 0 { - if IsStringEmpty(reqURL.RawQuery) { - reqURL.RawQuery = query.Encode() - } else { - reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode() - } - } - - r.URL = reqURL.String() - - return nil -} - -func parseRequestHeader(c *Client, r *Request) error { - hdr := make(http.Header) - for k := range c.Header { - hdr[k] = append(hdr[k], c.Header[k]...) - } - - for k := range r.Header { - hdr.Del(k) - hdr[k] = append(hdr[k], r.Header[k]...) - } - - if IsStringEmpty(hdr.Get(hdrUserAgentKey)) { - hdr.Set(hdrUserAgentKey, fmt.Sprintf(hdrUserAgentValue, Version)) - } - - ct := hdr.Get(hdrContentTypeKey) - if IsStringEmpty(hdr.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && - (IsJSONType(ct) || IsXMLType(ct)) { - hdr.Set(hdrAcceptKey, hdr.Get(hdrContentTypeKey)) - } - - r.Header = hdr - - return nil -} - -func parseRequestBody(c *Client, r *Request) (err error) { - if isPayloadSupported(r.Method, c.AllowGetMethodPayload) { - // Handling Multipart - if r.isMultiPart && !(r.Method == MethodPatch) { - if err = handleMultipart(c, r); err != nil { - return - } - - goto CL - } - - // Handling Form Data - if len(c.FormData) > 0 || len(r.FormData) > 0 { - handleFormData(c, r) - - goto CL - } - - // Handling Request body - if r.Body != nil { - handleContentType(c, r) - - if err = handleRequestBody(c, r); err != nil { - return - } - } - } - -CL: - // by default resty won't set content length, you can if you want to :) - if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil { - r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len())) - } - - return -} - -func createHTTPRequest(c *Client, r *Request) (err error) { - if r.bodyBuf == nil { - if reader, ok := r.Body.(io.Reader); ok { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader) - } else { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil) - } - } else { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf) - } - - if err != nil { - return - } - - // Assign close connection option - r.RawRequest.Close = c.closeConnection - - // Add headers into http request - r.RawRequest.Header = r.Header - - // Add cookies into http request - for _, cookie := range c.Cookies { - r.RawRequest.AddCookie(cookie) - } - - // it's for non-http scheme option - if r.RawRequest.URL != nil && r.RawRequest.URL.Scheme == "" { - r.RawRequest.URL.Scheme = c.scheme - r.RawRequest.URL.Host = r.URL - } - - // Use context if it was specified - r.addContextIfAvailable() - - return -} - -func addCredentials(c *Client, r *Request) error { - var isBasicAuth bool - // Basic Auth - if r.UserInfo != nil { // takes precedence - r.RawRequest.SetBasicAuth(r.UserInfo.Username, r.UserInfo.Password) - isBasicAuth = true - } else if c.UserInfo != nil { - r.RawRequest.SetBasicAuth(c.UserInfo.Username, c.UserInfo.Password) - isBasicAuth = true - } - - if !c.DisableWarn { - if isBasicAuth && !strings.HasPrefix(r.URL, "https") { - c.Log.Println("WARNING - Using Basic Auth in HTTP mode is not secure.") - } - } - - // Token Auth - if !IsStringEmpty(r.Token) { // takes precedence - r.RawRequest.Header.Set(hdrAuthorizationKey, "Bearer "+r.Token) - } else if !IsStringEmpty(c.Token) { - r.RawRequest.Header.Set(hdrAuthorizationKey, "Bearer "+c.Token) - } - - return nil -} - -func requestLogger(c *Client, r *Request) error { - if c.Debug { - rr := r.RawRequest - reqLog := "\n---------------------- REQUEST LOG -----------------------\n" + - fmt.Sprintf("%s %s %s\n", r.Method, rr.URL.RequestURI(), rr.Proto) + - fmt.Sprintf("HOST : %s\n", rr.URL.Host) + - fmt.Sprintf("HEADERS:\n") + - composeHeaders(rr.Header) + "\n" + - fmt.Sprintf("BODY :\n%v\n", r.fmtBodyString()) + - "----------------------------------------------------------\n" - - c.Log.Print(reqLog) - } - - return nil -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Response Middleware(s) -//___________________________________ - -func responseLogger(c *Client, res *Response) error { - if c.Debug { - resLog := "\n---------------------- RESPONSE LOG -----------------------\n" + - fmt.Sprintf("STATUS : %s\n", res.Status()) + - fmt.Sprintf("RECEIVED AT : %v\n", res.ReceivedAt().Format(time.RFC3339Nano)) + - fmt.Sprintf("RESPONSE TIME : %v\n", res.Time()) + - "HEADERS:\n" + - composeHeaders(res.Header()) + "\n" - - if res.Request.isSaveResponse { - resLog += fmt.Sprintf("BODY :\n***** RESPONSE WRITTEN INTO FILE *****\n") - } else { - resLog += fmt.Sprintf("BODY :\n%v\n", res.fmtBodyString(c.debugBodySizeLimit)) - } - resLog += "----------------------------------------------------------\n" - - c.Log.Print(resLog) - } - - return nil -} - -func parseResponseBody(c *Client, res *Response) (err error) { - // Handles only JSON or XML content type - ct := firstNonEmpty(res.Header().Get(hdrContentTypeKey), res.Request.fallbackContentType) - if IsJSONType(ct) || IsXMLType(ct) { - // HTTP status code > 199 and < 300, considered as Result - if res.IsSuccess() { - if res.Request.Result != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Result) - return - } - } - - // HTTP status code > 399, considered as Error - if res.IsError() { - // global error interface - if res.Request.Error == nil && c.Error != nil { - res.Request.Error = reflect.New(c.Error).Interface() - } - - if res.Request.Error != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Error) - } - } - } - - return -} - -func handleMultipart(c *Client, r *Request) (err error) { - r.bodyBuf = acquireBuffer() - w := multipart.NewWriter(r.bodyBuf) - - for k, v := range c.FormData { - for _, iv := range v { - if err = w.WriteField(k, iv); err != nil { - return err - } - } - } - - for k, v := range r.FormData { - for _, iv := range v { - if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return - } - } else { // form value - if err = w.WriteField(k, iv); err != nil { - return err - } - } - } - } - - // #21 - adding io.Reader support - if len(r.multipartFiles) > 0 { - for _, f := range r.multipartFiles { - err = addFileReader(w, f) - if err != nil { - return - } - } - } - - // GitHub #130 adding multipart field support with content type - if len(r.multipartFields) > 0 { - for _, mf := range r.multipartFields { - if err = addMultipartFormField(w, mf); err != nil { - return - } - } - } - - r.Header.Set(hdrContentTypeKey, w.FormDataContentType()) - err = w.Close() - - return -} - -func handleFormData(c *Client, r *Request) { - formData := url.Values{} - - for k, v := range c.FormData { - for _, iv := range v { - formData.Add(k, iv) - } - } - - for k, v := range r.FormData { - // remove form data field from client level by key - // since overrides happens for that key in the request - formData.Del(k) - - for _, iv := range v { - formData.Add(k, iv) - } - } - - r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode())) - r.Header.Set(hdrContentTypeKey, formContentType) - r.isFormData = true -} - -func handleContentType(c *Client, r *Request) { - contentType := r.Header.Get(hdrContentTypeKey) - if IsStringEmpty(contentType) { - contentType = DetectContentType(r.Body) - r.Header.Set(hdrContentTypeKey, contentType) - } -} - -func handleRequestBody(c *Client, r *Request) (err error) { - var bodyBytes []byte - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) - r.bodyBuf = nil - - if reader, ok := r.Body.(io.Reader); ok { - if c.setContentLength || r.setContentLength { // keep backward compability - r.bodyBuf = acquireBuffer() - _, err = r.bodyBuf.ReadFrom(reader) - r.Body = nil - } else { - // Otherwise buffer less processing for `io.Reader`, sounds good. - return - } - } else if b, ok := r.Body.([]byte); ok { - bodyBytes = b - } else if s, ok := r.Body.(string); ok { - bodyBytes = []byte(s) - } else if IsJSONType(contentType) && - (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { - bodyBytes, err = c.JSONMarshal(r.Body) - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - bodyBytes, err = xml.Marshal(r.Body) - } - - if bodyBytes == nil && r.bodyBuf == nil { - err = errors.New("unsupported 'Body' type/value") - } - - // if any errors during body bytes handling, return it - if err != nil { - return - } - - // []byte into Buffer - if bodyBytes != nil && r.bodyBuf == nil { - r.bodyBuf = acquireBuffer() - _, _ = r.bodyBuf.Write(bodyBytes) - } - - return -} - -func saveResponseIntoFile(c *Client, res *Response) error { - if res.Request.isSaveResponse { - file := "" - - if len(c.outputDirectory) > 0 && !filepath.IsAbs(res.Request.outputFile) { - file += c.outputDirectory + string(filepath.Separator) - } - - file = filepath.Clean(file + res.Request.outputFile) - if err := createDirectory(filepath.Dir(file)); err != nil { - return err - } - - outFile, err := os.Create(file) - if err != nil { - return err - } - defer closeq(outFile) - - // io.Copy reads maximum 32kb size, it is perfect for large file download too - defer closeq(res.RawResponse.Body) - - written, err := io.Copy(outFile, res.RawResponse.Body) - if err != nil { - return err - } - - res.size = written - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/redirect.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/redirect.go deleted file mode 100644 index ac362cc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/redirect.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "errors" - "fmt" - "net" - "net/http" - "strings" -) - -type ( - // RedirectPolicy to regulate the redirects in the resty client. - // Objects implementing the RedirectPolicy interface can be registered as - // - // Apply function should return nil to continue the redirect jounery, otherwise - // return error to stop the redirect. - RedirectPolicy interface { - Apply(req *http.Request, via []*http.Request) error - } - - // The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. - // If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f. - RedirectPolicyFunc func(*http.Request, []*http.Request) error -) - -// Apply calls f(req, via). -func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error { - return f(req, via) -} - -// NoRedirectPolicy is used to disable redirects in the HTTP client -// resty.SetRedirectPolicy(NoRedirectPolicy()) -func NoRedirectPolicy() RedirectPolicy { - return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - return errors.New("auto redirect is disabled") - }) -} - -// FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client. -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) -func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy { - return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - if len(via) >= noOfRedirect { - return fmt.Errorf("stopped after %d redirects", noOfRedirect) - } - - checkHostAndAddHeaders(req, via[0]) - - return nil - }) -} - -// DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. -// Redirect is allowed for only mentioned host in the policy. -// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) -func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy { - hosts := make(map[string]bool) - for _, h := range hostnames { - hosts[strings.ToLower(h)] = true - } - - fn := RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - if ok := hosts[getHostname(req.URL.Host)]; !ok { - return errors.New("redirect is not allowed as per DomainCheckRedirectPolicy") - } - - return nil - }) - - return fn -} - -func getHostname(host string) (hostname string) { - if strings.Index(host, ":") > 0 { - host, _, _ = net.SplitHostPort(host) - } - hostname = strings.ToLower(host) - return -} - -// By default Golang will not redirect request headers -// after go throughing various discussion comments from thread -// https://github.com/golang/go/issues/4800 -// go-resty will add all the headers during a redirect for the same host -func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) { - curHostname := getHostname(cur.URL.Host) - preHostname := getHostname(pre.URL.Host) - if strings.EqualFold(curHostname, preHostname) { - for key, val := range pre.Header { - cur.Header[key] = val - } - } else { // only library User-Agent header is added - cur.Header.Set(hdrUserAgentKey, fmt.Sprintf(hdrUserAgentValue, Version)) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request.go deleted file mode 100644 index a5685e5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request.go +++ /dev/null @@ -1,558 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "encoding/base64" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "net" - "net/url" - "reflect" - "strings" -) - -// SRVRecord holds the data to query the SRV record for the following service -type SRVRecord struct { - Service string - Domain string -} - -// SetHeader method is to set a single header field and its value in the current request. -// Example: To set `Content-Type` and `Accept` as `application/json`. -// resty.R(). -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") -// -// Also you can override header value, which was set at client instance level. -// -func (r *Request) SetHeader(header, value string) *Request { - r.Header.Set(header, value) - return r -} - -// SetHeaders method sets multiple headers field and its values at one go in the current request. -// Example: To set `Content-Type` and `Accept` as `application/json` -// -// resty.R(). -// SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) -// Also you can override header value, which was set at client instance level. -// -func (r *Request) SetHeaders(headers map[string]string) *Request { - for h, v := range headers { - r.SetHeader(h, v) - } - - return r -} - -// SetQueryParam method sets single parameter and its value in the current request. -// It will be formed as query string for the request. -// Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// resty.R(). -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") -// Also you can override query params value, which was set at client instance level -// -func (r *Request) SetQueryParam(param, value string) *Request { - r.QueryParam.Set(param, value) - return r -} - -// SetQueryParams method sets multiple parameters and its values at one go in the current request. -// It will be formed as query string for the request. -// Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// resty.R(). -// SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) -// Also you can override query params value, which was set at client instance level -// -func (r *Request) SetQueryParams(params map[string]string) *Request { - for p, v := range params { - r.SetQueryParam(p, v) - } - - return r -} - -// SetMultiValueQueryParams method appends multiple parameters with multi-value -// at one go in the current request. It will be formed as query string for the request. -// Example: `status=pending&status=approved&status=open` in the URL after `?` mark. -// resty.R(). -// SetMultiValueQueryParams(url.Values{ -// "status": []string{"pending", "approved", "open"}, -// }) -// Also you can override query params value, which was set at client instance level -// -func (r *Request) SetMultiValueQueryParams(params url.Values) *Request { - for p, v := range params { - for _, pv := range v { - r.QueryParam.Add(p, pv) - } - } - - return r -} - -// SetQueryString method provides ability to use string as an input to set URL query string for the request. -// -// Using String as an input -// resty.R(). -// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") -// -func (r *Request) SetQueryString(query string) *Request { - params, err := url.ParseQuery(strings.TrimSpace(query)) - if err == nil { - for p, v := range params { - for _, pv := range v { - r.QueryParam.Add(p, pv) - } - } - } else { - r.client.Log.Printf("ERROR %v", err) - } - return r -} - -// SetFormData method sets Form parameters and their values in the current request. -// It's applicable only HTTP method `POST` and `PUT` and requests content type would be set as -// `application/x-www-form-urlencoded`. -// resty.R(). -// SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) -// Also you can override form data value, which was set at client instance level -// -func (r *Request) SetFormData(data map[string]string) *Request { - for k, v := range data { - r.FormData.Set(k, v) - } - - return r -} - -// SetMultiValueFormData method appends multiple form parameters with multi-value -// at one go in the current request. -// resty.R(). -// SetMultiValueFormData(url.Values{ -// "search_criteria": []string{"book", "glass", "pencil"}, -// }) -// Also you can override form data value, which was set at client instance level -// -func (r *Request) SetMultiValueFormData(params url.Values) *Request { - for k, v := range params { - for _, kv := range v { - r.FormData.Add(k, kv) - } - } - - return r -} - -// SetBody method sets the request body for the request. It supports various realtime need easy. -// We can say its quite handy or powerful. Supported request body data types is `string`, `[]byte`, -// `struct` and `map`. Body value can be pointer or non-pointer. Automatic marshalling -// for JSON and XML content type, if it is `struct` or `map`. -// -// Example: -// -// Struct as a body input, based on content type, it will be marshalled. -// resty.R(). -// SetBody(User{ -// Username: "jeeva@myjeeva.com", -// Password: "welcome2resty", -// }) -// -// Map as a body input, based on content type, it will be marshalled. -// resty.R(). -// SetBody(map[string]interface{}{ -// "username": "jeeva@myjeeva.com", -// "password": "welcome2resty", -// "address": &Address{ -// Address1: "1111 This is my street", -// Address2: "Apt 201", -// City: "My City", -// State: "My State", -// ZipCode: 00000, -// }, -// }) -// -// String as a body input. Suitable for any need as a string input. -// resty.R(). -// SetBody(`{ -// "username": "jeeva@getrightcare.com", -// "password": "admin" -// }`) -// -// []byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc. -// resty.R(). -// SetBody([]byte("This is my raw request, sent as-is")) -// -func (r *Request) SetBody(body interface{}) *Request { - r.Body = body - return r -} - -// SetResult method is to register the response `Result` object for automatic unmarshalling in the RESTful mode -// if response status code is between 200 and 299 and content type either JSON or XML. -// -// Note: Result object can be pointer or non-pointer. -// resty.R().SetResult(&AuthToken{}) -// // OR -// resty.R().SetResult(AuthToken{}) -// -// Accessing a result value -// response.Result().(*AuthToken) -// -func (r *Request) SetResult(res interface{}) *Request { - r.Result = getPointer(res) - return r -} - -// SetError method is to register the request `Error` object for automatic unmarshalling in the RESTful mode -// if response status code is greater than 399 and content type either JSON or XML. -// -// Note: Error object can be pointer or non-pointer. -// resty.R().SetError(&AuthError{}) -// // OR -// resty.R().SetError(AuthError{}) -// -// Accessing a error value -// response.Error().(*AuthError) -// -func (r *Request) SetError(err interface{}) *Request { - r.Error = getPointer(err) - return r -} - -// SetFile method is to set single file field name and its path for multipart upload. -// resty.R(). -// SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf") -// -func (r *Request) SetFile(param, filePath string) *Request { - r.isMultiPart = true - r.FormData.Set("@"+param, filePath) - - return r -} - -// SetFiles method is to set multiple file field name and its path for multipart upload. -// resty.R(). -// SetFiles(map[string]string{ -// "my_file1": "/Users/jeeva/Gas Bill - Sep.pdf", -// "my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf", -// "my_file3": "/Users/jeeva/Water Bill - Sep.pdf", -// }) -// -func (r *Request) SetFiles(files map[string]string) *Request { - r.isMultiPart = true - - for f, fp := range files { - r.FormData.Set("@"+f, fp) - } - - return r -} - -// SetFileReader method is to set single file using io.Reader for multipart upload. -// resty.R(). -// SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)). -// SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes)) -// -func (r *Request) SetFileReader(param, fileName string, reader io.Reader) *Request { - r.isMultiPart = true - - r.multipartFiles = append(r.multipartFiles, &File{ - Name: fileName, - ParamName: param, - Reader: reader, - }) - - return r -} - -// SetMultipartField method is to set custom data using io.Reader for multipart upload. -func (r *Request) SetMultipartField(param, fileName, contentType string, reader io.Reader) *Request { - r.isMultiPart = true - - r.multipartFields = append(r.multipartFields, &multipartField{ - Param: param, - FileName: fileName, - ContentType: contentType, - Reader: reader, - }) - - return r -} - -// SetContentLength method sets the HTTP header `Content-Length` value for current request. -// By default go-resty won't set `Content-Length`. Also you have an option to enable for every -// request. See `resty.SetContentLength` -// resty.R().SetContentLength(true) -// -func (r *Request) SetContentLength(l bool) *Request { - r.setContentLength = true - - return r -} - -// SetBasicAuth method sets the basic authentication header in the current HTTP request. -// For Header example: -// Authorization: Basic -// -// To set the header for username "go-resty" and password "welcome" -// resty.R().SetBasicAuth("go-resty", "welcome") -// -// This method overrides the credentials set by method `resty.SetBasicAuth`. -// -func (r *Request) SetBasicAuth(username, password string) *Request { - r.UserInfo = &User{Username: username, Password: password} - return r -} - -// SetAuthToken method sets bearer auth token header in the current HTTP request. Header example: -// Authorization: Bearer -// -// Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F -// -// resty.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") -// -// This method overrides the Auth token set by method `resty.SetAuthToken`. -// -func (r *Request) SetAuthToken(token string) *Request { - r.Token = token - return r -} - -// SetOutput method sets the output file for current HTTP request. Current HTTP response will be -// saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. -// If is it relative path then output file goes under the output directory, as mentioned -// in the `Client.SetOutputDirectory`. -// resty.R(). -// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). -// Get("http://bit.ly/1LouEKr") -// -// Note: In this scenario `Response.Body` might be nil. -func (r *Request) SetOutput(file string) *Request { - r.outputFile = file - r.isSaveResponse = true - return r -} - -// SetSRV method sets the details to query the service SRV record and execute the -// request. -// resty.R(). -// SetSRV(SRVRecord{"web", "testservice.com"}). -// Get("/get") -func (r *Request) SetSRV(srv *SRVRecord) *Request { - r.SRV = srv - return r -} - -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, -// otherwise you might get into connection leaks, no connection reuse. -// -// Please Note: Response middlewares are not applicable, if you use this option. Basically you have -// taken over the control of response parsing from `Resty`. -func (r *Request) SetDoNotParseResponse(parse bool) *Request { - r.notParseResponse = parse - return r -} - -// SetPathParams method sets multiple URL path key-value pairs at one go in the -// resty current request instance. -// resty.R().SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details -// It replace the value of the key while composing request URL. Also you can -// override Path Params value, which was set at client instance level. -func (r *Request) SetPathParams(params map[string]string) *Request { - for p, v := range params { - r.pathParams[p] = v - } - return r -} - -// ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling -// when `Content-Type` response header is unavailable. -func (r *Request) ExpectContentType(contentType string) *Request { - r.fallbackContentType = contentType - return r -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// HTTP verb method starts here -//___________________________________ - -// Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231. -func (r *Request) Get(url string) (*Response, error) { - return r.Execute(MethodGet, url) -} - -// Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231. -func (r *Request) Head(url string) (*Response, error) { - return r.Execute(MethodHead, url) -} - -// Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231. -func (r *Request) Post(url string) (*Response, error) { - return r.Execute(MethodPost, url) -} - -// Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231. -func (r *Request) Put(url string) (*Response, error) { - return r.Execute(MethodPut, url) -} - -// Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231. -func (r *Request) Delete(url string) (*Response, error) { - return r.Execute(MethodDelete, url) -} - -// Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231. -func (r *Request) Options(url string) (*Response, error) { - return r.Execute(MethodOptions, url) -} - -// Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789. -func (r *Request) Patch(url string) (*Response, error) { - return r.Execute(MethodPatch, url) -} - -// Execute method performs the HTTP request with given HTTP method and URL -// for current `Request`. -// resp, err := resty.R().Execute(resty.GET, "http://httpbin.org/get") -// -func (r *Request) Execute(method, url string) (*Response, error) { - var addrs []*net.SRV - var err error - - if r.isMultiPart && !(method == MethodPost || method == MethodPut) { - return nil, fmt.Errorf("multipart content is not allowed in HTTP verb [%v]", method) - } - - if r.SRV != nil { - _, addrs, err = net.LookupSRV(r.SRV.Service, "tcp", r.SRV.Domain) - if err != nil { - return nil, err - } - } - - r.Method = method - r.URL = r.selectAddr(addrs, url, 0) - - if r.client.RetryCount == 0 { - return r.client.execute(r) - } - - var resp *Response - attempt := 0 - _ = Backoff( - func() (*Response, error) { - attempt++ - - r.URL = r.selectAddr(addrs, url, attempt) - - resp, err = r.client.execute(r) - if err != nil { - r.client.Log.Printf("ERROR %v, Attempt %v", err, attempt) - if r.isContextCancelledIfAvailable() { - // stop Backoff from retrying request if request has been - // canceled by context - return resp, nil - } - } - - return resp, err - }, - Retries(r.client.RetryCount), - WaitTime(r.client.RetryWaitTime), - MaxWaitTime(r.client.RetryMaxWaitTime), - RetryConditions(r.client.RetryConditions), - ) - - return resp, err -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request Unexported methods -//___________________________________ - -func (r *Request) fmtBodyString() (body string) { - body = "***** NO CONTENT *****" - if isPayloadSupported(r.Method, r.client.AllowGetMethodPayload) { - if _, ok := r.Body.(io.Reader); ok { - body = "***** BODY IS io.Reader *****" - return - } - - // multipart or form-data - if r.isMultiPart || r.isFormData { - body = r.bodyBuf.String() - return - } - - // request body data - if r.Body == nil { - return - } - var prtBodyBytes []byte - var err error - - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) - if canJSONMarshal(contentType, kind) { - prtBodyBytes, err = json.MarshalIndent(&r.Body, "", " ") - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ") - } else if b, ok := r.Body.(string); ok { - if IsJSONType(contentType) { - bodyBytes := []byte(b) - out := acquireBuffer() - defer releaseBuffer(out) - if err = json.Indent(out, bodyBytes, "", " "); err == nil { - prtBodyBytes = out.Bytes() - } - } else { - body = b - return - } - } else if b, ok := r.Body.([]byte); ok { - body = base64.StdEncoding.EncodeToString(b) - } - - if prtBodyBytes != nil && err == nil { - body = string(prtBodyBytes) - } - } - - return -} - -func (r *Request) selectAddr(addrs []*net.SRV, path string, attempt int) string { - if addrs == nil { - return path - } - - idx := attempt % len(addrs) - domain := strings.TrimRight(addrs[idx].Target, ".") - path = strings.TrimLeft(path, "/") - - return fmt.Sprintf("%s://%s:%d/%s", r.client.scheme, domain, addrs[idx].Port, path) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request16.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request16.go deleted file mode 100644 index a61a7c0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request16.go +++ /dev/null @@ -1,58 +0,0 @@ -// +build !go1.7 - -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com) -// 2016 Andrew Grigorev (https://github.com/ei-grad) -// All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "net/http" - "net/url" - "time" -) - -// Request type is used to compose and send individual request from client -// go-resty is provide option override client level settings such as -// Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object -// and also you can add more options for that particular request -type Request struct { - URL string - Method string - Token string - QueryParam url.Values - FormData url.Values - Header http.Header - Time time.Time - Body interface{} - Result interface{} - Error interface{} - RawRequest *http.Request - SRV *SRVRecord - UserInfo *User - - isMultiPart bool - isFormData bool - setContentLength bool - isSaveResponse bool - notParseResponse bool - outputFile string - fallbackContentType string - pathParams map[string]string - client *Client - bodyBuf *bytes.Buffer - multipartFiles []*File - multipartFields []*multipartField -} - -func (r *Request) addContextIfAvailable() { - // nothing to do for golang<1.7 -} - -func (r *Request) isContextCancelledIfAvailable() bool { - // just always return false golang<1.7 - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request17.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request17.go deleted file mode 100644 index 5e0f3b3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/request17.go +++ /dev/null @@ -1,75 +0,0 @@ -// +build go1.7 go1.8 - -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com) -// 2016 Andrew Grigorev (https://github.com/ei-grad) -// All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "context" - "net/http" - "net/url" - "time" -) - -// Request type is used to compose and send individual request from client -// go-resty is provide option override client level settings such as -// Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object -// and also you can add more options for that particular request -type Request struct { - URL string - Method string - Token string - QueryParam url.Values - FormData url.Values - Header http.Header - Time time.Time - Body interface{} - Result interface{} - Error interface{} - RawRequest *http.Request - SRV *SRVRecord - UserInfo *User - - isMultiPart bool - isFormData bool - setContentLength bool - isSaveResponse bool - notParseResponse bool - outputFile string - fallbackContentType string - ctx context.Context - pathParams map[string]string - client *Client - bodyBuf *bytes.Buffer - multipartFiles []*File - multipartFields []*multipartField -} - -// SetContext method sets the context.Context for current Request. It allows -// to interrupt the request execution if ctx.Done() channel is closed. -// See https://blog.golang.org/context article and the "context" package -// documentation. -func (r *Request) SetContext(ctx context.Context) *Request { - r.ctx = ctx - return r -} - -func (r *Request) addContextIfAvailable() { - if r.ctx != nil { - r.RawRequest = r.RawRequest.WithContext(r.ctx) - } -} - -func (r *Request) isContextCancelledIfAvailable() bool { - if r.ctx != nil { - if r.ctx.Err() != nil { - return true - } - } - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/response.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/response.go deleted file mode 100644 index f54e905..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/response.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "time" -) - -// Response is an object represents executed request and its values. -type Response struct { - Request *Request - RawResponse *http.Response - - body []byte - size int64 - receivedAt time.Time -} - -// Body method returns HTTP response as []byte array for the executed request. -// Note: `Response.Body` might be nil, if `Request.SetOutput` is used. -func (r *Response) Body() []byte { - if r.RawResponse == nil { - return []byte{} - } - return r.body -} - -// Status method returns the HTTP status string for the executed request. -// Example: 200 OK -func (r *Response) Status() string { - if r.RawResponse == nil { - return "" - } - - return r.RawResponse.Status -} - -// StatusCode method returns the HTTP status code for the executed request. -// Example: 200 -func (r *Response) StatusCode() int { - if r.RawResponse == nil { - return 0 - } - - return r.RawResponse.StatusCode -} - -// Result method returns the response value as an object if it has one -func (r *Response) Result() interface{} { - return r.Request.Result -} - -// Error method returns the error object if it has one -func (r *Response) Error() interface{} { - return r.Request.Error -} - -// Header method returns the response headers -func (r *Response) Header() http.Header { - if r.RawResponse == nil { - return http.Header{} - } - - return r.RawResponse.Header -} - -// Cookies method to access all the response cookies -func (r *Response) Cookies() []*http.Cookie { - if r.RawResponse == nil { - return make([]*http.Cookie, 0) - } - - return r.RawResponse.Cookies() -} - -// String method returns the body of the server response as String. -func (r *Response) String() string { - if r.body == nil { - return "" - } - - return strings.TrimSpace(string(r.body)) -} - -// Time method returns the time of HTTP response time that from request we sent and received a request. -// See `response.ReceivedAt` to know when client recevied response and see `response.Request.Time` to know -// when client sent a request. -func (r *Response) Time() time.Duration { - return r.receivedAt.Sub(r.Request.Time) -} - -// ReceivedAt method returns when response got recevied from server for the request. -func (r *Response) ReceivedAt() time.Time { - return r.receivedAt -} - -// Size method returns the HTTP response size in bytes. Ya, you can relay on HTTP `Content-Length` header, -// however it won't be good for chucked transfer/compressed response. Since Resty calculates response size -// at the client end. You will get actual size of the http response. -func (r *Response) Size() int64 { - return r.size -} - -// RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse` -// option otherwise you get an error as `read err: http: read on closed response body`. -// -// Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse. -// Basically you have taken over the control of response parsing from `Resty`. -func (r *Response) RawBody() io.ReadCloser { - if r.RawResponse == nil { - return nil - } - return r.RawResponse.Body -} - -// IsSuccess method returns true if HTTP status code >= 200 and <= 299 otherwise false. -func (r *Response) IsSuccess() bool { - return r.StatusCode() > 199 && r.StatusCode() < 300 -} - -// IsError method returns true if HTTP status code >= 400 otherwise false. -func (r *Response) IsError() bool { - return r.StatusCode() > 399 -} - -func (r *Response) fmtBodyString(sl int64) string { - if r.body != nil { - if int64(len(r.body)) > sl { - return fmt.Sprintf("***** RESPONSE TOO LARGE (size - %d) *****", len(r.body)) - } - ct := r.Header().Get(hdrContentTypeKey) - if IsJSONType(ct) { - out := acquireBuffer() - defer releaseBuffer(out) - if err := json.Indent(out, r.body, "", " "); err == nil { - return out.String() - } - } - return r.String() - } - - return "***** NO CONTENT *****" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/resty.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/resty.go deleted file mode 100644 index d0a7ad3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/resty.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -// Package resty provides simple HTTP and REST client for Go inspired by Ruby rest-client. -package resty - -// Version # of resty -const Version = "1.8.0" diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/retry.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/retry.go deleted file mode 100644 index 7b88cb7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/retry.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "math" - "math/rand" - "time" -) - -const ( - defaultMaxRetries = 3 - defaultWaitTime = time.Duration(100) * time.Millisecond - defaultMaxWaitTime = time.Duration(2000) * time.Millisecond -) - -type ( - // Option is to create convenient retry options like wait time, max retries, etc. - Option func(*Options) - - // RetryConditionFunc type is for retry condition function - RetryConditionFunc func(*Response) (bool, error) - - // Options to hold go-resty retry values - Options struct { - maxRetries int - waitTime time.Duration - maxWaitTime time.Duration - retryConditions []RetryConditionFunc - } -) - -// Retries sets the max number of retries -func Retries(value int) Option { - return func(o *Options) { - o.maxRetries = value - } -} - -// WaitTime sets the default wait time to sleep between requests -func WaitTime(value time.Duration) Option { - return func(o *Options) { - o.waitTime = value - } -} - -// MaxWaitTime sets the max wait time to sleep between requests -func MaxWaitTime(value time.Duration) Option { - return func(o *Options) { - o.maxWaitTime = value - } -} - -// RetryConditions sets the conditions that will be checked for retry. -func RetryConditions(conditions []RetryConditionFunc) Option { - return func(o *Options) { - o.retryConditions = conditions - } -} - -// Backoff retries with increasing timeout duration up until X amount of retries -// (Default is 3 attempts, Override with option Retries(n)) -func Backoff(operation func() (*Response, error), options ...Option) error { - // Defaults - opts := Options{ - maxRetries: defaultMaxRetries, - waitTime: defaultWaitTime, - maxWaitTime: defaultMaxWaitTime, - retryConditions: []RetryConditionFunc{}, - } - - for _, o := range options { - o(&opts) - } - - var ( - resp *Response - err error - ) - base := float64(opts.waitTime) // Time to wait between each attempt - capLevel := float64(opts.maxWaitTime) // Maximum amount of wait time for the retry - for attempt := 0; attempt < opts.maxRetries; attempt++ { - resp, err = operation() - - var needsRetry bool - var conditionErr error - for _, condition := range opts.retryConditions { - needsRetry, conditionErr = condition(resp) - if needsRetry || conditionErr != nil { - break - } - } - - // If the operation returned no error, there was no condition satisfied and - // there was no error caused by the conditional functions. - if err == nil && !needsRetry && conditionErr == nil { - return nil - } - // Adding capped exponential backup with jitter - // See the following article... - // http://www.awsarchitectureblog.com/2015/03/backoff.html - temp := math.Min(capLevel, base*math.Exp2(float64(attempt))) - sleepDuration := time.Duration(int(temp/2) + rand.Intn(int(temp/2))) - - if sleepDuration < opts.waitTime { - sleepDuration = opts.waitTime - } - time.Sleep(sleepDuration) - } - - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/util.go b/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/util.go deleted file mode 100644 index db16edc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/go-resty/resty/util.go +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (c) 2015-2018 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "log" - "mime/multipart" - "net/http" - "net/textproto" - "os" - "path/filepath" - "reflect" - "runtime" - "sort" - "strings" -) - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Helper methods -//___________________________________ - -// IsStringEmpty method tells whether given string is empty or not -func IsStringEmpty(str string) bool { - return len(strings.TrimSpace(str)) == 0 -} - -// DetectContentType method is used to figure out `Request.Body` content type for request header -func DetectContentType(body interface{}) string { - contentType := plainTextType - kind := kindOf(body) - switch kind { - case reflect.Struct, reflect.Map: - contentType = jsonContentType - case reflect.String: - contentType = plainTextType - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = jsonContentType - } - } - - return contentType -} - -// IsJSONType method is to check JSON content type or not -func IsJSONType(ct string) bool { - return jsonCheck.MatchString(ct) -} - -// IsXMLType method is to check XML content type or not -func IsXMLType(ct string) bool { - return xmlCheck.MatchString(ct) -} - -// Unmarshal content into object from JSON or XML -// Deprecated: kept for backward compatibility -func Unmarshal(ct string, b []byte, d interface{}) (err error) { - if IsJSONType(ct) { - err = json.Unmarshal(b, d) - } else if IsXMLType(ct) { - err = xml.Unmarshal(b, d) - } - - return -} - -// Unmarshalc content into object from JSON or XML -func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error) { - if IsJSONType(ct) { - err = c.JSONUnmarshal(b, d) - } else if IsXMLType(ct) { - err = xml.Unmarshal(b, d) - } - - return -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Unexported methods -//___________________________________ - -func firstNonEmpty(v ...string) string { - for _, s := range v { - if !IsStringEmpty(s) { - return s - } - } - return "" -} - -func getLogger(w io.Writer) *log.Logger { - return log.New(w, "RESTY ", log.LstdFlags) -} - -var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") - -func escapeQuotes(s string) string { - return quoteEscaper.Replace(s) -} - -func createMultipartHeader(param, fileName, contentType string) textproto.MIMEHeader { - hdr := make(textproto.MIMEHeader) - hdr.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, - escapeQuotes(param), escapeQuotes(fileName))) - hdr.Set("Content-Type", contentType) - return hdr -} - -func addMultipartFormField(w *multipart.Writer, mf *multipartField) error { - partWriter, err := w.CreatePart(createMultipartHeader(mf.Param, mf.FileName, mf.ContentType)) - if err != nil { - return err - } - - _, err = io.Copy(partWriter, mf.Reader) - return err -} - -func writeMultipartFormFile(w *multipart.Writer, fieldName, fileName string, r io.Reader) error { - // Auto detect actual multipart content type - cbuf := make([]byte, 512) - size, err := r.Read(cbuf) - if err != nil { - return err - } - - partWriter, err := w.CreatePart(createMultipartHeader(fieldName, fileName, http.DetectContentType(cbuf))) - if err != nil { - return err - } - - if _, err = partWriter.Write(cbuf[:size]); err != nil { - return err - } - - _, err = io.Copy(partWriter, r) - return err -} - -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer closeq(file) - return writeMultipartFormFile(w, fieldName, filepath.Base(path), file) -} - -func addFileReader(w *multipart.Writer, f *File) error { - return writeMultipartFormFile(w, f.ParamName, f.Name, f.Reader) -} - -func getPointer(v interface{}) interface{} { - vv := valueOf(v) - if vv.Kind() == reflect.Ptr { - return v - } - return reflect.New(vv.Type()).Interface() -} - -func isPayloadSupported(m string, allowMethodGet bool) bool { - return !(m == MethodHead || m == MethodOptions || (m == MethodGet && !allowMethodGet)) -} - -func typeOf(i interface{}) reflect.Type { - return indirect(valueOf(i)).Type() -} - -func valueOf(i interface{}) reflect.Value { - return reflect.ValueOf(i) -} - -func indirect(v reflect.Value) reflect.Value { - return reflect.Indirect(v) -} - -func kindOf(v interface{}) reflect.Kind { - return typeOf(v).Kind() -} - -func createDirectory(dir string) (err error) { - if _, err = os.Stat(dir); err != nil { - if os.IsNotExist(err) { - if err = os.MkdirAll(dir, 0755); err != nil { - return - } - } - } - return -} - -func canJSONMarshal(contentType string, kind reflect.Kind) bool { - return IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map) -} - -func functionName(i interface{}) string { - return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() -} - -func acquireBuffer() *bytes.Buffer { - return bufPool.Get().(*bytes.Buffer) -} - -func releaseBuffer(buf *bytes.Buffer) { - if buf != nil { - buf.Reset() - bufPool.Put(buf) - } -} - -func closeq(v interface{}) { - if c, ok := v.(io.Closer); ok { - sliently(c.Close()) - } -} - -func sliently(_ ...interface{}) {} - -func composeHeaders(hdrs http.Header) string { - var str []string - for _, k := range sortHeaderKeys(hdrs) { - str = append(str, fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", "))) - } - return strings.Join(str, "\n") -} - -func sortHeaderKeys(hdrs http.Header) []string { - var keys []string - for key := range hdrs { - keys = append(keys, key) - } - sort.Strings(keys) - return keys -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/AUTHORS deleted file mode 100644 index 15167cd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# 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. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/CONTRIBUTORS deleted file mode 100644 index 1c4577e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# 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. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 0f64693..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index 3cd3249..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,253 +0,0 @@ -// 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 ( - "fmt" - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(src Message) Message { - in := reflect.ValueOf(src) - if in.IsNil() { - return src - } - out := reflect.New(in.Type().Elem()) - dst := out.Interface().(Message) - Merge(dst, src) - return dst -} - -// Merger is the interface representing objects that can merge messages of the same type. -type Merger interface { - // Merge merges src into this message. - // 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 may panic if called with a different argument type than the receiver. - Merge(src Message) -} - -// generatedMerger is the custom merge method that generated protos will have. -// We must add this method since a generate Merge method will conflict with -// many existing protos that have a Merge data field already defined. -type generatedMerger interface { - XXX_Merge(src 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) { - if m, ok := dst.(Merger); ok { - m.Merge(src) - return - } - - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) - } - if in.IsNil() { - return // Merge from nil src is a noop - } - if m, ok := dst.(generatedMerger); ok { - m.XXX_Merge(src) - 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, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index d9aa3c4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,428 +0,0 @@ -// 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" -) - -// 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") - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - // x -= 0x80 << 63 // Always zero. - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// 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 -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -// Unmarshal implementations should not clear the receiver. -// Any unmarshaled data should be merged into the receiver. -// Callers of Unmarshal that do not want to retain existing data -// should Reset the receiver before calling Unmarshal. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// newUnmarshaler is the interface representing objects that can -// unmarshal themselves. The semantics are identical to Unmarshaler. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newUnmarshaler interface { - XXX_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() - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(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 u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - 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. -// StartGroup tag is already consumed. This function consumes -// EndGroup tag. -func (p *Buffer) DecodeGroup(pb Message) error { - b := p.buf[p.index:] - x, y := findEndGroup(b) - if x < 0 { - return io.ErrUnexpectedEOF - } - err := Unmarshal(b[:x], pb) - p.index += y - return err -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(newUnmarshaler); ok { - err := u.XXX_Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - // Slow workaround for messages that aren't Unmarshalers. - // This includes some hand-coded .pb.go files and - // bootstrap protos. - // TODO: fix all of those and then add Unmarshal to - // the Message interface. Then: - // The cast above and code below can be deleted. - // The old unmarshaler can be deleted. - // Clients can call Unmarshal directly (can already do that, actually). - var info InternalMessageInfo - err := info.Unmarshal(pb, p.buf[p.index:]) - p.index = len(p.buf) - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index dea2617..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,350 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 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 ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type generatedDiscarder interface { - XXX_DiscardUnknown() -} - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -// -// For proto2 messages, the unknown fields of message extensions are only -// discarded from messages that have been accessed via GetExtension. -func DiscardUnknown(m Message) { - if m, ok := m.(generatedDiscarder); ok { - m.XXX_DiscardUnknown() - return - } - // TODO: Dynamically populate a InternalMessageInfo for legacy messages, - // but the master branch has no implementation for InternalMessageInfo, - // so it would be more work to replicate that approach. - discardLegacy(m) -} - -// DiscardUnknown recursively discards all unknown fields. -func (a *InternalMessageInfo) DiscardUnknown(m Message) { - di := atomicLoadDiscardInfo(&a.discard) - if di == nil { - di = getDiscardInfo(reflect.TypeOf(m).Elem()) - atomicStoreDiscardInfo(&a.discard, di) - } - di.discard(toPointer(&m)) -} - -type discardInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []discardFieldInfo - unrecognized field -} - -type discardFieldInfo struct { - field field // Offset of field, guaranteed to be valid - discard func(src pointer) -} - -var ( - discardInfoMap = map[reflect.Type]*discardInfo{} - discardInfoLock sync.Mutex -) - -func getDiscardInfo(t reflect.Type) *discardInfo { - discardInfoLock.Lock() - defer discardInfoLock.Unlock() - di := discardInfoMap[t] - if di == nil { - di = &discardInfo{typ: t} - discardInfoMap[t] = di - } - return di -} - -func (di *discardInfo) discard(src pointer) { - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&di.initialized) == 0 { - di.computeDiscardInfo() - } - - for _, fi := range di.fields { - sfp := src.offset(fi.field) - fi.discard(sfp) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { - // Ignore lock since DiscardUnknown is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - DiscardUnknown(m) - } - } - } - - if di.unrecognized.IsValid() { - *src.offset(di.unrecognized).toBytes() = nil - } -} - -func (di *discardInfo) computeDiscardInfo() { - di.lock.Lock() - defer di.lock.Unlock() - if di.initialized != 0 { - return - } - t := di.typ - n := t.NumField() - - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - dfi := discardFieldInfo{field: toField(&f)} - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) - case isSlice: // E.g., []*pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sps := src.getPointerSlice() - for _, sp := range sps { - if !sp.isNil() { - di.discard(sp) - } - } - } - default: // E.g., *pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sp := src.getPointer() - if !sp.isNil() { - di.discard(sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) - default: // E.g., map[K]V - if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) - dfi.discard = func(src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - DiscardUnknown(val.Interface().(Message)) - } - } - } else { - dfi.discard = func(pointer) {} // Noop - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) - default: // E.g., interface{} - // TODO: Make this faster? - dfi.discard = func(src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - DiscardUnknown(sv.Interface().(Message)) - } - } - } - } - default: - continue - } - di.fields = append(di.fields, dfi) - } - - di.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - di.unrecognized = toField(&f) - } - - atomic.StoreInt32(&di.initialized, 1) -} - -func discardLegacy(m Message) { - v := reflect.ValueOf(m) - if v.Kind() != reflect.Ptr || v.IsNil() { - return - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return - } - t := v.Type() - - for i := 0; i < v.NumField(); i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - vf := v.Field(i) - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) - case isSlice: // E.g., []*pb.T - for j := 0; j < vf.Len(); j++ { - discardLegacy(vf.Index(j).Interface().(Message)) - } - default: // E.g., *pb.T - discardLegacy(vf.Interface().(Message)) - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) - default: // E.g., map[K]V - tv := vf.Type().Elem() - if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) - for _, key := range vf.MapKeys() { - val := vf.MapIndex(key) - discardLegacy(val.Interface().(Message)) - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) - default: // E.g., test_proto.isCommunique_Union interface - if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { - vf = vf.Elem() // E.g., *test_proto.Communique_Msg - if !vf.IsNil() { - vf = vf.Elem() // E.g., test_proto.Communique_Msg - vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value - if vf.Kind() == reflect.Ptr { - discardLegacy(vf.Interface().(Message)) - } - } - } - } - } - } - - if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { - if vf.Type() != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - vf.Set(reflect.ValueOf([]byte(nil))) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(m); err == nil { - // Ignore lock since discardLegacy is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - discardLegacy(m) - } - } - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 3abfed2..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,203 +0,0 @@ -// 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" - "reflect" -) - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") - - // ErrTooLarge is the error returned if Marshal is called with a - // message that encodes to >2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// 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 { - switch { - case x < 1<<7: - return 1 - case x < 1<<14: - return 2 - case x < 1<<21: - return 3 - case x < 1<<28: - return 4 - case x < 1<<35: - return 5 - case x < 1<<42: - return 6 - case x < 1<<49: - return 7 - case x < 1<<56: - return 8 - case x < 1<<63: - return 9 - } - return 10 -} - -// 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 -} - -// 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 -} - -// 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)))) -} - -// 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)))) -} - -// 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 -} - -// 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 -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - siz := Size(pb) - p.EncodeVarint(uint64(siz)) - return p.Marshal(pb) -} - -// 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 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index d4db5a1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal. Note a "bytes" field, - although represented by []byte, is not a repeated field and the - rule for the scalar fields described above applies. - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Two map fields are equal iff their lengths are the same, - and they contain the same set of elements. Zero-length map - fields are equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_InternalExtensions") - if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - return bytes.Equal(u1, u2) -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - // Maps may have nil values in them, so check for nil. - if v1.IsNil() && v2.IsNil() { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// x1 and x2 are InternalExtensions. -func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { - em1, _ := x1.extensionsRead() - em2, _ := x2.extensionsRead() - return equalExtMap(base, em1, em2) -} - -func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1, m2 := e1.value, e2.value - - if m1 == nil && m2 == nil { - // Both have only encoded form. - if bytes.Equal(e1.enc, e2.enc) { - continue - } - // The bytes are different, but the extensions might still be - // equal. We need to decode them to compare. - } - - 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 { - // If both have only encoded form and the bytes are the same, - // it is handled above. We get here when the bytes are different. - // We don't know how to decode it, so just compare them as byte - // slices. - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - return false - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index 816a3b9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,543 +0,0 @@ -// 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" - "io" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer generated by the current -// proto compiler that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - extensionsWrite() map[int32]Extension - extensionsRead() (map[int32]Extension, sync.Locker) -} - -// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous -// version of the proto compiler that may be extended. -type extendableProtoV1 interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. -type extensionAdapter struct { - extendableProtoV1 -} - -func (e extensionAdapter) extensionsWrite() map[int32]Extension { - return e.ExtensionMap() -} - -func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { - return e.ExtensionMap(), notLocker{} -} - -// notLocker is a sync.Locker whose Lock and Unlock methods are nops. -type notLocker struct{} - -func (n notLocker) Lock() {} -func (n notLocker) Unlock() {} - -// extendable returns the extendableProto interface for the given generated proto message. -// If the proto message has the old extension format, it returns a wrapper that implements -// the extendableProto interface. -func extendable(p interface{}) (extendableProto, error) { - switch p := p.(type) { - case extendableProto: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return p, nil - case extendableProtoV1: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return extensionAdapter{p}, nil - } - // Don't allocate a specific error containing %T: - // this is the hot path for Clone and MarshalText. - return nil, errNotExtendable -} - -var errNotExtendable = errors.New("proto: not an extendable proto.Message") - -func isNilPtr(x interface{}) bool { - v := reflect.ValueOf(x) - return v.Kind() == reflect.Ptr && v.IsNil() -} - -// XXX_InternalExtensions is an internal representation of proto extensions. -// -// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, -// thus gaining the unexported 'extensions' method, which can be called only from the proto package. -// -// The methods of XXX_InternalExtensions are not concurrency safe in general, -// but calls to logically read-only methods such as has and get may be executed concurrently. -type XXX_InternalExtensions struct { - // The struct must be indirect so that if a user inadvertently copies a - // generated message and its embedded XXX_InternalExtensions, they - // avoid the mayhem of a copied mutex. - // - // The mutex serializes all logically read-only operations to p.extensionMap. - // It is up to the client to ensure that write operations to p.extensionMap are - // mutually exclusive with other accesses. - p *struct { - mu sync.Mutex - extensionMap map[int32]Extension - } -} - -// extensionsWrite returns the extension map, creating it on first use. -func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { - if e.p == nil { - e.p = new(struct { - mu sync.Mutex - extensionMap map[int32]Extension - }) - e.p.extensionMap = make(map[int32]Extension) - } - return e.p.extensionMap -} - -// extensionsRead returns the extensions map for read-only use. It may be nil. -// The caller must hold the returned mutex's lock when accessing Elements within the map. -func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { - if e.p == nil { - return nil, nil - } - return e.p.extensionMap, &e.p.mu -} - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style - Filename string // name of the file in which the extension is defined -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - value interface{} - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base Message, id int32, b []byte) { - epb, err := extendable(base) - if err != nil { - return - } - extmap := epb.extensionsWrite() - extmap[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - var pbi interface{} = pb - // Check the extended type. - if ea, ok := pbi.(extensionAdapter); ok { - pbi = ea.extendableProtoV1 - } - if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) - } - // 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 -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb Message, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - epb, err := extendable(pb) - if err != nil { - return false - } - extmap, mu := epb.extensionsRead() - if extmap == nil { - return false - } - mu.Lock() - _, ok := extmap[extension.Field] - mu.Unlock() - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb Message, extension *ExtensionDesc) { - epb, err := extendable(pb) - if err != nil { - return - } - // TODO: Check types, field numbers, etc.? - extmap := epb.extensionsWrite() - delete(extmap, extension.Field) -} - -// GetExtension retrieves a proto2 extended field from pb. -// -// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), -// then GetExtension parses the encoded field and returns a Go value of the specified type. -// If the field is not present, then the default value is returned (if one is specified), -// otherwise ErrMissingExtension is reported. -// -// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes of the field extension. -func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - - if extension.ExtendedType != nil { - // can only check type if this is a complete descriptor - if err := checkExtensionTypes(epb, extension); err != nil { - return nil, err - } - } - - emap, mu := epb.extensionsRead() - if emap == nil { - return defaultExtensionValue(extension) - } - mu.Lock() - defer mu.Unlock() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return e.value, nil - } - - if extension.ExtensionType == nil { - // incomplete descriptor - return e.enc, 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) { - if extension.ExtensionType == nil { - // incomplete descriptor, so no default - return nil, ErrMissingExtension - } - - 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) { - t := reflect.TypeOf(extension.ExtensionType) - unmarshal := typeUnmarshaler(t, extension.Tag) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate space to store the pointer/slice. - value := reflect.New(t).Elem() - - var err error - for { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - wire := int(x) & 7 - - b, err = unmarshal(b, valToPointer(value.Addr()), wire) - if err != nil { - return nil, err - } - - if len(b) == 0 { - 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, err := extendable(pb) - if err != nil { - return nil, err - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. -// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing -// just the Field field, which defines the extension's field number. -func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - registeredExtensions := RegisteredExtensions(pb) - - emap, mu := epb.extensionsRead() - if emap == nil { - return nil, nil - } - mu.Lock() - defer mu.Unlock() - extensions := make([]*ExtensionDesc, 0, len(emap)) - for extid, e := range emap { - desc := e.desc - if desc == nil { - desc = registeredExtensions[extid] - if desc == nil { - desc = &ExtensionDesc{Field: extid} - } - } - - extensions = append(extensions, desc) - } - return extensions, nil -} - -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, err := extendable(pb) - if err != nil { - return err - } - if err := checkExtensionTypes(epb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return errors.New("proto: bad extension value type") - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - extmap := epb.extensionsWrite() - extmap[extension.Field] = Extension{desc: extension, value: value} - return nil -} - -// ClearAllExtensions clears all extensions from pb. -func ClearAllExtensions(pb Message) { - epb, err := extendable(pb) - if err != nil { - return - } - m := epb.extensionsWrite() - for k := range m { - delete(m, k) - } -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 75565cc..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,979 +0,0 @@ -// 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. - - 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" -) - -// RequiredNotSetError is an error type returned by either Marshal or Unmarshal. -// Marshal reports this when a required field is not initialized. -// Unmarshal reports this when a required field is missing from the wire data. -type RequiredNotSetError struct{ field string } - -func (e *RequiredNotSetError) Error() string { - if e.field == "" { - return fmt.Sprintf("proto: required field not set") - } - return fmt.Sprintf("proto: required field %q not set", e.field) -} -func (e *RequiredNotSetError) RequiredNotSet() bool { - return true -} - -type invalidUTF8Error struct{ field string } - -func (e *invalidUTF8Error) Error() string { - if e.field == "" { - return "proto: invalid UTF-8 detected" - } - return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field) -} -func (e *invalidUTF8Error) InvalidUTF8() bool { - return true -} - -// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8. -// This error should not be exposed to the external API as such errors should -// be recreated with the field information. -var errInvalidUTF8 = &invalidUTF8Error{} - -// isNonFatal reports whether the error is either a RequiredNotSet error -// or a InvalidUTF8 error. -func isNonFatal(err error) bool { - if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() { - return true - } - if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() { - return true - } - return false -} - -type nonFatal struct{ E error } - -// Merge merges err into nf and reports whether it was successful. -// Otherwise it returns false for any fatal non-nil errors. -func (nf *nonFatal) Merge(err error) (ok bool) { - if err == nil { - return true // not an error - } - if !isNonFatal(err) { - return false // fatal error - } - if nf.E == nil { - nf.E = err // store first instance of non-fatal error - } - return true -} - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - deterministic bool -} - -// 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 } - -// SetDeterministic sets whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (p *Buffer) SetDeterministic(deterministic bool) { - p.deterministic = deterministic -} - -/* - * 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 -} - -// mapKeys returns a sort.Interface to be used for sorting the map keys. -// Map fields may have key types of non-float scalars, strings and enums. -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{vs: vs} - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. - 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() } - case reflect.Bool: - s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true - case reflect.String: - s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } - default: - panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -// ProtoPackageIsVersion2 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion2 = true - -// ProtoPackageIsVersion1 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion1 = true - -// InternalMessageInfo is a type used internally by generated .pb.go files. -// This type is not intended to be used by non-generated code. -// This type is not subject to any compatibility guarantee. -type InternalMessageInfo struct { - marshal *marshalInfo - unmarshal *unmarshalInfo - merge *mergeInfo - discard *discardInfo -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index 3b6ca41..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,314 +0,0 @@ -// 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" - "sync" -) - -// 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 { - return ms.find(pb) != nil -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(exts interface{}) ([]byte, error) { - return marshalMessageSet(exts, false) -} - -// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. -func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var u marshalInfo - siz := u.sizeMessageSet(exts) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, exts, deterministic) - - case map[int32]Extension: - // This is an old-style extension map. - // Wrap it in a new-style XXX_InternalExtensions. - ie := XXX_InternalExtensions{ - p: &struct { - mu sync.Mutex - extensionMap map[int32]Extension - }{ - extensionMap: exts, - }, - } - - var u marshalInfo - siz := u.sizeMessageSet(&ie) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, &ie, deterministic) - - default: - return nil, errors.New("proto: not an extension map") - } -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var mu sync.Locker - m, mu = exts.extensionsRead() - if m != nil { - // Keep the extensions map locked until we're done marshaling to prevent - // races between marshaling and unmarshaling the lazily-{en,de}coded - // values. - mu.Lock() - defer mu.Unlock() - } - case map[int32]Extension: - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - - if i > 0 && b.Len() > 1 { - b.WriteByte(',') - } - - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index b6cad90..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,357 +0,0 @@ -// 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 purego appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "reflect" - "sync" -) - -const unsafeAllowed = false - -// A field identifies a field in a struct, accessible from a pointer. -// 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) - -// zeroField is a noop when calling pointer.offset. -var zeroField = field([]int{}) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// The pointer type is for the table-driven decoder. -// The implementation here uses a reflect.Value of pointer type to -// create a generic pointer. In pointer_unsafe.go we use unsafe -// instead of reflect to implement the same (but faster) interface. -type pointer struct { - v reflect.Value -} - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - return pointer{v: reflect.ValueOf(*i)} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - v := reflect.ValueOf(*i) - u := reflect.New(v.Type()) - u.Elem().Set(v) - return pointer{v: u} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{v: v} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} -} - -func (p pointer) isNil() bool { - return p.v.IsNil() -} - -// grow updates the slice s in place to make it one element longer. -// s must be addressable. -// Returns the (addressable) new element. -func grow(s reflect.Value) reflect.Value { - n, m := s.Len(), s.Cap() - if n < m { - s.SetLen(n + 1) - } else { - s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) - } - return s.Index(n) -} - -func (p pointer) toInt64() *int64 { - return p.v.Interface().(*int64) -} -func (p pointer) toInt64Ptr() **int64 { - return p.v.Interface().(**int64) -} -func (p pointer) toInt64Slice() *[]int64 { - return p.v.Interface().(*[]int64) -} - -var int32ptr = reflect.TypeOf((*int32)(nil)) - -func (p pointer) toInt32() *int32 { - return p.v.Convert(int32ptr).Interface().(*int32) -} - -// The toInt32Ptr/Slice methods don't work because of enums. -// Instead, we must use set/get methods for the int32ptr/slice case. -/* - func (p pointer) toInt32Ptr() **int32 { - return p.v.Interface().(**int32) -} - func (p pointer) toInt32Slice() *[]int32 { - return p.v.Interface().(*[]int32) -} -*/ -func (p pointer) getInt32Ptr() *int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().(*int32) - } - // an enum - return p.v.Elem().Convert(int32PtrType).Interface().(*int32) -} -func (p pointer) setInt32Ptr(v int32) { - // Allocate value in a *int32. Possibly convert that to a *enum. - // Then assign it to a **int32 or **enum. - // Note: we can convert *int32 to *enum, but we can't convert - // **int32 to **enum! - p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) -} - -// getInt32Slice copies []int32 from p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getInt32Slice() []int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().([]int32) - } - // an enum - // Allocate a []int32, then assign []enum's values into it. - // Note: we can't convert []enum to []int32. - slice := p.v.Elem() - s := make([]int32, slice.Len()) - for i := 0; i < slice.Len(); i++ { - s[i] = int32(slice.Index(i).Int()) - } - return s -} - -// setInt32Slice copies []int32 into p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setInt32Slice(v []int32) { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - p.v.Elem().Set(reflect.ValueOf(v)) - return - } - // an enum - // Allocate a []enum, then assign []int32's values into it. - // Note: we can't convert []enum to []int32. - slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) - for i, x := range v { - slice.Index(i).SetInt(int64(x)) - } - p.v.Elem().Set(slice) -} -func (p pointer) appendInt32Slice(v int32) { - grow(p.v.Elem()).SetInt(int64(v)) -} - -func (p pointer) toUint64() *uint64 { - return p.v.Interface().(*uint64) -} -func (p pointer) toUint64Ptr() **uint64 { - return p.v.Interface().(**uint64) -} -func (p pointer) toUint64Slice() *[]uint64 { - return p.v.Interface().(*[]uint64) -} -func (p pointer) toUint32() *uint32 { - return p.v.Interface().(*uint32) -} -func (p pointer) toUint32Ptr() **uint32 { - return p.v.Interface().(**uint32) -} -func (p pointer) toUint32Slice() *[]uint32 { - return p.v.Interface().(*[]uint32) -} -func (p pointer) toBool() *bool { - return p.v.Interface().(*bool) -} -func (p pointer) toBoolPtr() **bool { - return p.v.Interface().(**bool) -} -func (p pointer) toBoolSlice() *[]bool { - return p.v.Interface().(*[]bool) -} -func (p pointer) toFloat64() *float64 { - return p.v.Interface().(*float64) -} -func (p pointer) toFloat64Ptr() **float64 { - return p.v.Interface().(**float64) -} -func (p pointer) toFloat64Slice() *[]float64 { - return p.v.Interface().(*[]float64) -} -func (p pointer) toFloat32() *float32 { - return p.v.Interface().(*float32) -} -func (p pointer) toFloat32Ptr() **float32 { - return p.v.Interface().(**float32) -} -func (p pointer) toFloat32Slice() *[]float32 { - return p.v.Interface().(*[]float32) -} -func (p pointer) toString() *string { - return p.v.Interface().(*string) -} -func (p pointer) toStringPtr() **string { - return p.v.Interface().(**string) -} -func (p pointer) toStringSlice() *[]string { - return p.v.Interface().(*[]string) -} -func (p pointer) toBytes() *[]byte { - return p.v.Interface().(*[]byte) -} -func (p pointer) toBytesSlice() *[][]byte { - return p.v.Interface().(*[][]byte) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return p.v.Interface().(*XXX_InternalExtensions) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return p.v.Interface().(*map[int32]Extension) -} -func (p pointer) getPointer() pointer { - return pointer{v: p.v.Elem()} -} -func (p pointer) setPointer(q pointer) { - p.v.Elem().Set(q.v) -} -func (p pointer) appendPointer(q pointer) { - grow(p.v.Elem()).Set(q.v) -} - -// getPointerSlice copies []*T from p as a new []pointer. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getPointerSlice() []pointer { - if p.v.IsNil() { - return nil - } - n := p.v.Elem().Len() - s := make([]pointer, n) - for i := 0; i < n; i++ { - s[i] = pointer{v: p.v.Elem().Index(i)} - } - return s -} - -// setPointerSlice copies []pointer into p as a new []*T. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setPointerSlice(v []pointer) { - if v == nil { - p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) - return - } - s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) - for _, p := range v { - s = reflect.Append(s, p.v) - } - p.v.Elem().Set(s) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - if p.v.Elem().IsNil() { - return pointer{v: p.v.Elem()} - } - return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct -} - -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - // TODO: check that p.v.Type().Elem() == t? - return p.v -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} - -var atomicLock sync.Mutex diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index d55a335..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,308 +0,0 @@ -// 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 !purego,!appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "sync/atomic" - "unsafe" -) - -const unsafeAllowed = true - -// A field identifies a field in a struct, accessible from a pointer. -// 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) - -// zeroField is a noop when calling pointer.offset. -const zeroField = field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != invalidField -} - -// The pointer type below is for the new table-driven encoder/decoder. -// The implementation here uses unsafe.Pointer to create a generic pointer. -// In pointer_reflect.go we use reflect instead of unsafe to implement -// the same (but slower) interface. -type pointer struct { - p unsafe.Pointer -} - -// size of pointer -var ptrSize = unsafe.Sizeof(uintptr(0)) - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - // Super-tricky - read pointer out of data word of interface value. - // Saves ~25ns over the equivalent: - // return valToPointer(reflect.ValueOf(*i)) - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - // Super-tricky - read or get the address of data word of interface value. - if isptr { - // The interface is of pointer type, thus it is a direct interface. - // The data word is the pointer data itself. We take its address. - return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} - } - // The interface is not of pointer type. The data word is the pointer - // to the data. - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{p: unsafe.Pointer(v.Pointer())} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - // For safety, we should panic if !f.IsValid, however calling panic causes - // this to no longer be inlineable, which is a serious performance cost. - /* - if !f.IsValid() { - panic("invalid field") - } - */ - return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} -} - -func (p pointer) isNil() bool { - return p.p == nil -} - -func (p pointer) toInt64() *int64 { - return (*int64)(p.p) -} -func (p pointer) toInt64Ptr() **int64 { - return (**int64)(p.p) -} -func (p pointer) toInt64Slice() *[]int64 { - return (*[]int64)(p.p) -} -func (p pointer) toInt32() *int32 { - return (*int32)(p.p) -} - -// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. -/* - func (p pointer) toInt32Ptr() **int32 { - return (**int32)(p.p) - } - func (p pointer) toInt32Slice() *[]int32 { - return (*[]int32)(p.p) - } -*/ -func (p pointer) getInt32Ptr() *int32 { - return *(**int32)(p.p) -} -func (p pointer) setInt32Ptr(v int32) { - *(**int32)(p.p) = &v -} - -// getInt32Slice loads a []int32 from p. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getInt32Slice() []int32 { - return *(*[]int32)(p.p) -} - -// setInt32Slice stores a []int32 to p. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setInt32Slice(v []int32) { - *(*[]int32)(p.p) = v -} - -// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? -func (p pointer) appendInt32Slice(v int32) { - s := (*[]int32)(p.p) - *s = append(*s, v) -} - -func (p pointer) toUint64() *uint64 { - return (*uint64)(p.p) -} -func (p pointer) toUint64Ptr() **uint64 { - return (**uint64)(p.p) -} -func (p pointer) toUint64Slice() *[]uint64 { - return (*[]uint64)(p.p) -} -func (p pointer) toUint32() *uint32 { - return (*uint32)(p.p) -} -func (p pointer) toUint32Ptr() **uint32 { - return (**uint32)(p.p) -} -func (p pointer) toUint32Slice() *[]uint32 { - return (*[]uint32)(p.p) -} -func (p pointer) toBool() *bool { - return (*bool)(p.p) -} -func (p pointer) toBoolPtr() **bool { - return (**bool)(p.p) -} -func (p pointer) toBoolSlice() *[]bool { - return (*[]bool)(p.p) -} -func (p pointer) toFloat64() *float64 { - return (*float64)(p.p) -} -func (p pointer) toFloat64Ptr() **float64 { - return (**float64)(p.p) -} -func (p pointer) toFloat64Slice() *[]float64 { - return (*[]float64)(p.p) -} -func (p pointer) toFloat32() *float32 { - return (*float32)(p.p) -} -func (p pointer) toFloat32Ptr() **float32 { - return (**float32)(p.p) -} -func (p pointer) toFloat32Slice() *[]float32 { - return (*[]float32)(p.p) -} -func (p pointer) toString() *string { - return (*string)(p.p) -} -func (p pointer) toStringPtr() **string { - return (**string)(p.p) -} -func (p pointer) toStringSlice() *[]string { - return (*[]string)(p.p) -} -func (p pointer) toBytes() *[]byte { - return (*[]byte)(p.p) -} -func (p pointer) toBytesSlice() *[][]byte { - return (*[][]byte)(p.p) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(p.p) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return (*map[int32]Extension)(p.p) -} - -// getPointerSlice loads []*T from p as a []pointer. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getPointerSlice() []pointer { - // Super-tricky - p should point to a []*T where T is a - // message type. We load it as []pointer. - return *(*[]pointer)(p.p) -} - -// setPointerSlice stores []pointer into p as a []*T. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setPointerSlice(v []pointer) { - // Super-tricky - p should point to a []*T where T is a - // message type. We store it as []pointer. - *(*[]pointer)(p.p) = v -} - -// getPointer loads the pointer at p and returns it. -func (p pointer) getPointer() pointer { - return pointer{p: *(*unsafe.Pointer)(p.p)} -} - -// setPointer stores the pointer q at p. -func (p pointer) setPointer(q pointer) { - *(*unsafe.Pointer)(p.p) = q.p -} - -// append q to the slice pointed to by p. -func (p pointer) appendPointer(q pointer) { - s := (*[]unsafe.Pointer)(p.p) - *s = append(*s, q.p) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - // Super-tricky - read pointer out of data word of interface value. - return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} -} - -// asPointerTo returns a reflect.Value that is a pointer to an -// object of type t stored at p. -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - return reflect.NewAt(t, p.p) -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index 50b99b8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,544 +0,0 @@ -// 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 -) - -// 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 - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. - OneofTypes map[string]*OneofProperties -} - -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - - mtype reflect.Type // set for map types only - MapKeyProp *Properties // set for map types only - MapValProp *Properties // set for map types only -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { - s += ",json=" + p.JSONName - } - if p.proto3 { - s += ",proto3" - } - if p.oneof { - s += ",oneof" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - case "fixed32": - p.WireType = WireFixed32 - case "fixed64": - p.WireType = WireFixed64 - case "zigzag32": - p.WireType = WireVarint - case "zigzag64": - p.WireType = WireVarint - 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 - } - -outer: - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break outer - } - } - } -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// setFieldProps initializes the field properties for submessages and maps. -func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - switch t1 := typ; t1.Kind() { - case reflect.Ptr: - if t1.Elem().Kind() == reflect.Struct { - p.stype = t1.Elem() - } - - case reflect.Slice: - if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { - p.stype = t2.Elem() - } - - case reflect.Map: - p.mtype = t1 - p.MapKeyProp = &Properties{} - p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.MapValProp = &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.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -) - -// 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 tag == "" { - return - } - p.Parse(tag) - p.setFieldProps(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.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) - - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - } - - // 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{} - _, _, _, oots = om.XXX_OneofFuncs() - - // 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 -} - -// 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 ( - protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers - protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types - 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 := protoTypedNils[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { - // Generated code always calls RegisterType with nil x. - // This check is just for extra safety. - protoTypedNils[name] = x - } else { - protoTypedNils[name] = reflect.Zero(t).Interface().(Message) - } - revProtoTypes[t] = name -} - -// RegisterMapType is called from generated code and maps from the fully qualified -// proto name to the native map type of the proto map definition. -func RegisterMapType(x interface{}, name string) { - if reflect.TypeOf(x).Kind() != reflect.Map { - panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) - } - if _, ok := protoMapTypes[name]; ok { - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoMapTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -// The type is not guaranteed to implement proto.Message if the name refers to a -// map entry. -func MessageType(name string) reflect.Type { - if t, ok := protoTypedNils[name]; ok { - return reflect.TypeOf(t) - } - return protoMapTypes[name] -} - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100644 index b167944..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2767 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errLater error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name} - } - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errLater -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(t, tags, false, false) - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - validateUTF8 := true - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if validateUTF8 { - if pointer { - return sizeStringPtr, appendUTF8StringPtr - } - if slice { - return sizeStringSlice, appendUTF8StringSlice - } - if nozero { - return sizeStringValueNoZero, appendUTF8StringValueNoZero - } - return sizeStringValue, appendUTF8StringValue - } - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - - // If value is a message with nested maps, calling - // valSizer in marshal may be quadratic. We should use - // cached version in marshal (but not in size). - // If value is not message type, we don't have size cache, - // but it cannot be nested either. Just use valSizer. - valCachedSizer := valSizer - if valIsPtr && valType.Elem().Kind() == reflect.Struct { - u := getMarshalInfo(valType.Elem()) - valCachedSizer = func(ptr pointer, tagsize int) int { - // Same as message sizer, but use cache. - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.cachedsize(p) - return siz + SizeVarint(uint64(siz)) + tagsize - } - } - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - - var nerr nonFatal - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if !nerr.Merge(err) { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != ErrNil && !nerr.Merge(err) { // allow nil value in map - return b, err - } - } - return b, nerr.E - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - 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. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if !nerr.Merge(err) { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - var nerr nonFatal - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, 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. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100644 index 5525def..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,654 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100644 index ebf1caa..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,2051 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - if errLater == nil { - errLater = r - } - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if reqMask != u.reqMask && errLater == nil { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - errLater = &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return errLater -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask, name) - } - - // Find any types associated with oneof fields. - // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") - if fn.IsValid() { - res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} - for i := res.Len() - 1; i >= 0; i-- { - v := res.Index(i) // interface{} - tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tags := strings.Split(f.Tag.Get("protobuf"), ",") - fieldNum, err := strconv.Atoi(tags[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tags[1]) - } - var name string - for _, tag := range tags { - if strings.HasPrefix(tag, "name=") { - name = strings.TrimPrefix(tag, "name=") - break - } - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(fieldNum, of.field, unmarshal, 0, name) - } - } - } - } - - // Get extension ranges, if any. - fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0, "") - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - proto3 := false - validateUTF8 := true - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - if tag == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if validateUTF8 { - if pointer { - return unmarshalUTF8StringPtr - } - if slice { - return unmarshalUTF8StringSlice - } - return unmarshalUTF8StringValue - } - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - var nerr nonFatal - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if nerr.Merge(err) { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nerr.E - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - var nerr nonFatal - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if !nerr.Merge(err) { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nerr.E - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) <= 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index 1aaee72..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,843 +0,0 @@ -// 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(" ") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if name == "XXX_NoUnkeyedLiteral" { - continue - } - - 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 := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.MapKeyProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.MapValProp); 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 - } - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, err := extendable(pv.Interface()); err == nil { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if v.CanAddr() { - // Calling v.Interface on a struct causes the reflect package to - // copy the entire struct. This is racy with the new Marshaler - // since we atomically update the XXX_sizecache. - // - // Thus, we retrieve a pointer to the struct if possible to avoid - // a race since v.Interface on the pointer doesn't copy the struct. - // - // If v is not addressable, then we are not worried about a race - // since it implies that the binary Marshaler cannot possibly be - // mutating this value. - v = v.Addr() - } - if etm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if err := tm.writeStruct(w, v); err != nil { - return err - } - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index bb55a3a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,880 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") -) - -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': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(i), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// 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]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.MapKeyProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.MapValProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - return um.UnmarshalText([]byte(s)) - } - pb.Reset() - v := reflect.ValueOf(pb) - return newTextParser(s).readStruct(v.Elem(), "") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/any.go deleted file mode 100644 index 70276e8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/any.go +++ /dev/null @@ -1,141 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -// This file implements functions to marshal proto.Message to/from -// google.protobuf.Any message. - -import ( - "fmt" - "reflect" - "strings" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/any" -) - -const googleApis = "type.googleapis.com/" - -// AnyMessageName returns the name of the message contained in a google.protobuf.Any message. -// -// Note that regular type assertions should be done using the Is -// function. AnyMessageName is provided for less common use cases like filtering a -// sequence of Any messages based on a set of allowed message type names. -func AnyMessageName(any *any.Any) (string, error) { - if any == nil { - return "", fmt.Errorf("message is nil") - } - slash := strings.LastIndex(any.TypeUrl, "/") - if slash < 0 { - return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) - } - return any.TypeUrl[slash+1:], nil -} - -// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any. -func MarshalAny(pb proto.Message) (*any.Any, error) { - value, err := proto.Marshal(pb) - if err != nil { - return nil, err - } - return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil -} - -// DynamicAny is a value that can be passed to UnmarshalAny to automatically -// allocate a proto.Message for the type specified in a google.protobuf.Any -// message. The allocated message is stored in the embedded proto.Message. -// -// Example: -// -// var x ptypes.DynamicAny -// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } -// fmt.Printf("unmarshaled message: %v", x.Message) -type DynamicAny struct { - proto.Message -} - -// Empty returns a new proto.Message of the type specified in a -// google.protobuf.Any message. It returns an error if corresponding message -// type isn't linked in. -func Empty(any *any.Any) (proto.Message, error) { - aname, err := AnyMessageName(any) - if err != nil { - return nil, err - } - - t := proto.MessageType(aname) - if t == nil { - return nil, fmt.Errorf("any: message type %q isn't linked in", aname) - } - return reflect.New(t.Elem()).Interface().(proto.Message), nil -} - -// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any -// message and places the decoded result in pb. It returns an error if type of -// contents of Any message does not match type of pb message. -// -// pb can be a proto.Message, or a *DynamicAny. -func UnmarshalAny(any *any.Any, pb proto.Message) error { - if d, ok := pb.(*DynamicAny); ok { - if d.Message == nil { - var err error - d.Message, err = Empty(any) - if err != nil { - return err - } - } - return UnmarshalAny(any, d.Message) - } - - aname, err := AnyMessageName(any) - if err != nil { - return err - } - - mname := proto.MessageName(pb) - if aname != mname { - return fmt.Errorf("mismatched message type: got %q want %q", aname, mname) - } - return proto.Unmarshal(any.Value, pb) -} - -// Is returns true if any value contains a given message type. -func Is(any *any.Any, pb proto.Message) bool { - // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb), - // but it avoids scanning TypeUrl for the slash. - if any == nil { - return false - } - name := proto.MessageName(pb) - prefix := len(any.TypeUrl) - len(name) - return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go deleted file mode 100644 index e3c56d3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/any.proto - -package any // import "github.com/golang/protobuf/ptypes/any" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -type Any struct { - // A URL/resource name whose content describes the type of the - // serialized protocol buffer message. - // - // For URLs which use the scheme `http`, `https`, or no scheme, the - // following restrictions and interpretations apply: - // - // * If no scheme is provided, `https` is assumed. - // * The last segment of the URL's path must represent the fully - // qualified name of the type (as in `path/google.protobuf.Duration`). - // The name should be in a canonical form (e.g., leading "." is - // not accepted). - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` - // Must be a valid serialized protocol buffer of the above specified type. - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Any) Reset() { *m = Any{} } -func (m *Any) String() string { return proto.CompactTextString(m) } -func (*Any) ProtoMessage() {} -func (*Any) Descriptor() ([]byte, []int) { - return fileDescriptor_any_744b9ca530f228db, []int{0} -} -func (*Any) XXX_WellKnownType() string { return "Any" } -func (m *Any) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Any.Unmarshal(m, b) -} -func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Any.Marshal(b, m, deterministic) -} -func (dst *Any) XXX_Merge(src proto.Message) { - xxx_messageInfo_Any.Merge(dst, src) -} -func (m *Any) XXX_Size() int { - return xxx_messageInfo_Any.Size(m) -} -func (m *Any) XXX_DiscardUnknown() { - xxx_messageInfo_Any.DiscardUnknown(m) -} - -var xxx_messageInfo_Any proto.InternalMessageInfo - -func (m *Any) GetTypeUrl() string { - if m != nil { - return m.TypeUrl - } - return "" -} - -func (m *Any) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*Any)(nil), "google.protobuf.Any") -} - -func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_any_744b9ca530f228db) } - -var fileDescriptor_any_744b9ca530f228db = []byte{ - // 185 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, - 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, - 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, - 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, - 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce, - 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52, - 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, - 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, - 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, - 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, - 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/doc.go deleted file mode 100644 index c0d595d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/doc.go +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package ptypes contains code for interacting with well-known types. -*/ -package ptypes diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/duration.go deleted file mode 100644 index 65cb0f8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/duration.go +++ /dev/null @@ -1,102 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -// This file implements conversions between google.protobuf.Duration -// and time.Duration. - -import ( - "errors" - "fmt" - "time" - - durpb "github.com/golang/protobuf/ptypes/duration" -) - -const ( - // Range of a durpb.Duration in seconds, as specified in - // google/protobuf/duration.proto. This is about 10,000 years in seconds. - maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) - minSeconds = -maxSeconds -) - -// validateDuration determines whether the durpb.Duration is valid according to the -// definition in google/protobuf/duration.proto. A valid durpb.Duration -// may still be too large to fit into a time.Duration (the range of durpb.Duration -// is about 10,000 years, and the range of time.Duration is about 290). -func validateDuration(d *durpb.Duration) error { - if d == nil { - return errors.New("duration: nil Duration") - } - if d.Seconds < minSeconds || d.Seconds > maxSeconds { - return fmt.Errorf("duration: %v: seconds out of range", d) - } - if d.Nanos <= -1e9 || d.Nanos >= 1e9 { - return fmt.Errorf("duration: %v: nanos out of range", d) - } - // Seconds and Nanos must have the same sign, unless d.Nanos is zero. - if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { - return fmt.Errorf("duration: %v: seconds and nanos have different signs", d) - } - return nil -} - -// Duration converts a durpb.Duration to a time.Duration. Duration -// returns an error if the durpb.Duration is invalid or is too large to be -// represented in a time.Duration. -func Duration(p *durpb.Duration) (time.Duration, error) { - if err := validateDuration(p); err != nil { - return 0, err - } - d := time.Duration(p.Seconds) * time.Second - if int64(d/time.Second) != p.Seconds { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) - } - if p.Nanos != 0 { - d += time.Duration(p.Nanos) - if (d < 0) != (p.Nanos < 0) { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) - } - } - return d, nil -} - -// DurationProto converts a time.Duration to a durpb.Duration. -func DurationProto(d time.Duration) *durpb.Duration { - nanos := d.Nanoseconds() - secs := nanos / 1e9 - nanos -= secs * 1e9 - return &durpb.Duration{ - Seconds: secs, - Nanos: int32(nanos), - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go deleted file mode 100644 index a7beb2c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/duration.proto - -package duration // import "github.com/golang/protobuf/ptypes/duration" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -type Duration struct { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { - return fileDescriptor_duration_e7d612259e3f0613, []int{0} -} -func (*Duration) XXX_WellKnownType() string { return "Duration" } -func (m *Duration) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Duration.Unmarshal(m, b) -} -func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Duration.Marshal(b, m, deterministic) -} -func (dst *Duration) XXX_Merge(src proto.Message) { - xxx_messageInfo_Duration.Merge(dst, src) -} -func (m *Duration) XXX_Size() int { - return xxx_messageInfo_Duration.Size(m) -} -func (m *Duration) XXX_DiscardUnknown() { - xxx_messageInfo_Duration.DiscardUnknown(m) -} - -var xxx_messageInfo_Duration proto.InternalMessageInfo - -func (m *Duration) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Duration) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -func init() { - proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") -} - -func init() { - proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_duration_e7d612259e3f0613) -} - -var fileDescriptor_duration_e7d612259e3f0613 = []byte{ - // 190 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, - 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, - 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, - 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, - 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c, - 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56, - 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, - 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4, - 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, - 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, - 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/timestamp.go deleted file mode 100644 index 47f10db..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/timestamp.go +++ /dev/null @@ -1,134 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -// This file implements operations on google.protobuf.Timestamp. - -import ( - "errors" - "fmt" - "time" - - tspb "github.com/golang/protobuf/ptypes/timestamp" -) - -const ( - // Seconds field of the earliest valid Timestamp. - // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - minValidSeconds = -62135596800 - // Seconds field just after the latest valid Timestamp. - // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - maxValidSeconds = 253402300800 -) - -// validateTimestamp determines whether a Timestamp is valid. -// A valid timestamp represents a time in the range -// [0001-01-01, 10000-01-01) and has a Nanos field -// in the range [0, 1e9). -// -// If the Timestamp is valid, validateTimestamp returns nil. -// Otherwise, it returns an error that describes -// the problem. -// -// Every valid Timestamp can be represented by a time.Time, but the converse is not true. -func validateTimestamp(ts *tspb.Timestamp) error { - if ts == nil { - return errors.New("timestamp: nil Timestamp") - } - if ts.Seconds < minValidSeconds { - return fmt.Errorf("timestamp: %v before 0001-01-01", ts) - } - if ts.Seconds >= maxValidSeconds { - return fmt.Errorf("timestamp: %v after 10000-01-01", ts) - } - if ts.Nanos < 0 || ts.Nanos >= 1e9 { - return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) - } - return nil -} - -// Timestamp converts a google.protobuf.Timestamp proto to a time.Time. -// It returns an error if the argument is invalid. -// -// Unlike most Go functions, if Timestamp returns an error, the first return value -// is not the zero time.Time. Instead, it is the value obtained from the -// time.Unix function when passed the contents of the Timestamp, in the UTC -// locale. This may or may not be a meaningful time; many invalid Timestamps -// do map to valid time.Times. -// -// A nil Timestamp returns an error. The first return value in that case is -// undefined. -func Timestamp(ts *tspb.Timestamp) (time.Time, error) { - // Don't return the zero value on error, because corresponds to a valid - // timestamp. Instead return whatever time.Unix gives us. - var t time.Time - if ts == nil { - t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp - } else { - t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() - } - return t, validateTimestamp(ts) -} - -// TimestampNow returns a google.protobuf.Timestamp for the current time. -func TimestampNow() *tspb.Timestamp { - ts, err := TimestampProto(time.Now()) - if err != nil { - panic("ptypes: time.Now() out of Timestamp range") - } - return ts -} - -// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. -// It returns an error if the resulting Timestamp is invalid. -func TimestampProto(t time.Time) (*tspb.Timestamp, error) { - seconds := t.Unix() - nanos := int32(t.Sub(time.Unix(seconds, 0))) - ts := &tspb.Timestamp{ - Seconds: seconds, - Nanos: nanos, - } - if err := validateTimestamp(ts); err != nil { - return nil, err - } - return ts, nil -} - -// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid -// Timestamps, it returns an error message in parentheses. -func TimestampString(ts *tspb.Timestamp) string { - t, err := Timestamp(ts) - if err != nil { - return fmt.Sprintf("(%v)", err) - } - return t.Format(time.RFC3339Nano) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go deleted file mode 100644 index 8e76ae9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/timestamp.proto - -package timestamp // import "github.com/golang/protobuf/ptypes/timestamp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required, though only UTC (as indicated by "Z") is presently supported. -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--) -// to obtain a formatter capable of generating timestamps in this format. -// -// -type Timestamp struct { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { - return fileDescriptor_timestamp_b826e8e5fba671a8, []int{0} -} -func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } -func (m *Timestamp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Timestamp.Unmarshal(m, b) -} -func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) -} -func (dst *Timestamp) XXX_Merge(src proto.Message) { - xxx_messageInfo_Timestamp.Merge(dst, src) -} -func (m *Timestamp) XXX_Size() int { - return xxx_messageInfo_Timestamp.Size(m) -} -func (m *Timestamp) XXX_DiscardUnknown() { - xxx_messageInfo_Timestamp.DiscardUnknown(m) -} - -var xxx_messageInfo_Timestamp proto.InternalMessageInfo - -func (m *Timestamp) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Timestamp) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -func init() { - proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") -} - -func init() { - proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_timestamp_b826e8e5fba671a8) -} - -var fileDescriptor_timestamp_b826e8e5fba671a8 = []byte{ - // 191 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, - 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, - 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, - 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, - 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70, - 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51, - 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, - 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71, - 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, - 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, - 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/go-querystring/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/google/go-querystring/LICENSE deleted file mode 100644 index ae121a1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/go-querystring/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013 Google. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/go-querystring/query/encode.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/go-querystring/query/encode.go deleted file mode 100644 index 37080b1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/go-querystring/query/encode.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package query implements encoding of structs into URL query parameters. -// -// As a simple example: -// -// type Options struct { -// Query string `url:"q"` -// ShowAll bool `url:"all"` -// Page int `url:"page"` -// } -// -// opt := Options{ "foo", true, 2 } -// v, _ := query.Values(opt) -// fmt.Print(v.Encode()) // will output: "q=foo&all=true&page=2" -// -// The exact mapping between Go values and url.Values is described in the -// documentation for the Values() function. -package query - -import ( - "bytes" - "fmt" - "net/url" - "reflect" - "strconv" - "strings" - "time" -) - -var timeType = reflect.TypeOf(time.Time{}) - -var encoderType = reflect.TypeOf(new(Encoder)).Elem() - -// Encoder is an interface implemented by any type that wishes to encode -// itself into URL values in a non-standard way. -type Encoder interface { - EncodeValues(key string, v *url.Values) error -} - -// Values returns the url.Values encoding of v. -// -// Values expects to be passed a struct, and traverses it recursively using the -// following encoding rules. -// -// Each exported struct field is encoded as a URL parameter unless -// -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option -// -// The empty values are false, 0, any nil pointer or interface value, any array -// slice, map, or string of length zero, and any time.Time that returns true -// for IsZero(). -// -// The URL parameter name defaults to the struct field name but can be -// specified in the struct field's tag value. The "url" key in the struct -// field's tag value is the key name, followed by an optional comma and -// options. For example: -// -// // Field is ignored by this package. -// Field int `url:"-"` -// -// // Field appears as URL parameter "myName". -// Field int `url:"myName"` -// -// // Field appears as URL parameter "myName" and the field is omitted if -// // its value is empty -// Field int `url:"myName,omitempty"` -// -// // Field appears as URL parameter "Field" (the default), but the field -// // is skipped if empty. Note the leading comma. -// Field int `url:",omitempty"` -// -// For encoding individual field values, the following type-dependent rules -// apply: -// -// Boolean values default to encoding as the strings "true" or "false". -// Including the "int" option signals that the field should be encoded as the -// strings "1" or "0". -// -// time.Time values default to encoding as RFC3339 timestamps. Including the -// "unix" option signals that the field should be encoded as a Unix time (see -// time.Unix()) -// -// Slice and Array values default to encoding as multiple URL values of the -// same name. Including the "comma" option signals that the field should be -// encoded as a single comma-delimited value. Including the "space" option -// similarly encodes the value as a single space-delimited string. Including -// the "semicolon" option will encode the value as a semicolon-delimited string. -// Including the "brackets" option signals that the multiple URL values should -// have "[]" appended to the value name. "numbered" will append a number to -// the end of each incidence of the value name, example: -// name0=value0&name1=value1, etc. -// -// Anonymous struct fields are usually encoded as if their inner exported -// fields were fields in the outer struct, subject to the standard Go -// visibility rules. An anonymous struct field with a name given in its URL -// tag is treated as having that name, rather than being anonymous. -// -// Non-nil pointer values are encoded as the value pointed to. -// -// Nested structs are encoded including parent fields in value names for -// scoping. e.g: -// -// "user[name]=acme&user[addr][postcode]=1234&user[addr][city]=SFO" -// -// All other values are encoded using their default string representation. -// -// Multiple fields that encode to the same URL parameter name will be included -// as multiple URL values of the same name. -func Values(v interface{}) (url.Values, error) { - values := make(url.Values) - val := reflect.ValueOf(v) - for val.Kind() == reflect.Ptr { - if val.IsNil() { - return values, nil - } - val = val.Elem() - } - - if v == nil { - return values, nil - } - - if val.Kind() != reflect.Struct { - return nil, fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind()) - } - - err := reflectValue(values, val, "") - return values, err -} - -// reflectValue populates the values parameter from the struct fields in val. -// Embedded structs are followed recursively (using the rules defined in the -// Values function documentation) breadth-first. -func reflectValue(values url.Values, val reflect.Value, scope string) error { - var embedded []reflect.Value - - typ := val.Type() - for i := 0; i < typ.NumField(); i++ { - sf := typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - - sv := val.Field(i) - tag := sf.Tag.Get("url") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if name == "" { - if sf.Anonymous && sv.Kind() == reflect.Struct { - // save embedded struct for later processing - embedded = append(embedded, sv) - continue - } - - name = sf.Name - } - - if scope != "" { - name = scope + "[" + name + "]" - } - - if opts.Contains("omitempty") && isEmptyValue(sv) { - continue - } - - if sv.Type().Implements(encoderType) { - if !reflect.Indirect(sv).IsValid() { - sv = reflect.New(sv.Type().Elem()) - } - - m := sv.Interface().(Encoder) - if err := m.EncodeValues(name, &values); err != nil { - return err - } - continue - } - - if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array { - var del byte - if opts.Contains("comma") { - del = ',' - } else if opts.Contains("space") { - del = ' ' - } else if opts.Contains("semicolon") { - del = ';' - } else if opts.Contains("brackets") { - name = name + "[]" - } - - if del != 0 { - s := new(bytes.Buffer) - first := true - for i := 0; i < sv.Len(); i++ { - if first { - first = false - } else { - s.WriteByte(del) - } - s.WriteString(valueString(sv.Index(i), opts)) - } - values.Add(name, s.String()) - } else { - for i := 0; i < sv.Len(); i++ { - k := name - if opts.Contains("numbered") { - k = fmt.Sprintf("%s%d", name, i) - } - values.Add(k, valueString(sv.Index(i), opts)) - } - } - continue - } - - for sv.Kind() == reflect.Ptr { - if sv.IsNil() { - break - } - sv = sv.Elem() - } - - if sv.Type() == timeType { - values.Add(name, valueString(sv, opts)) - continue - } - - if sv.Kind() == reflect.Struct { - reflectValue(values, sv, name) - continue - } - - values.Add(name, valueString(sv, opts)) - } - - for _, f := range embedded { - if err := reflectValue(values, f, scope); err != nil { - return err - } - } - - return nil -} - -// valueString returns the string representation of a value. -func valueString(v reflect.Value, opts tagOptions) string { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - return "" - } - v = v.Elem() - } - - if v.Kind() == reflect.Bool && opts.Contains("int") { - if v.Bool() { - return "1" - } - return "0" - } - - if v.Type() == timeType { - t := v.Interface().(time.Time) - if opts.Contains("unix") { - return strconv.FormatInt(t.Unix(), 10) - } - return t.Format(time.RFC3339) - } - - return fmt.Sprint(v.Interface()) -} - -// isEmptyValue checks if a value should be considered empty for the purposes -// of omitting fields with the "omitempty" option. -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() - } - - if v.Type() == timeType { - return v.Interface().(time.Time).IsZero() - } - - return false -} - -// tagOptions is the string following a comma in a struct field's "url" tag, or -// the empty string. It does not include the leading comma. -type tagOptions []string - -// parseTag splits a struct field's url tag into its name and comma-separated -// options. -func parseTag(tag string) (string, tagOptions) { - s := strings.Split(tag, ",") - return s[0], s[1:] -} - -// Contains checks whether the tagOptions contains the specified option. -func (o tagOptions) Contains(option string) bool { - for _, s := range o { - if s == option { - return true - } - } - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/CONTRIBUTORS deleted file mode 100644 index b4bb97f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -Paul Borman -bmatsuo -shawnps -theory -jboverfelt -dsymonds -cd1 -wallclockbuilder -dansouza diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/LICENSE deleted file mode 100644 index 5dc6826..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009,2014 Google Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/dce.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/dce.go deleted file mode 100644 index a6479db..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/dce.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2016 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, error) { - uuid, err := NewUUID() - if err == nil { - uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 - uuid[9] = byte(domain) - binary.BigEndian.PutUint32(uuid[0:], id) - } - return uuid, err -} - -// 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, error) { - 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, error) { - return NewDCESecurity(Group, uint32(os.Getgid())) -} - -// Domain returns the domain for a Version 2 UUID. Domains are only defined -// for Version 2 UUIDs. -func (uuid UUID) Domain() Domain { - return Domain(uuid[9]) -} - -// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 -// UUIDs. -func (uuid UUID) ID() uint32 { - return binary.BigEndian.Uint32(uuid[0:4]) -} - -func (d Domain) String() string { - switch d { - case Person: - return "Person" - case Group: - return "Group" - case Org: - return "Org" - } - return fmt.Sprintf("Domain%d", int(d)) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/doc.go deleted file mode 100644 index 5b8a4b9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2016 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 generates and inspects UUIDs. -// -// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security -// Services. -// -// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to -// maps or compared directly. -package uuid diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/hash.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/hash.go deleted file mode 100644 index 4fc5a77..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/hash.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2016 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 namespace IDs and UUIDs -var ( - NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) - Nil UUID // empty UUID, all zeros -) - -// NewHash returns a new UUID derived from the hash of space concatenated with -// data generated by h. The hash should be at least 16 byte in length. The -// first 16 bytes of the hash are used to form the UUID. The version of the -// UUID will be the lower 4 bits of version. NewHash is used to implement -// NewMD5 and NewSHA1. -func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { - h.Reset() - h.Write(space[:]) - h.Write([]byte(data)) - s := h.Sum(nil) - var uuid UUID - 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. It is the same as calling: -// -// 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. It is the same as calling: -// -// NewHash(sha1.New(), space, data, 5) -func NewSHA1(space UUID, data []byte) UUID { - return NewHash(sha1.New(), space, data, 5) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/marshal.go deleted file mode 100644 index 84bbc58..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/marshal.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2016 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 "fmt" - -// MarshalText implements encoding.TextMarshaler. -func (uuid UUID) MarshalText() ([]byte, error) { - var js [36]byte - encodeHex(js[:], uuid) - return js[:], nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (uuid *UUID) UnmarshalText(data []byte) error { - // See comment in ParseBytes why we do this. - // id, err := ParseBytes(data) - id, err := ParseBytes(data) - if err == nil { - *uuid = id - } - return err -} - -// MarshalBinary implements encoding.BinaryMarshaler. -func (uuid UUID) MarshalBinary() ([]byte, error) { - return uuid[:], nil -} - -// UnmarshalBinary implements encoding.BinaryUnmarshaler. -func (uuid *UUID) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) - } - copy(uuid[:], data) - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/node.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/node.go deleted file mode 100644 index 5f0156a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/node.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "net" - "sync" -) - -var ( - nodeMu sync.Mutex - interfaces []net.Interface // cached list of interfaces - ifname string // name of interface being used - nodeID [6]byte // hardware for version 1 UUIDs - zeroID [6]byte // nodeID with only 0's -) - -// NodeInterface returns the name of the interface from which the NodeID was -// derived. The interface "user" is returned if the NodeID was set by -// SetNodeID. -func NodeInterface() string { - defer nodeMu.Unlock() - nodeMu.Lock() - return ifname -} - -// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. -// If name is "" then the first usable interface found will be used or a random -// Node ID will be generated. If a named interface cannot be found then false -// is returned. -// -// SetNodeInterface never fails when name is "". -func SetNodeInterface(name string) bool { - defer nodeMu.Unlock() - nodeMu.Lock() - return setNodeInterface(name) -} - -func setNodeInterface(name string) bool { - if interfaces == nil { - var err error - interfaces, err = net.Interfaces() - if err != nil && name != "" { - return false - } - } - - for _, ifs := range interfaces { - if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { - copy(nodeID[:], 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 == "" { - randomBits(nodeID[:]) - return true - } - return false -} - -// NodeID returns a slice of a copy of the current Node ID, setting the Node ID -// if not already set. -func NodeID() []byte { - defer nodeMu.Unlock() - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - 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 len(id) < 6 { - return false - } - defer nodeMu.Unlock() - nodeMu.Lock() - copy(nodeID[:], id) - ifname = "user" - 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 - } - var node [6]byte - copy(node[:], uuid[10:]) - return node[:] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/sql.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/sql.go deleted file mode 100644 index 528ad0d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/sql.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2016 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 ( - "database/sql/driver" - "fmt" -) - -// Scan implements sql.Scanner so UUIDs can be read from databases transparently -// Currently, database types that map to string and []byte are supported. Please -// consult database-specific driver documentation for matching types. -func (uuid *UUID) Scan(src interface{}) error { - switch src.(type) { - case string: - // if an empty UUID comes from a table, we return a null UUID - if src.(string) == "" { - return nil - } - - // see Parse for required string format - u, err := Parse(src.(string)) - - if err != nil { - return fmt.Errorf("Scan: %v", err) - } - - *uuid = u - case []byte: - b := src.([]byte) - - // if an empty UUID comes from a table, we return a null UUID - if len(b) == 0 { - return nil - } - - // assumes a simple slice of bytes if 16 bytes - // otherwise attempts to parse - if len(b) != 16 { - return uuid.Scan(string(b)) - } - copy((*uuid)[:], b) - - default: - return fmt.Errorf("Scan: unable to scan type %T into UUID", src) - } - - return nil -} - -// Value implements sql.Valuer so that UUIDs can be written to databases -// transparently. Currently, UUIDs map to strings. Please consult -// database-specific driver documentation for matching types. -func (uuid UUID) Value() (driver.Value, error) { - return uuid.String(), nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/time.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/time.go deleted file mode 100644 index fd7fe0a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/time.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "sync" - "time" -) - -// A Time represents a time as the number of 100's of nanoseconds since 15 Oct -// 1582. -type Time int64 - -const ( - lillian = 2299160 // Julian day of 15 Oct 1582 - unix = 2440587 // Julian day of 1 Jan 1970 - epoch = unix - lillian // Days between epochs - g1582 = epoch * 86400 // seconds between epochs - g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs -) - -var ( - timeMu sync.Mutex - lasttime uint64 // last time we returned - clockSeq uint16 // clock sequence for this run - - timeNow = time.Now // for testing -) - -// UnixTime converts t the number of seconds and nanoseconds using the Unix -// epoch of 1 Jan 1970. -func (t Time) UnixTime() (sec, nsec int64) { - sec = int64(t - g1582ns100) - nsec = (sec % 10000000) * 100 - sec /= 10000000 - return sec, nsec -} - -// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and -// clock sequence as well as adjusting the clock sequence as needed. An error -// is returned if the current time cannot be determined. -func GetTime() (Time, uint16, error) { - defer timeMu.Unlock() - timeMu.Lock() - return getTime() -} - -func getTime() (Time, uint16, error) { - t := timeNow() - - // If we don't have a clock sequence already, set one. - if clockSeq == 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 { - clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 - } - lasttime = now - return Time(now), clockSeq, 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 is used, 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) -func ClockSequence() int { - defer timeMu.Unlock() - timeMu.Lock() - return clockSequence() -} - -func clockSequence() int { - if clockSeq == 0 { - setClockSequence(-1) - } - return int(clockSeq & 0x3fff) -} - -// SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to -// -1 causes a new sequence to be generated. -func SetClockSequence(seq int) { - defer timeMu.Unlock() - timeMu.Lock() - setClockSequence(seq) -} - -func setClockSequence(seq int) { - if seq == -1 { - var b [2]byte - randomBits(b[:]) // clock sequence - seq = int(b[0])<<8 | int(b[1]) - } - old_seq := clockSeq - clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant - if old_seq != clockSeq { - lasttime = 0 - } -} - -// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in -// uuid. The time is only defined for version 1 and 2 UUIDs. -func (uuid UUID) Time() Time { - 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) -} - -// ClockSequence returns the clock sequence encoded in uuid. -// The clock sequence is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) ClockSequence() int { - return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/util.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/util.go deleted file mode 100644 index 5ea6c73..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/util.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "io" -) - -// randomBits completely fills slice b with random data. -func randomBits(b []byte) { - if _, err := io.ReadFull(rander, b); err != nil { - panic(err.Error()) // rand should never fail - } -} - -// xvalues returns the value of a byte as a hexadecimal digit or 255. -var xvalues = [256]byte{ - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, -} - -// xtob converts hex characters x1 and x2 into a byte. -func xtob(x1, x2 byte) (byte, bool) { - b1 := xvalues[x1] - b2 := xvalues[x2] - return (b1 << 4) | b2, b1 != 255 && b2 != 255 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/uuid.go deleted file mode 100644 index b7b9ced..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/uuid.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "strings" -) - -// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC -// 4122. -type UUID [16]byte - -// A Version represents a UUID's version. -type Version byte - -// A Variant represents a UUID's 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 - -// Parse decodes s into a UUID or returns an error. 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, error) { - var uuid UUID - if len(s) != 36 { - if len(s) != 36+9 { - return uuid, fmt.Errorf("invalid UUID length: %d", len(s)) - } - if strings.ToLower(s[:9]) != "urn:uuid:" { - return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) - } - s = s[9:] - } - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34} { - if v, ok := xtob(s[x], s[x+1]); !ok { - return uuid, errors.New("invalid UUID format") - } else { - uuid[i] = v - } - } - return uuid, nil -} - -// ParseBytes is like Parse, except it parses a byte slice instead of a string. -func ParseBytes(b []byte) (UUID, error) { - var uuid UUID - if len(b) != 36 { - if len(b) != 36+9 { - return uuid, fmt.Errorf("invalid UUID length: %d", len(b)) - } - if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) { - return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) - } - b = b[9:] - } - if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34} { - if v, ok := xtob(b[x], b[x+1]); !ok { - return uuid, errors.New("invalid UUID format") - } else { - uuid[i] = v - } - } - return uuid, nil -} - -// Must returns uuid if err is nil and panics otherwise. -func Must(uuid UUID, err error) UUID { - if err != nil { - panic(err) - } - return uuid -} - -// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// , or "" if uuid is invalid. -func (uuid UUID) String() string { - var buf [36]byte - encodeHex(buf[:], uuid) - return string(buf[:]) -} - -// URN returns the RFC 2141 URN form of uuid, -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. -func (uuid UUID) URN() string { - var buf [36 + 9]byte - copy(buf[:], "urn:uuid:") - encodeHex(buf[9:], uuid) - return string(buf[:]) -} - -func encodeHex(dst []byte, uuid UUID) { - hex.Encode(dst[:], uuid[:4]) - dst[8] = '-' - hex.Encode(dst[9:13], uuid[4:6]) - dst[13] = '-' - hex.Encode(dst[14:18], uuid[6:8]) - dst[18] = '-' - hex.Encode(dst[19:23], uuid[8:10]) - dst[23] = '-' - hex.Encode(dst[24:], uuid[10:]) -} - -// Variant returns the variant encoded in uuid. -func (uuid UUID) Variant() Variant { - switch { - case (uuid[8] & 0xc0) == 0x80: - return RFC4122 - case (uuid[8] & 0xe0) == 0xc0: - return Microsoft - case (uuid[8] & 0xe0) == 0xe0: - return Future - default: - return Reserved - } -} - -// Version returns the version of uuid. -func (uuid UUID) Version() Version { - return Version(uuid[6] >> 4) -} - -func (v Version) String() string { - if v > 15 { - return fmt.Sprintf("BAD_VERSION_%d", v) - } - return fmt.Sprintf("VERSION_%d", v) -} - -func (v Variant) String() string { - switch v { - case RFC4122: - return "RFC4122" - case Reserved: - return "Reserved" - case Microsoft: - return "Microsoft" - case Future: - return "Future" - case Invalid: - return "Invalid" - } - return fmt.Sprintf("BadVariant%d", int(v)) -} - -// SetRand sets the random number generator to r, which implents io.Reader. -// If r.Read returns an error when the package requests random data then -// a panic will be issued. -// -// Calling SetRand with nil sets the random number generator to the default -// generator. -func SetRand(r io.Reader) { - if r == nil { - rander = rand.Reader - return - } - rander = r -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/version1.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/version1.go deleted file mode 100644 index 22dc07c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/version1.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2016 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 and an error. -// -// In most cases, New should be used. -func NewUUID() (UUID, error) { - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - nodeMu.Unlock() - - var uuid UUID - now, seq, err := GetTime() - if err != nil { - return uuid, err - } - - timeLow := uint32(now & 0xffffffff) - timeMid := uint16((now >> 32) & 0xffff) - timeHi := uint16((now >> 48) & 0x0fff) - timeHi |= 0x1000 // Version 1 - - binary.BigEndian.PutUint32(uuid[0:], timeLow) - binary.BigEndian.PutUint16(uuid[4:], timeMid) - binary.BigEndian.PutUint16(uuid[6:], timeHi) - binary.BigEndian.PutUint16(uuid[8:], seq) - copy(uuid[10:], nodeID[:]) - - return uuid, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/version4.go b/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/version4.go deleted file mode 100644 index 390dd2c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/google/uuid/version4.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2016 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" - -// New is creates a new random UUID or panics. New is equivalent to -// the expression -// -// uuid.Must(uuid.NewRandom()) -func New() UUID { - return Must(NewRandom()) -} - -// NewRandom 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, error) { - var uuid UUID - _, err := io.ReadFull(rander, uuid[:]) - if err != nil { - return Nil, err - } - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return uuid, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/LICENSE deleted file mode 100644 index fbbbc9e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Copyright 2012-2013 Rackspace, 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. - ------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/auth_options.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/auth_options.go deleted file mode 100644 index 5ffa8d1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/auth_options.go +++ /dev/null @@ -1,437 +0,0 @@ -package gophercloud - -/* -AuthOptions stores information needed to authenticate to an OpenStack Cloud. -You can populate one manually, or use a provider's AuthOptionsFromEnv() function -to read relevant information from the standard environment variables. Pass one -to a provider's AuthenticatedClient function to authenticate and obtain a -ProviderClient representing an active session on that provider. - -Its fields are the union of those recognized by each identity implementation and -provider. - -An example of manually providing authentication information: - - opts := gophercloud.AuthOptions{ - IdentityEndpoint: "https://openstack.example.com:5000/v2.0", - Username: "{username}", - Password: "{password}", - TenantID: "{tenant_id}", - } - - provider, err := openstack.AuthenticatedClient(opts) - -An example of using AuthOptionsFromEnv(), where the environment variables can -be read from a file, such as a standard openrc file: - - opts, err := openstack.AuthOptionsFromEnv() - provider, err := openstack.AuthenticatedClient(opts) -*/ -type AuthOptions struct { - // IdentityEndpoint specifies the HTTP endpoint that is required to work with - // the Identity API of the appropriate version. While it's ultimately needed by - // all of the identity services, it will often be populated by a provider-level - // function. - // - // The IdentityEndpoint is typically referred to as the "auth_url" or - // "OS_AUTH_URL" in the information provided by the cloud operator. - IdentityEndpoint string `json:"-"` - - // Username is required if using Identity V2 API. Consult with your provider's - // control panel to discover your account's username. In Identity V3, either - // UserID or a combination of Username and DomainID or DomainName are needed. - Username string `json:"username,omitempty"` - UserID string `json:"-"` - - Password string `json:"password,omitempty"` - - // At most one of DomainID and DomainName must be provided if using Username - // with Identity V3. Otherwise, either are optional. - DomainID string `json:"-"` - DomainName string `json:"name,omitempty"` - - // The TenantID and TenantName fields are optional for the Identity V2 API. - // The same fields are known as project_id and project_name in the Identity - // V3 API, but are collected as TenantID and TenantName here in both cases. - // Some providers allow you to specify a TenantName instead of the TenantId. - // Some require both. Your provider's authentication policies will determine - // how these fields influence authentication. - // If DomainID or DomainName are provided, they will also apply to TenantName. - // It is not currently possible to authenticate with Username and a Domain - // and scope to a Project in a different Domain by using TenantName. To - // accomplish that, the ProjectID will need to be provided as the TenantID - // option. - TenantID string `json:"tenantId,omitempty"` - TenantName string `json:"tenantName,omitempty"` - - // AllowReauth should be set to true if you grant permission for Gophercloud to - // cache your credentials in memory, and to allow Gophercloud to attempt to - // re-authenticate automatically if/when your token expires. If you set it to - // false, it will not cache these settings, but re-authentication will not be - // possible. This setting defaults to false. - // - // NOTE: The reauth function will try to re-authenticate endlessly if left - // unchecked. The way to limit the number of attempts is to provide a custom - // HTTP client to the provider client and provide a transport that implements - // the RoundTripper interface and stores the number of failed retries. For an - // example of this, see here: - // https://github.com/rackspace/rack/blob/1.0.0/auth/clients.go#L311 - AllowReauth bool `json:"-"` - - // TokenID allows users to authenticate (possibly as another user) with an - // authentication token ID. - TokenID string `json:"-"` - - // Scope determines the scoping of the authentication request. - Scope *AuthScope `json:"-"` - - // Authentication through Application Credentials requires supplying name, project and secret - // For project we can use TenantID - ApplicationCredentialID string `json:"-"` - ApplicationCredentialName string `json:"-"` - ApplicationCredentialSecret string `json:"-"` -} - -// AuthScope allows a created token to be limited to a specific domain or project. -type AuthScope struct { - ProjectID string - ProjectName string - DomainID string - DomainName string -} - -// ToTokenV2CreateMap allows AuthOptions to satisfy the AuthOptionsBuilder -// interface in the v2 tokens package -func (opts AuthOptions) ToTokenV2CreateMap() (map[string]interface{}, error) { - // Populate the request map. - authMap := make(map[string]interface{}) - - if opts.Username != "" { - if opts.Password != "" { - authMap["passwordCredentials"] = map[string]interface{}{ - "username": opts.Username, - "password": opts.Password, - } - } else { - return nil, ErrMissingInput{Argument: "Password"} - } - } else if opts.TokenID != "" { - authMap["token"] = map[string]interface{}{ - "id": opts.TokenID, - } - } else { - return nil, ErrMissingInput{Argument: "Username"} - } - - if opts.TenantID != "" { - authMap["tenantId"] = opts.TenantID - } - if opts.TenantName != "" { - authMap["tenantName"] = opts.TenantName - } - - return map[string]interface{}{"auth": authMap}, nil -} - -func (opts *AuthOptions) ToTokenV3CreateMap(scope map[string]interface{}) (map[string]interface{}, error) { - type domainReq struct { - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - } - - type projectReq struct { - Domain *domainReq `json:"domain,omitempty"` - Name *string `json:"name,omitempty"` - ID *string `json:"id,omitempty"` - } - - type userReq struct { - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Password string `json:"password,omitempty"` - Domain *domainReq `json:"domain,omitempty"` - } - - type passwordReq struct { - User userReq `json:"user"` - } - - type tokenReq struct { - ID string `json:"id"` - } - - type applicationCredentialReq struct { - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - User *userReq `json:"user,omitempty"` - Secret *string `json:"secret,omitempty"` - } - - type identityReq struct { - Methods []string `json:"methods"` - Password *passwordReq `json:"password,omitempty"` - Token *tokenReq `json:"token,omitempty"` - ApplicationCredential *applicationCredentialReq `json:"application_credential,omitempty"` - } - - type authReq struct { - Identity identityReq `json:"identity"` - } - - type request struct { - Auth authReq `json:"auth"` - } - - // Populate the request structure based on the provided arguments. Create and return an error - // if insufficient or incompatible information is present. - var req request - - if opts.Password == "" { - if opts.TokenID != "" { - // Because we aren't using password authentication, it's an error to also provide any of the user-based authentication - // parameters. - if opts.Username != "" { - return nil, ErrUsernameWithToken{} - } - if opts.UserID != "" { - return nil, ErrUserIDWithToken{} - } - if opts.DomainID != "" { - return nil, ErrDomainIDWithToken{} - } - if opts.DomainName != "" { - return nil, ErrDomainNameWithToken{} - } - - // Configure the request for Token authentication. - req.Auth.Identity.Methods = []string{"token"} - req.Auth.Identity.Token = &tokenReq{ - ID: opts.TokenID, - } - - } else if opts.ApplicationCredentialID != "" { - // Configure the request for ApplicationCredentialID authentication. - // https://github.com/openstack/keystoneauth/blob/stable/rocky/keystoneauth1/identity/v3/application_credential.py#L48-L67 - // There are three kinds of possible application_credential requests - // 1. application_credential id + secret - // 2. application_credential name + secret + user_id - // 3. application_credential name + secret + username + domain_id / domain_name - if opts.ApplicationCredentialSecret == "" { - return nil, ErrAppCredMissingSecret{} - } - req.Auth.Identity.Methods = []string{"application_credential"} - req.Auth.Identity.ApplicationCredential = &applicationCredentialReq{ - ID: &opts.ApplicationCredentialID, - Secret: &opts.ApplicationCredentialSecret, - } - } else if opts.ApplicationCredentialName != "" { - if opts.ApplicationCredentialSecret == "" { - return nil, ErrAppCredMissingSecret{} - } - - var userRequest *userReq - - if opts.UserID != "" { - // UserID could be used without the domain information - userRequest = &userReq{ - ID: &opts.UserID, - } - } - - if userRequest == nil && opts.Username == "" { - // Make sure that Username or UserID are provided - return nil, ErrUsernameOrUserID{} - } - - if userRequest == nil && opts.DomainID != "" { - userRequest = &userReq{ - Name: &opts.Username, - Domain: &domainReq{ID: &opts.DomainID}, - } - } - - if userRequest == nil && opts.DomainName != "" { - userRequest = &userReq{ - Name: &opts.Username, - Domain: &domainReq{Name: &opts.DomainName}, - } - } - - // Make sure that DomainID or DomainName are provided among Username - if userRequest == nil { - return nil, ErrDomainIDOrDomainName{} - } - - req.Auth.Identity.Methods = []string{"application_credential"} - req.Auth.Identity.ApplicationCredential = &applicationCredentialReq{ - Name: &opts.ApplicationCredentialName, - User: userRequest, - Secret: &opts.ApplicationCredentialSecret, - } - } else { - // If no password or token ID or ApplicationCredential are available, authentication can't continue. - return nil, ErrMissingPassword{} - } - } else { - // Password authentication. - req.Auth.Identity.Methods = []string{"password"} - - // At least one of Username and UserID must be specified. - if opts.Username == "" && opts.UserID == "" { - return nil, ErrUsernameOrUserID{} - } - - if opts.Username != "" { - // If Username is provided, UserID may not be provided. - if opts.UserID != "" { - return nil, ErrUsernameOrUserID{} - } - - // Either DomainID or DomainName must also be specified. - if opts.DomainID == "" && opts.DomainName == "" { - return nil, ErrDomainIDOrDomainName{} - } - - if opts.DomainID != "" { - if opts.DomainName != "" { - return nil, ErrDomainIDOrDomainName{} - } - - // Configure the request for Username and Password authentication with a DomainID. - req.Auth.Identity.Password = &passwordReq{ - User: userReq{ - Name: &opts.Username, - Password: opts.Password, - Domain: &domainReq{ID: &opts.DomainID}, - }, - } - } - - if opts.DomainName != "" { - // Configure the request for Username and Password authentication with a DomainName. - req.Auth.Identity.Password = &passwordReq{ - User: userReq{ - Name: &opts.Username, - Password: opts.Password, - Domain: &domainReq{Name: &opts.DomainName}, - }, - } - } - } - - if opts.UserID != "" { - // If UserID is specified, neither DomainID nor DomainName may be. - if opts.DomainID != "" { - return nil, ErrDomainIDWithUserID{} - } - if opts.DomainName != "" { - return nil, ErrDomainNameWithUserID{} - } - - // Configure the request for UserID and Password authentication. - req.Auth.Identity.Password = &passwordReq{ - User: userReq{ID: &opts.UserID, Password: opts.Password}, - } - } - } - - b, err := BuildRequestBody(req, "") - if err != nil { - return nil, err - } - - if len(scope) != 0 { - b["auth"].(map[string]interface{})["scope"] = scope - } - - return b, nil -} - -func (opts *AuthOptions) ToTokenV3ScopeMap() (map[string]interface{}, error) { - // For backwards compatibility. - // If AuthOptions.Scope was not set, try to determine it. - // This works well for common scenarios. - if opts.Scope == nil { - opts.Scope = new(AuthScope) - if opts.TenantID != "" { - opts.Scope.ProjectID = opts.TenantID - } else { - if opts.TenantName != "" { - opts.Scope.ProjectName = opts.TenantName - opts.Scope.DomainID = opts.DomainID - opts.Scope.DomainName = opts.DomainName - } - } - } - - if opts.Scope.ProjectName != "" { - // ProjectName provided: either DomainID or DomainName must also be supplied. - // ProjectID may not be supplied. - if opts.Scope.DomainID == "" && opts.Scope.DomainName == "" { - return nil, ErrScopeDomainIDOrDomainName{} - } - if opts.Scope.ProjectID != "" { - return nil, ErrScopeProjectIDOrProjectName{} - } - - if opts.Scope.DomainID != "" { - // ProjectName + DomainID - return map[string]interface{}{ - "project": map[string]interface{}{ - "name": &opts.Scope.ProjectName, - "domain": map[string]interface{}{"id": &opts.Scope.DomainID}, - }, - }, nil - } - - if opts.Scope.DomainName != "" { - // ProjectName + DomainName - return map[string]interface{}{ - "project": map[string]interface{}{ - "name": &opts.Scope.ProjectName, - "domain": map[string]interface{}{"name": &opts.Scope.DomainName}, - }, - }, nil - } - } else if opts.Scope.ProjectID != "" { - // ProjectID provided. ProjectName, DomainID, and DomainName may not be provided. - if opts.Scope.DomainID != "" { - return nil, ErrScopeProjectIDAlone{} - } - if opts.Scope.DomainName != "" { - return nil, ErrScopeProjectIDAlone{} - } - - // ProjectID - return map[string]interface{}{ - "project": map[string]interface{}{ - "id": &opts.Scope.ProjectID, - }, - }, nil - } else if opts.Scope.DomainID != "" { - // DomainID provided. ProjectID, ProjectName, and DomainName may not be provided. - if opts.Scope.DomainName != "" { - return nil, ErrScopeDomainIDOrDomainName{} - } - - // DomainID - return map[string]interface{}{ - "domain": map[string]interface{}{ - "id": &opts.Scope.DomainID, - }, - }, nil - } else if opts.Scope.DomainName != "" { - // DomainName - return map[string]interface{}{ - "domain": map[string]interface{}{ - "name": &opts.Scope.DomainName, - }, - }, nil - } - - return nil, nil -} - -func (opts AuthOptions) CanReauth() bool { - return opts.AllowReauth -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/doc.go deleted file mode 100644 index 131cc8e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/doc.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Package gophercloud provides a multi-vendor interface to OpenStack-compatible -clouds. The library has a three-level hierarchy: providers, services, and -resources. - -Authenticating with Providers - -Provider structs represent the cloud providers that offer and manage a -collection of services. You will generally want to create one Provider -client per OpenStack cloud. - -Use your OpenStack credentials to create a Provider client. The -IdentityEndpoint is typically refered to as "auth_url" or "OS_AUTH_URL" in -information provided by the cloud operator. Additionally, the cloud may refer to -TenantID or TenantName as project_id and project_name. Credentials are -specified like so: - - opts := gophercloud.AuthOptions{ - IdentityEndpoint: "https://openstack.example.com:5000/v2.0", - Username: "{username}", - Password: "{password}", - TenantID: "{tenant_id}", - } - - provider, err := openstack.AuthenticatedClient(opts) - -You may also use the openstack.AuthOptionsFromEnv() helper function. This -function reads in standard environment variables frequently found in an -OpenStack `openrc` file. Again note that Gophercloud currently uses "tenant" -instead of "project". - - opts, err := openstack.AuthOptionsFromEnv() - provider, err := openstack.AuthenticatedClient(opts) - -Service Clients - -Service structs are specific to a provider and handle all of the logic and -operations for a particular OpenStack service. Examples of services include: -Compute, Object Storage, Block Storage. In order to define one, you need to -pass in the parent provider, like so: - - opts := gophercloud.EndpointOpts{Region: "RegionOne"} - - client, err := openstack.NewComputeV2(provider, opts) - -Resources - -Resource structs are the domain models that services make use of in order -to work with and represent the state of API resources: - - server, err := servers.Get(client, "{serverId}").Extract() - -Intermediate Result structs are returned for API operations, which allow -generic access to the HTTP headers, response body, and any errors associated -with the network transaction. To turn a result into a usable resource struct, -you must call the Extract method which is chained to the response, or an -Extract function from an applicable extension: - - result := servers.Get(client, "{serverId}") - - // Attempt to extract the disk configuration from the OS-DCF disk config - // extension: - config, err := diskconfig.ExtractGet(result) - -All requests that enumerate a collection return a Pager struct that is used to -iterate through the results one page at a time. Use the EachPage method on that -Pager to handle each successive Page in a closure, then use the appropriate -extraction method from that request's package to interpret that Page as a slice -of results: - - err := servers.List(client, nil).EachPage(func (page pagination.Page) (bool, error) { - s, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - - // Handle the []servers.Server slice. - - // Return "false" or an error to prematurely stop fetching new pages. - return true, nil - }) - -If you want to obtain the entire collection of pages without doing any -intermediary processing on each page, you can use the AllPages method: - - allPages, err := servers.List(client, nil).AllPages() - allServers, err := servers.ExtractServers(allPages) - -This top-level package contains utility functions and data types that are used -throughout the provider and service packages. Of particular note for end users -are the AuthOptions and EndpointOpts structs. -*/ -package gophercloud diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/endpoint_search.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/endpoint_search.go deleted file mode 100644 index 2fbc3c9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/endpoint_search.go +++ /dev/null @@ -1,76 +0,0 @@ -package gophercloud - -// Availability indicates to whom a specific service endpoint is accessible: -// the internet at large, internal networks only, or only to administrators. -// Different identity services use different terminology for these. Identity v2 -// lists them as different kinds of URLs within the service catalog ("adminURL", -// "internalURL", and "publicURL"), while v3 lists them as "Interfaces" in an -// endpoint's response. -type Availability string - -const ( - // AvailabilityAdmin indicates that an endpoint is only available to - // administrators. - AvailabilityAdmin Availability = "admin" - - // AvailabilityPublic indicates that an endpoint is available to everyone on - // the internet. - AvailabilityPublic Availability = "public" - - // AvailabilityInternal indicates that an endpoint is only available within - // the cluster's internal network. - AvailabilityInternal Availability = "internal" -) - -// EndpointOpts specifies search criteria used by queries against an -// OpenStack service catalog. The options must contain enough information to -// unambiguously identify one, and only one, endpoint within the catalog. -// -// Usually, these are passed to service client factory functions in a provider -// package, like "openstack.NewComputeV2()". -type EndpointOpts struct { - // Type [required] is the service type for the client (e.g., "compute", - // "object-store"). Generally, this will be supplied by the service client - // function, but a user-given value will be honored if provided. - Type string - - // Name [optional] is the service name for the client (e.g., "nova") as it - // appears in the service catalog. Services can have the same Type but a - // different Name, which is why both Type and Name are sometimes needed. - Name string - - // Region [required] is the geographic region in which the endpoint resides, - // generally specifying which datacenter should house your resources. - // Required only for services that span multiple regions. - Region string - - // Availability [optional] is the visibility of the endpoint to be returned. - // Valid types include the constants AvailabilityPublic, AvailabilityInternal, - // or AvailabilityAdmin from this package. - // - // Availability is not required, and defaults to AvailabilityPublic. Not all - // providers or services offer all Availability options. - Availability Availability -} - -/* -EndpointLocator is an internal function to be used by provider implementations. - -It provides an implementation that locates a single endpoint from a service -catalog for a specific ProviderClient based on user-provided EndpointOpts. The -provider then uses it to discover related ServiceClients. -*/ -type EndpointLocator func(EndpointOpts) (string, error) - -// ApplyDefaults is an internal method to be used by provider implementations. -// -// It sets EndpointOpts fields if not already set, including a default type. -// Currently, EndpointOpts.Availability defaults to the public endpoint. -func (eo *EndpointOpts) ApplyDefaults(t string) { - if eo.Type == "" { - eo.Type = t - } - if eo.Availability == "" { - eo.Availability = AvailabilityPublic - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/errors.go deleted file mode 100644 index 4bf1024..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/errors.go +++ /dev/null @@ -1,460 +0,0 @@ -package gophercloud - -import ( - "fmt" - "strings" -) - -// BaseError is an error type that all other error types embed. -type BaseError struct { - DefaultErrString string - Info string -} - -func (e BaseError) Error() string { - e.DefaultErrString = "An error occurred while executing a Gophercloud request." - return e.choseErrString() -} - -func (e BaseError) choseErrString() string { - if e.Info != "" { - return e.Info - } - return e.DefaultErrString -} - -// ErrMissingInput is the error when input is required in a particular -// situation but not provided by the user -type ErrMissingInput struct { - BaseError - Argument string -} - -func (e ErrMissingInput) Error() string { - e.DefaultErrString = fmt.Sprintf("Missing input for argument [%s]", e.Argument) - return e.choseErrString() -} - -// ErrInvalidInput is an error type used for most non-HTTP Gophercloud errors. -type ErrInvalidInput struct { - ErrMissingInput - Value interface{} -} - -func (e ErrInvalidInput) Error() string { - e.DefaultErrString = fmt.Sprintf("Invalid input provided for argument [%s]: [%+v]", e.Argument, e.Value) - return e.choseErrString() -} - -// ErrMissingEnvironmentVariable is the error when environment variable is required -// in a particular situation but not provided by the user -type ErrMissingEnvironmentVariable struct { - BaseError - EnvironmentVariable string -} - -func (e ErrMissingEnvironmentVariable) Error() string { - e.DefaultErrString = fmt.Sprintf("Missing environment variable [%s]", e.EnvironmentVariable) - return e.choseErrString() -} - -// ErrMissingAnyoneOfEnvironmentVariables is the error when anyone of the environment variables -// is required in a particular situation but not provided by the user -type ErrMissingAnyoneOfEnvironmentVariables struct { - BaseError - EnvironmentVariables []string -} - -func (e ErrMissingAnyoneOfEnvironmentVariables) Error() string { - e.DefaultErrString = fmt.Sprintf( - "Missing one of the following environment variables [%s]", - strings.Join(e.EnvironmentVariables, ", "), - ) - return e.choseErrString() -} - -// ErrUnexpectedResponseCode is returned by the Request method when a response code other than -// those listed in OkCodes is encountered. -type ErrUnexpectedResponseCode struct { - BaseError - URL string - Method string - Expected []int - Actual int - Body []byte -} - -func (e ErrUnexpectedResponseCode) Error() string { - e.DefaultErrString = fmt.Sprintf( - "Expected HTTP response code %v when accessing [%s %s], but got %d instead\n%s", - e.Expected, e.Method, e.URL, e.Actual, e.Body, - ) - return e.choseErrString() -} - -// ErrDefault400 is the default error type returned on a 400 HTTP response code. -type ErrDefault400 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault401 is the default error type returned on a 401 HTTP response code. -type ErrDefault401 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault403 is the default error type returned on a 403 HTTP response code. -type ErrDefault403 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault404 is the default error type returned on a 404 HTTP response code. -type ErrDefault404 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault405 is the default error type returned on a 405 HTTP response code. -type ErrDefault405 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault408 is the default error type returned on a 408 HTTP response code. -type ErrDefault408 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault429 is the default error type returned on a 429 HTTP response code. -type ErrDefault429 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault500 is the default error type returned on a 500 HTTP response code. -type ErrDefault500 struct { - ErrUnexpectedResponseCode -} - -// ErrDefault503 is the default error type returned on a 503 HTTP response code. -type ErrDefault503 struct { - ErrUnexpectedResponseCode -} - -func (e ErrDefault400) Error() string { - e.DefaultErrString = fmt.Sprintf( - "Bad request with: [%s %s], error message: %s", - e.Method, e.URL, e.Body, - ) - return e.choseErrString() -} -func (e ErrDefault401) Error() string { - return "Authentication failed" -} -func (e ErrDefault403) Error() string { - e.DefaultErrString = fmt.Sprintf( - "Request forbidden: [%s %s], error message: %s", - e.Method, e.URL, e.Body, - ) - return e.choseErrString() -} -func (e ErrDefault404) Error() string { - return "Resource not found" -} -func (e ErrDefault405) Error() string { - return "Method not allowed" -} -func (e ErrDefault408) Error() string { - return "The server timed out waiting for the request" -} -func (e ErrDefault429) Error() string { - return "Too many requests have been sent in a given amount of time. Pause" + - " requests, wait up to one minute, and try again." -} -func (e ErrDefault500) Error() string { - return "Internal Server Error" -} -func (e ErrDefault503) Error() string { - return "The service is currently unable to handle the request due to a temporary" + - " overloading or maintenance. This is a temporary condition. Try again later." -} - -// Err400er is the interface resource error types implement to override the error message -// from a 400 error. -type Err400er interface { - Error400(ErrUnexpectedResponseCode) error -} - -// Err401er is the interface resource error types implement to override the error message -// from a 401 error. -type Err401er interface { - Error401(ErrUnexpectedResponseCode) error -} - -// Err403er is the interface resource error types implement to override the error message -// from a 403 error. -type Err403er interface { - Error403(ErrUnexpectedResponseCode) error -} - -// Err404er is the interface resource error types implement to override the error message -// from a 404 error. -type Err404er interface { - Error404(ErrUnexpectedResponseCode) error -} - -// Err405er is the interface resource error types implement to override the error message -// from a 405 error. -type Err405er interface { - Error405(ErrUnexpectedResponseCode) error -} - -// Err408er is the interface resource error types implement to override the error message -// from a 408 error. -type Err408er interface { - Error408(ErrUnexpectedResponseCode) error -} - -// Err429er is the interface resource error types implement to override the error message -// from a 429 error. -type Err429er interface { - Error429(ErrUnexpectedResponseCode) error -} - -// Err500er is the interface resource error types implement to override the error message -// from a 500 error. -type Err500er interface { - Error500(ErrUnexpectedResponseCode) error -} - -// Err503er is the interface resource error types implement to override the error message -// from a 503 error. -type Err503er interface { - Error503(ErrUnexpectedResponseCode) error -} - -// ErrTimeOut is the error type returned when an operations times out. -type ErrTimeOut struct { - BaseError -} - -func (e ErrTimeOut) Error() string { - e.DefaultErrString = "A time out occurred" - return e.choseErrString() -} - -// ErrUnableToReauthenticate is the error type returned when reauthentication fails. -type ErrUnableToReauthenticate struct { - BaseError - ErrOriginal error -} - -func (e ErrUnableToReauthenticate) Error() string { - e.DefaultErrString = fmt.Sprintf("Unable to re-authenticate: %s", e.ErrOriginal) - return e.choseErrString() -} - -// ErrErrorAfterReauthentication is the error type returned when reauthentication -// succeeds, but an error occurs afterword (usually an HTTP error). -type ErrErrorAfterReauthentication struct { - BaseError - ErrOriginal error -} - -func (e ErrErrorAfterReauthentication) Error() string { - e.DefaultErrString = fmt.Sprintf("Successfully re-authenticated, but got error executing request: %s", e.ErrOriginal) - return e.choseErrString() -} - -// ErrServiceNotFound is returned when no service in a service catalog matches -// the provided EndpointOpts. This is generally returned by provider service -// factory methods like "NewComputeV2()" and can mean that a service is not -// enabled for your account. -type ErrServiceNotFound struct { - BaseError -} - -func (e ErrServiceNotFound) Error() string { - e.DefaultErrString = "No suitable service could be found in the service catalog." - return e.choseErrString() -} - -// ErrEndpointNotFound is returned when no available endpoints match the -// provided EndpointOpts. This is also generally returned by provider service -// factory methods, and usually indicates that a region was specified -// incorrectly. -type ErrEndpointNotFound struct { - BaseError -} - -func (e ErrEndpointNotFound) Error() string { - e.DefaultErrString = "No suitable endpoint could be found in the service catalog." - return e.choseErrString() -} - -// ErrResourceNotFound is the error when trying to retrieve a resource's -// ID by name and the resource doesn't exist. -type ErrResourceNotFound struct { - BaseError - Name string - ResourceType string -} - -func (e ErrResourceNotFound) Error() string { - e.DefaultErrString = fmt.Sprintf("Unable to find %s with name %s", e.ResourceType, e.Name) - return e.choseErrString() -} - -// ErrMultipleResourcesFound is the error when trying to retrieve a resource's -// ID by name and multiple resources have the user-provided name. -type ErrMultipleResourcesFound struct { - BaseError - Name string - Count int - ResourceType string -} - -func (e ErrMultipleResourcesFound) Error() string { - e.DefaultErrString = fmt.Sprintf("Found %d %ss matching %s", e.Count, e.ResourceType, e.Name) - return e.choseErrString() -} - -// ErrUnexpectedType is the error when an unexpected type is encountered -type ErrUnexpectedType struct { - BaseError - Expected string - Actual string -} - -func (e ErrUnexpectedType) Error() string { - e.DefaultErrString = fmt.Sprintf("Expected %s but got %s", e.Expected, e.Actual) - return e.choseErrString() -} - -func unacceptedAttributeErr(attribute string) string { - return fmt.Sprintf("The base Identity V3 API does not accept authentication by %s", attribute) -} - -func redundantWithTokenErr(attribute string) string { - return fmt.Sprintf("%s may not be provided when authenticating with a TokenID", attribute) -} - -func redundantWithUserID(attribute string) string { - return fmt.Sprintf("%s may not be provided when authenticating with a UserID", attribute) -} - -// ErrAPIKeyProvided indicates that an APIKey was provided but can't be used. -type ErrAPIKeyProvided struct{ BaseError } - -func (e ErrAPIKeyProvided) Error() string { - return unacceptedAttributeErr("APIKey") -} - -// ErrTenantIDProvided indicates that a TenantID was provided but can't be used. -type ErrTenantIDProvided struct{ BaseError } - -func (e ErrTenantIDProvided) Error() string { - return unacceptedAttributeErr("TenantID") -} - -// ErrTenantNameProvided indicates that a TenantName was provided but can't be used. -type ErrTenantNameProvided struct{ BaseError } - -func (e ErrTenantNameProvided) Error() string { - return unacceptedAttributeErr("TenantName") -} - -// ErrUsernameWithToken indicates that a Username was provided, but token authentication is being used instead. -type ErrUsernameWithToken struct{ BaseError } - -func (e ErrUsernameWithToken) Error() string { - return redundantWithTokenErr("Username") -} - -// ErrUserIDWithToken indicates that a UserID was provided, but token authentication is being used instead. -type ErrUserIDWithToken struct{ BaseError } - -func (e ErrUserIDWithToken) Error() string { - return redundantWithTokenErr("UserID") -} - -// ErrDomainIDWithToken indicates that a DomainID was provided, but token authentication is being used instead. -type ErrDomainIDWithToken struct{ BaseError } - -func (e ErrDomainIDWithToken) Error() string { - return redundantWithTokenErr("DomainID") -} - -// ErrDomainNameWithToken indicates that a DomainName was provided, but token authentication is being used instead.s -type ErrDomainNameWithToken struct{ BaseError } - -func (e ErrDomainNameWithToken) Error() string { - return redundantWithTokenErr("DomainName") -} - -// ErrUsernameOrUserID indicates that neither username nor userID are specified, or both are at once. -type ErrUsernameOrUserID struct{ BaseError } - -func (e ErrUsernameOrUserID) Error() string { - return "Exactly one of Username and UserID must be provided for password authentication" -} - -// ErrDomainIDWithUserID indicates that a DomainID was provided, but unnecessary because a UserID is being used. -type ErrDomainIDWithUserID struct{ BaseError } - -func (e ErrDomainIDWithUserID) Error() string { - return redundantWithUserID("DomainID") -} - -// ErrDomainNameWithUserID indicates that a DomainName was provided, but unnecessary because a UserID is being used. -type ErrDomainNameWithUserID struct{ BaseError } - -func (e ErrDomainNameWithUserID) Error() string { - return redundantWithUserID("DomainName") -} - -// ErrDomainIDOrDomainName indicates that a username was provided, but no domain to scope it. -// It may also indicate that both a DomainID and a DomainName were provided at once. -type ErrDomainIDOrDomainName struct{ BaseError } - -func (e ErrDomainIDOrDomainName) Error() string { - return "You must provide exactly one of DomainID or DomainName to authenticate by Username" -} - -// ErrMissingPassword indicates that no password was provided and no token is available. -type ErrMissingPassword struct{ BaseError } - -func (e ErrMissingPassword) Error() string { - return "You must provide a password to authenticate" -} - -// ErrScopeDomainIDOrDomainName indicates that a domain ID or Name was required in a Scope, but not present. -type ErrScopeDomainIDOrDomainName struct{ BaseError } - -func (e ErrScopeDomainIDOrDomainName) Error() string { - return "You must provide exactly one of DomainID or DomainName in a Scope with ProjectName" -} - -// ErrScopeProjectIDOrProjectName indicates that both a ProjectID and a ProjectName were provided in a Scope. -type ErrScopeProjectIDOrProjectName struct{ BaseError } - -func (e ErrScopeProjectIDOrProjectName) Error() string { - return "You must provide at most one of ProjectID or ProjectName in a Scope" -} - -// ErrScopeProjectIDAlone indicates that a ProjectID was provided with other constraints in a Scope. -type ErrScopeProjectIDAlone struct{ BaseError } - -func (e ErrScopeProjectIDAlone) Error() string { - return "ProjectID must be supplied alone in a Scope" -} - -// ErrScopeEmpty indicates that no credentials were provided in a Scope. -type ErrScopeEmpty struct{ BaseError } - -func (e ErrScopeEmpty) Error() string { - return "You must provide either a Project or Domain in a Scope" -} - -// ErrAppCredMissingSecret indicates that no Application Credential Secret was provided with Application Credential ID or Name -type ErrAppCredMissingSecret struct{ BaseError } - -func (e ErrAppCredMissingSecret) Error() string { - return "You must provide an Application Credential Secret" -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go deleted file mode 100644 index 0bb1f48..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go +++ /dev/null @@ -1,114 +0,0 @@ -package openstack - -import ( - "os" - - "github.com/gophercloud/gophercloud" -) - -var nilOptions = gophercloud.AuthOptions{} - -/* -AuthOptionsFromEnv fills out an identity.AuthOptions structure with the -settings found on the various OpenStack OS_* environment variables. - -The following variables provide sources of truth: OS_AUTH_URL, OS_USERNAME, -OS_PASSWORD, OS_TENANT_ID, and OS_TENANT_NAME. - -Of these, OS_USERNAME, OS_PASSWORD, and OS_AUTH_URL must have settings, -or an error will result. OS_TENANT_ID, OS_TENANT_NAME, OS_PROJECT_ID, and -OS_PROJECT_NAME are optional. - -OS_TENANT_ID and OS_TENANT_NAME are mutually exclusive to OS_PROJECT_ID and -OS_PROJECT_NAME. If OS_PROJECT_ID and OS_PROJECT_NAME are set, they will -still be referred as "tenant" in Gophercloud. - -To use this function, first set the OS_* environment variables (for example, -by sourcing an `openrc` file), then: - - opts, err := openstack.AuthOptionsFromEnv() - provider, err := openstack.AuthenticatedClient(opts) -*/ -func AuthOptionsFromEnv() (gophercloud.AuthOptions, error) { - authURL := os.Getenv("OS_AUTH_URL") - username := os.Getenv("OS_USERNAME") - userID := os.Getenv("OS_USERID") - password := os.Getenv("OS_PASSWORD") - tenantID := os.Getenv("OS_TENANT_ID") - tenantName := os.Getenv("OS_TENANT_NAME") - domainID := os.Getenv("OS_DOMAIN_ID") - domainName := os.Getenv("OS_DOMAIN_NAME") - applicationCredentialID := os.Getenv("OS_APPLICATION_CREDENTIAL_ID") - applicationCredentialName := os.Getenv("OS_APPLICATION_CREDENTIAL_NAME") - applicationCredentialSecret := os.Getenv("OS_APPLICATION_CREDENTIAL_SECRET") - - // If OS_PROJECT_ID is set, overwrite tenantID with the value. - if v := os.Getenv("OS_PROJECT_ID"); v != "" { - tenantID = v - } - - // If OS_PROJECT_NAME is set, overwrite tenantName with the value. - if v := os.Getenv("OS_PROJECT_NAME"); v != "" { - tenantName = v - } - - if authURL == "" { - err := gophercloud.ErrMissingEnvironmentVariable{ - EnvironmentVariable: "OS_AUTH_URL", - } - return nilOptions, err - } - - if userID == "" && username == "" { - // Empty username and userID could be ignored, when applicationCredentialID and applicationCredentialSecret are set - if applicationCredentialID == "" && applicationCredentialSecret == "" { - err := gophercloud.ErrMissingAnyoneOfEnvironmentVariables{ - EnvironmentVariables: []string{"OS_USERID", "OS_USERNAME"}, - } - return nilOptions, err - } - } - - if password == "" && applicationCredentialID == "" && applicationCredentialName == "" { - err := gophercloud.ErrMissingEnvironmentVariable{ - EnvironmentVariable: "OS_PASSWORD", - } - return nilOptions, err - } - - if (applicationCredentialID != "" || applicationCredentialName != "") && applicationCredentialSecret == "" { - err := gophercloud.ErrMissingEnvironmentVariable{ - EnvironmentVariable: "OS_APPLICATION_CREDENTIAL_SECRET", - } - return nilOptions, err - } - - if applicationCredentialID == "" && applicationCredentialName != "" && applicationCredentialSecret != "" { - if userID == "" && username == "" { - return nilOptions, gophercloud.ErrMissingAnyoneOfEnvironmentVariables{ - EnvironmentVariables: []string{"OS_USERID", "OS_USERNAME"}, - } - } - if username != "" && domainID == "" && domainName == "" { - return nilOptions, gophercloud.ErrMissingAnyoneOfEnvironmentVariables{ - EnvironmentVariables: []string{"OS_DOMAIN_ID", "OS_DOMAIN_NAME"}, - } - } - } - - ao := gophercloud.AuthOptions{ - IdentityEndpoint: authURL, - UserID: userID, - Username: username, - Password: password, - TenantID: tenantID, - TenantName: tenantName, - DomainID: domainID, - DomainName: domainName, - ApplicationCredentialID: applicationCredentialID, - ApplicationCredentialName: applicationCredentialName, - ApplicationCredentialSecret: applicationCredentialSecret, - } - - return ao, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/client.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/client.go deleted file mode 100644 index 2cef3f0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/client.go +++ /dev/null @@ -1,429 +0,0 @@ -package openstack - -import ( - "fmt" - "reflect" - - "github.com/gophercloud/gophercloud" - tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens" - tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens" - "github.com/gophercloud/gophercloud/openstack/utils" -) - -const ( - // v2 represents Keystone v2. - // It should never increase beyond 2.0. - v2 = "v2.0" - - // v3 represents Keystone v3. - // The version can be anything from v3 to v3.x. - v3 = "v3" -) - -/* -NewClient prepares an unauthenticated ProviderClient instance. -Most users will probably prefer using the AuthenticatedClient function -instead. - -This is useful if you wish to explicitly control the version of the identity -service that's used for authentication explicitly, for example. - -A basic example of using this would be: - - ao, err := openstack.AuthOptionsFromEnv() - provider, err := openstack.NewClient(ao.IdentityEndpoint) - client, err := openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}) -*/ -func NewClient(endpoint string) (*gophercloud.ProviderClient, error) { - base, err := utils.BaseEndpoint(endpoint) - if err != nil { - return nil, err - } - - endpoint = gophercloud.NormalizeURL(endpoint) - base = gophercloud.NormalizeURL(base) - - p := new(gophercloud.ProviderClient) - p.IdentityBase = base - p.IdentityEndpoint = endpoint - p.UseTokenLock() - - return p, nil -} - -/* -AuthenticatedClient logs in to an OpenStack cloud found at the identity endpoint -specified by the options, acquires a token, and returns a Provider Client -instance that's ready to operate. - -If the full path to a versioned identity endpoint was specified (example: -http://example.com:5000/v3), that path will be used as the endpoint to query. - -If a versionless endpoint was specified (example: http://example.com:5000/), -the endpoint will be queried to determine which versions of the identity service -are available, then chooses the most recent or most supported version. - -Example: - - ao, err := openstack.AuthOptionsFromEnv() - provider, err := openstack.AuthenticatedClient(ao) - client, err := openstack.NewNetworkV2(client, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) -*/ -func AuthenticatedClient(options gophercloud.AuthOptions) (*gophercloud.ProviderClient, error) { - client, err := NewClient(options.IdentityEndpoint) - if err != nil { - return nil, err - } - - err = Authenticate(client, options) - if err != nil { - return nil, err - } - return client, nil -} - -// Authenticate or re-authenticate against the most recent identity service -// supported at the provided endpoint. -func Authenticate(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error { - versions := []*utils.Version{ - {ID: v2, Priority: 20, Suffix: "/v2.0/"}, - {ID: v3, Priority: 30, Suffix: "/v3/"}, - } - - chosen, endpoint, err := utils.ChooseVersion(client, versions) - if err != nil { - return err - } - - switch chosen.ID { - case v2: - return v2auth(client, endpoint, options, gophercloud.EndpointOpts{}) - case v3: - return v3auth(client, endpoint, &options, gophercloud.EndpointOpts{}) - default: - // The switch statement must be out of date from the versions list. - return fmt.Errorf("Unrecognized identity version: %s", chosen.ID) - } -} - -// AuthenticateV2 explicitly authenticates against the identity v2 endpoint. -func AuthenticateV2(client *gophercloud.ProviderClient, options gophercloud.AuthOptions, eo gophercloud.EndpointOpts) error { - return v2auth(client, "", options, eo) -} - -func v2auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions, eo gophercloud.EndpointOpts) error { - v2Client, err := NewIdentityV2(client, eo) - if err != nil { - return err - } - - if endpoint != "" { - v2Client.Endpoint = endpoint - } - - v2Opts := tokens2.AuthOptions{ - IdentityEndpoint: options.IdentityEndpoint, - Username: options.Username, - Password: options.Password, - TenantID: options.TenantID, - TenantName: options.TenantName, - AllowReauth: options.AllowReauth, - TokenID: options.TokenID, - } - - result := tokens2.Create(v2Client, v2Opts) - - token, err := result.ExtractToken() - if err != nil { - return err - } - - catalog, err := result.ExtractServiceCatalog() - if err != nil { - return err - } - - if options.AllowReauth { - // here we're creating a throw-away client (tac). it's a copy of the user's provider client, but - // with the token and reauth func zeroed out. combined with setting `AllowReauth` to `false`, - // this should retry authentication only once - tac := *client - tac.SetThrowaway(true) - tac.ReauthFunc = nil - tac.TokenID = "" - tao := options - tao.AllowReauth = false - client.ReauthFunc = func() error { - err := v2auth(&tac, endpoint, tao, eo) - if err != nil { - return err - } - client.TokenID = tac.TokenID - return nil - } - } - client.TokenID = token.ID - client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { - return V2EndpointURL(catalog, opts) - } - - return nil -} - -// AuthenticateV3 explicitly authenticates against the identity v3 service. -func AuthenticateV3(client *gophercloud.ProviderClient, options tokens3.AuthOptionsBuilder, eo gophercloud.EndpointOpts) error { - return v3auth(client, "", options, eo) -} - -func v3auth(client *gophercloud.ProviderClient, endpoint string, opts tokens3.AuthOptionsBuilder, eo gophercloud.EndpointOpts) error { - // Override the generated service endpoint with the one returned by the version endpoint. - v3Client, err := NewIdentityV3(client, eo) - if err != nil { - return err - } - - if endpoint != "" { - v3Client.Endpoint = endpoint - } - - result := tokens3.Create(v3Client, opts) - - token, err := result.ExtractToken() - if err != nil { - return err - } - - catalog, err := result.ExtractServiceCatalog() - if err != nil { - return err - } - - client.TokenID = token.ID - - if opts.CanReauth() { - // here we're creating a throw-away client (tac). it's a copy of the user's provider client, but - // with the token and reauth func zeroed out. combined with setting `AllowReauth` to `false`, - // this should retry authentication only once - tac := *client - tac.SetThrowaway(true) - tac.ReauthFunc = nil - tac.TokenID = "" - var tao tokens3.AuthOptionsBuilder - switch ot := opts.(type) { - case *gophercloud.AuthOptions: - o := *ot - o.AllowReauth = false - tao = &o - case *tokens3.AuthOptions: - o := *ot - o.AllowReauth = false - tao = &o - default: - tao = opts - } - client.ReauthFunc = func() error { - err := v3auth(&tac, endpoint, tao, eo) - if err != nil { - return err - } - client.TokenID = tac.TokenID - return nil - } - } - client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { - return V3EndpointURL(catalog, opts) - } - - return nil -} - -// NewIdentityV2 creates a ServiceClient that may be used to interact with the -// v2 identity service. -func NewIdentityV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - endpoint := client.IdentityBase + "v2.0/" - clientType := "identity" - var err error - if !reflect.DeepEqual(eo, gophercloud.EndpointOpts{}) { - eo.ApplyDefaults(clientType) - endpoint, err = client.EndpointLocator(eo) - if err != nil { - return nil, err - } - } - - return &gophercloud.ServiceClient{ - ProviderClient: client, - Endpoint: endpoint, - Type: clientType, - }, nil -} - -// NewIdentityV3 creates a ServiceClient that may be used to access the v3 -// identity service. -func NewIdentityV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - endpoint := client.IdentityBase + "v3/" - clientType := "identity" - var err error - if !reflect.DeepEqual(eo, gophercloud.EndpointOpts{}) { - eo.ApplyDefaults(clientType) - endpoint, err = client.EndpointLocator(eo) - if err != nil { - return nil, err - } - } - - // Ensure endpoint still has a suffix of v3. - // This is because EndpointLocator might have found a versionless - // endpoint or the published endpoint is still /v2.0. In both - // cases, we need to fix the endpoint to point to /v3. - base, err := utils.BaseEndpoint(endpoint) - if err != nil { - return nil, err - } - - base = gophercloud.NormalizeURL(base) - - endpoint = base + "v3/" - - return &gophercloud.ServiceClient{ - ProviderClient: client, - Endpoint: endpoint, - Type: clientType, - }, nil -} - -func initClientOpts(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts, clientType string) (*gophercloud.ServiceClient, error) { - sc := new(gophercloud.ServiceClient) - eo.ApplyDefaults(clientType) - url, err := client.EndpointLocator(eo) - if err != nil { - return sc, err - } - sc.ProviderClient = client - sc.Endpoint = url - sc.Type = clientType - return sc, nil -} - -// NewObjectStorageV1 creates a ServiceClient that may be used with the v1 -// object storage package. -func NewObjectStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "object-store") -} - -// NewComputeV2 creates a ServiceClient that may be used with the v2 compute -// package. -func NewComputeV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "compute") -} - -// NewNetworkV2 creates a ServiceClient that may be used with the v2 network -// package. -func NewNetworkV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - sc, err := initClientOpts(client, eo, "network") - sc.ResourceBase = sc.Endpoint + "v2.0/" - return sc, err -} - -// NewBlockStorageV1 creates a ServiceClient that may be used to access the v1 -// block storage service. -func NewBlockStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "volume") -} - -// NewBlockStorageV2 creates a ServiceClient that may be used to access the v2 -// block storage service. -func NewBlockStorageV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "volumev2") -} - -// NewBlockStorageV3 creates a ServiceClient that may be used to access the v3 block storage service. -func NewBlockStorageV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "volumev3") -} - -// NewSharedFileSystemV2 creates a ServiceClient that may be used to access the v2 shared file system service. -func NewSharedFileSystemV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "sharev2") -} - -// NewCDNV1 creates a ServiceClient that may be used to access the OpenStack v1 -// CDN service. -func NewCDNV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "cdn") -} - -// NewOrchestrationV1 creates a ServiceClient that may be used to access the v1 -// orchestration service. -func NewOrchestrationV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "orchestration") -} - -// NewDBV1 creates a ServiceClient that may be used to access the v1 DB service. -func NewDBV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "database") -} - -// NewDNSV2 creates a ServiceClient that may be used to access the v2 DNS -// service. -func NewDNSV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - sc, err := initClientOpts(client, eo, "dns") - sc.ResourceBase = sc.Endpoint + "v2/" - return sc, err -} - -// NewImageServiceV2 creates a ServiceClient that may be used to access the v2 -// image service. -func NewImageServiceV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - sc, err := initClientOpts(client, eo, "image") - sc.ResourceBase = sc.Endpoint + "v2/" - return sc, err -} - -// NewLoadBalancerV2 creates a ServiceClient that may be used to access the v2 -// load balancer service. -func NewLoadBalancerV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - sc, err := initClientOpts(client, eo, "load-balancer") - sc.ResourceBase = sc.Endpoint + "v2.0/" - return sc, err -} - -// NewClusteringV1 creates a ServiceClient that may be used with the v1 clustering -// package. -func NewClusteringV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "clustering") -} - -// NewMessagingV2 creates a ServiceClient that may be used with the v2 messaging -// service. -func NewMessagingV2(client *gophercloud.ProviderClient, clientID string, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - sc, err := initClientOpts(client, eo, "messaging") - sc.MoreHeaders = map[string]string{"Client-ID": clientID} - return sc, err -} - -// NewContainerV1 creates a ServiceClient that may be used with v1 container package -func NewContainerV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "container") -} - -// NewKeyManagerV1 creates a ServiceClient that may be used with the v1 key -// manager service. -func NewKeyManagerV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - sc, err := initClientOpts(client, eo, "key-manager") - sc.ResourceBase = sc.Endpoint + "v1/" - return sc, err -} - -// NewContainerInfraV1 creates a ServiceClient that may be used with the v1 container infra management -// package. -func NewContainerInfraV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "container-infra") -} - -// NewWorkflowV2 creates a ServiceClient that may be used with the v2 workflow management package. -func NewWorkflowV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { - return initClientOpts(client, eo, "workflowv2") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/doc.go deleted file mode 100644 index 617fafa..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/doc.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Package recordsets provides information and interaction with the zone API -resource for the OpenStack DNS service. - -Example to List RecordSets by Zone - - listOpts := recordsets.ListOpts{ - Type: "A", - } - - zoneID := "fff121f5-c506-410a-a69e-2d73ef9cbdbd" - - allPages, err := recordsets.ListByZone(dnsClient, zoneID, listOpts).AllPages() - if err != nil { - panic(err) - } - - allRRs, err := recordsets.ExtractRecordSets(allPages() - if err != nil { - panic(err) - } - - for _, rr := range allRRs { - fmt.Printf("%+v\n", rr) - } - -Example to Create a RecordSet - - createOpts := recordsets.CreateOpts{ - Name: "example.com.", - Type: "A", - TTL: 3600, - Description: "This is a recordset.", - Records: []string{"10.1.0.2"}, - } - - zoneID := "fff121f5-c506-410a-a69e-2d73ef9cbdbd" - - rr, err := recordsets.Create(dnsClient, zoneID, createOpts).Extract() - if err != nil { - panic(err) - } - -Example to Delete a RecordSet - - zoneID := "fff121f5-c506-410a-a69e-2d73ef9cbdbd" - recordsetID := "d96ed01a-b439-4eb8-9b90-7a9f71017f7b" - - err := recordsets.Delete(dnsClient, zoneID, recordsetID).ExtractErr() - if err != nil { - panic(err) - } -*/ -package recordsets diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/requests.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/requests.go deleted file mode 100644 index 2bc4579..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/requests.go +++ /dev/null @@ -1,166 +0,0 @@ -package recordsets - -import ( - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/pagination" -) - -// ListOptsBuilder allows extensions to add additional parameters to the -// List request. -type ListOptsBuilder interface { - ToRecordSetListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the server attributes you want to see returned. Marker and Limit are used -// for pagination. -// https://developer.openstack.org/api-ref/dns/ -type ListOpts struct { - // Integer value for the limit of values to return. - Limit int `q:"limit"` - - // UUID of the recordset at which you want to set a marker. - Marker string `q:"marker"` - - Data string `q:"data"` - Description string `q:"description"` - Name string `q:"name"` - SortDir string `q:"sort_dir"` - SortKey string `q:"sort_key"` - Status string `q:"status"` - TTL int `q:"ttl"` - Type string `q:"type"` - ZoneID string `q:"zone_id"` -} - -// ToRecordSetListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToRecordSetListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - return q.String(), err -} - -// ListByZone implements the recordset list request. -func ListByZone(client *gophercloud.ServiceClient, zoneID string, opts ListOptsBuilder) pagination.Pager { - url := baseURL(client, zoneID) - if opts != nil { - query, err := opts.ToRecordSetListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page { - return RecordSetPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Get implements the recordset Get request. -func Get(client *gophercloud.ServiceClient, zoneID string, rrsetID string) (r GetResult) { - _, r.Err = client.Get(rrsetURL(client, zoneID, rrsetID), &r.Body, nil) - return -} - -// CreateOptsBuilder allows extensions to add additional attributes to the -// Create request. -type CreateOptsBuilder interface { - ToRecordSetCreateMap() (map[string]interface{}, error) -} - -// CreateOpts specifies the base attributes that may be used to create a -// RecordSet. -type CreateOpts struct { - // Name is the name of the RecordSet. - Name string `json:"name" required:"true"` - - // Description is a description of the RecordSet. - Description string `json:"description,omitempty"` - - // Records are the DNS records of the RecordSet. - Records []string `json:"records,omitempty"` - - // TTL is the time to live of the RecordSet. - TTL int `json:"ttl,omitempty"` - - // Type is the RRTYPE of the RecordSet. - Type string `json:"type,omitempty"` -} - -// ToRecordSetCreateMap formats an CreateOpts structure into a request body. -func (opts CreateOpts) ToRecordSetCreateMap() (map[string]interface{}, error) { - b, err := gophercloud.BuildRequestBody(opts, "") - if err != nil { - return nil, err - } - - return b, nil -} - -// Create creates a recordset in a given zone. -func Create(client *gophercloud.ServiceClient, zoneID string, opts CreateOptsBuilder) (r CreateResult) { - b, err := opts.ToRecordSetCreateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Post(baseURL(client, zoneID), &b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{201, 202}, - }) - return -} - -// UpdateOptsBuilder allows extensions to add additional attributes to the -// Update request. -type UpdateOptsBuilder interface { - ToRecordSetUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts specifies the base attributes that may be updated on an existing -// RecordSet. -type UpdateOpts struct { - // Description is a description of the RecordSet. - Description *string `json:"description,omitempty"` - - // TTL is the time to live of the RecordSet. - TTL int `json:"ttl,omitempty"` - - // Records are the DNS records of the RecordSet. - Records []string `json:"records,omitempty"` -} - -// ToRecordSetUpdateMap formats an UpdateOpts structure into a request body. -func (opts UpdateOpts) ToRecordSetUpdateMap() (map[string]interface{}, error) { - b, err := gophercloud.BuildRequestBody(opts, "") - if err != nil { - return nil, err - } - - if opts.TTL > 0 { - b["ttl"] = opts.TTL - } else { - b["ttl"] = nil - } - - return b, nil -} - -// Update updates a recordset in a given zone -func Update(client *gophercloud.ServiceClient, zoneID string, rrsetID string, opts UpdateOptsBuilder) (r UpdateResult) { - b, err := opts.ToRecordSetUpdateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Put(rrsetURL(client, zoneID, rrsetID), &b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - return -} - -// Delete removes an existing RecordSet. -func Delete(client *gophercloud.ServiceClient, zoneID string, rrsetID string) (r DeleteResult) { - _, r.Err = client.Delete(rrsetURL(client, zoneID, rrsetID), &gophercloud.RequestOpts{ - OkCodes: []int{202}, - }) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/results.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/results.go deleted file mode 100644 index 0fdc1fe..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/results.go +++ /dev/null @@ -1,147 +0,0 @@ -package recordsets - -import ( - "encoding/json" - "time" - - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/pagination" -) - -type commonResult struct { - gophercloud.Result -} - -// Extract interprets a GetResult, CreateResult or UpdateResult as a RecordSet. -// An error is returned if the original call or the extraction failed. -func (r commonResult) Extract() (*RecordSet, error) { - var s *RecordSet - err := r.ExtractInto(&s) - return s, err -} - -// CreateResult is the result of a Create operation. Call its Extract method to -// interpret the result as a RecordSet. -type CreateResult struct { - commonResult -} - -// GetResult is the result of a Get operation. Call its Extract method to -// interpret the result as a RecordSet. -type GetResult struct { - commonResult -} - -// RecordSetPage is a single page of RecordSet results. -type RecordSetPage struct { - pagination.LinkedPageBase -} - -// UpdateResult is result of an Update operation. Call its Extract method to -// interpret the result as a RecordSet. -type UpdateResult struct { - commonResult -} - -// DeleteResult is result of a Delete operation. Call its ExtractErr method to -// determine if the operation succeeded or failed. -type DeleteResult struct { - gophercloud.ErrResult -} - -// IsEmpty returns true if the page contains no results. -func (r RecordSetPage) IsEmpty() (bool, error) { - s, err := ExtractRecordSets(r) - return len(s) == 0, err -} - -// ExtractRecordSets extracts a slice of RecordSets from a List result. -func ExtractRecordSets(r pagination.Page) ([]RecordSet, error) { - var s struct { - RecordSets []RecordSet `json:"recordsets"` - } - err := (r.(RecordSetPage)).ExtractInto(&s) - return s.RecordSets, err -} - -// RecordSet represents a DNS Record Set. -type RecordSet struct { - // ID is the unique ID of the recordset - ID string `json:"id"` - - // ZoneID is the ID of the zone the recordset belongs to. - ZoneID string `json:"zone_id"` - - // ProjectID is the ID of the project that owns the recordset. - ProjectID string `json:"project_id"` - - // Name is the name of the recordset. - Name string `json:"name"` - - // ZoneName is the name of the zone the recordset belongs to. - ZoneName string `json:"zone_name"` - - // Type is the RRTYPE of the recordset. - Type string `json:"type"` - - // Records are the DNS records of the recordset. - Records []string `json:"records"` - - // TTL is the time to live of the recordset. - TTL int `json:"ttl"` - - // Status is the status of the recordset. - Status string `json:"status"` - - // Action is the current action in progress of the recordset. - Action string `json:"action"` - - // Description is the description of the recordset. - Description string `json:"description"` - - // Version is the revision of the recordset. - Version int `json:"version"` - - // CreatedAt is the date when the recordset was created. - CreatedAt time.Time `json:"-"` - - // UpdatedAt is the date when the recordset was updated. - UpdatedAt time.Time `json:"-"` - - // Links includes HTTP references to the itself, - // useful for passing along to other APIs that might want a recordset - // reference. - Links []gophercloud.Link `json:"-"` -} - -func (r *RecordSet) UnmarshalJSON(b []byte) error { - type tmp RecordSet - var s struct { - tmp - CreatedAt gophercloud.JSONRFC3339MilliNoZ `json:"created_at"` - UpdatedAt gophercloud.JSONRFC3339MilliNoZ `json:"updated_at"` - Links map[string]interface{} `json:"links"` - } - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - *r = RecordSet(s.tmp) - - r.CreatedAt = time.Time(s.CreatedAt) - r.UpdatedAt = time.Time(s.UpdatedAt) - - if s.Links != nil { - for rel, href := range s.Links { - if v, ok := href.(string); ok { - link := gophercloud.Link{ - Rel: rel, - Href: v, - } - r.Links = append(r.Links, link) - } - } - } - - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/urls.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/urls.go deleted file mode 100644 index 5ec18d1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets/urls.go +++ /dev/null @@ -1,11 +0,0 @@ -package recordsets - -import "github.com/gophercloud/gophercloud" - -func baseURL(c *gophercloud.ServiceClient, zoneID string) string { - return c.ServiceURL("zones", zoneID, "recordsets") -} - -func rrsetURL(c *gophercloud.ServiceClient, zoneID string, rrsetID string) string { - return c.ServiceURL("zones", zoneID, "recordsets", rrsetID) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/doc.go deleted file mode 100644 index 7733155..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/doc.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Package zones provides information and interaction with the zone API -resource for the OpenStack DNS service. - -Example to List Zones - - listOpts := zones.ListOpts{ - Email: "jdoe@example.com", - } - - allPages, err := zones.List(dnsClient, listOpts).AllPages() - if err != nil { - panic(err) - } - - allZones, err := zones.ExtractZones(allPages) - if err != nil { - panic(err) - } - - for _, zone := range allZones { - fmt.Printf("%+v\n", zone) - } - -Example to Create a Zone - - createOpts := zones.CreateOpts{ - Name: "example.com.", - Email: "jdoe@example.com", - Type: "PRIMARY", - TTL: 7200, - Description: "This is a zone.", - } - - zone, err := zones.Create(dnsClient, createOpts).Extract() - if err != nil { - panic(err) - } - -Example to Delete a Zone - - zoneID := "99d10f68-5623-4491-91a0-6daafa32b60e" - err := zones.Delete(dnsClient, zoneID).ExtractErr() - if err != nil { - panic(err) - } -*/ -package zones diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/requests.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/requests.go deleted file mode 100644 index 78b08ae..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/requests.go +++ /dev/null @@ -1,174 +0,0 @@ -package zones - -import ( - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/pagination" -) - -// ListOptsBuilder allows extensions to add parameters to the List request. -type ListOptsBuilder interface { - ToZoneListQuery() (string, error) -} - -// ListOpts allows the filtering and sorting of paginated collections through -// the API. Filtering is achieved by passing in struct field values that map to -// the server attributes you want to see returned. Marker and Limit are used -// for pagination. -// https://developer.openstack.org/api-ref/dns/ -type ListOpts struct { - // Integer value for the limit of values to return. - Limit int `q:"limit"` - - // UUID of the zone at which you want to set a marker. - Marker string `q:"marker"` - - Description string `q:"description"` - Email string `q:"email"` - Name string `q:"name"` - SortDir string `q:"sort_dir"` - SortKey string `q:"sort_key"` - Status string `q:"status"` - TTL int `q:"ttl"` - Type string `q:"type"` -} - -// ToZoneListQuery formats a ListOpts into a query string. -func (opts ListOpts) ToZoneListQuery() (string, error) { - q, err := gophercloud.BuildQueryString(opts) - return q.String(), err -} - -// List implements a zone List request. -func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { - url := baseURL(client) - if opts != nil { - query, err := opts.ToZoneListQuery() - if err != nil { - return pagination.Pager{Err: err} - } - url += query - } - return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page { - return ZonePage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// Get returns information about a zone, given its ID. -func Get(client *gophercloud.ServiceClient, zoneID string) (r GetResult) { - _, r.Err = client.Get(zoneURL(client, zoneID), &r.Body, nil) - return -} - -// CreateOptsBuilder allows extensions to add additional attributes to the -// Create request. -type CreateOptsBuilder interface { - ToZoneCreateMap() (map[string]interface{}, error) -} - -// CreateOpts specifies the attributes used to create a zone. -type CreateOpts struct { - // Attributes are settings that supply hints and filters for the zone. - Attributes map[string]string `json:"attributes,omitempty"` - - // Email contact of the zone. - Email string `json:"email,omitempty"` - - // Description of the zone. - Description string `json:"description,omitempty"` - - // Name of the zone. - Name string `json:"name" required:"true"` - - // Masters specifies zone masters if this is a secondary zone. - Masters []string `json:"masters,omitempty"` - - // TTL is the time to live of the zone. - TTL int `json:"-"` - - // Type specifies if this is a primary or secondary zone. - Type string `json:"type,omitempty"` -} - -// ToZoneCreateMap formats an CreateOpts structure into a request body. -func (opts CreateOpts) ToZoneCreateMap() (map[string]interface{}, error) { - b, err := gophercloud.BuildRequestBody(opts, "") - if err != nil { - return nil, err - } - - if opts.TTL > 0 { - b["ttl"] = opts.TTL - } - - return b, nil -} - -// Create implements a zone create request. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) { - b, err := opts.ToZoneCreateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Post(baseURL(client), &b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{201, 202}, - }) - return -} - -// UpdateOptsBuilder allows extensions to add additional attributes to the -// Update request. -type UpdateOptsBuilder interface { - ToZoneUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts specifies the attributes to update a zone. -type UpdateOpts struct { - // Email contact of the zone. - Email string `json:"email,omitempty"` - - // TTL is the time to live of the zone. - TTL int `json:"-"` - - // Masters specifies zone masters if this is a secondary zone. - Masters []string `json:"masters,omitempty"` - - // Description of the zone. - Description *string `json:"description,omitempty"` -} - -// ToZoneUpdateMap formats an UpdateOpts structure into a request body. -func (opts UpdateOpts) ToZoneUpdateMap() (map[string]interface{}, error) { - b, err := gophercloud.BuildRequestBody(opts, "") - if err != nil { - return nil, err - } - - if opts.TTL > 0 { - b["ttl"] = opts.TTL - } - - return b, nil -} - -// Update implements a zone update request. -func Update(client *gophercloud.ServiceClient, zoneID string, opts UpdateOptsBuilder) (r UpdateResult) { - b, err := opts.ToZoneUpdateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Patch(zoneURL(client, zoneID), &b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 202}, - }) - return -} - -// Delete implements a zone delete request. -func Delete(client *gophercloud.ServiceClient, zoneID string) (r DeleteResult) { - _, r.Err = client.Delete(zoneURL(client, zoneID), &gophercloud.RequestOpts{ - OkCodes: []int{202}, - JSONResponse: &r.Body, - }) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/results.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/results.go deleted file mode 100644 index a36eca7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/results.go +++ /dev/null @@ -1,166 +0,0 @@ -package zones - -import ( - "encoding/json" - "strconv" - "time" - - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/pagination" -) - -type commonResult struct { - gophercloud.Result -} - -// Extract interprets a GetResult, CreateResult or UpdateResult as a Zone. -// An error is returned if the original call or the extraction failed. -func (r commonResult) Extract() (*Zone, error) { - var s *Zone - err := r.ExtractInto(&s) - return s, err -} - -// CreateResult is the result of a Create request. Call its Extract method -// to interpret the result as a Zone. -type CreateResult struct { - commonResult -} - -// GetResult is the result of a Get request. Call its Extract method -// to interpret the result as a Zone. -type GetResult struct { - commonResult -} - -// UpdateResult is the result of an Update request. Call its Extract method -// to interpret the result as a Zone. -type UpdateResult struct { - commonResult -} - -// DeleteResult is the result of a Delete request. Call its ExtractErr method -// to determine if the request succeeded or failed. -type DeleteResult struct { - commonResult -} - -// ZonePage is a single page of Zone results. -type ZonePage struct { - pagination.LinkedPageBase -} - -// IsEmpty returns true if the page contains no results. -func (r ZonePage) IsEmpty() (bool, error) { - s, err := ExtractZones(r) - return len(s) == 0, err -} - -// ExtractZones extracts a slice of Zones from a List result. -func ExtractZones(r pagination.Page) ([]Zone, error) { - var s struct { - Zones []Zone `json:"zones"` - } - err := (r.(ZonePage)).ExtractInto(&s) - return s.Zones, err -} - -// Zone represents a DNS zone. -type Zone struct { - // ID uniquely identifies this zone amongst all other zones, including those - // not accessible to the current tenant. - ID string `json:"id"` - - // PoolID is the ID for the pool hosting this zone. - PoolID string `json:"pool_id"` - - // ProjectID identifies the project/tenant owning this resource. - ProjectID string `json:"project_id"` - - // Name is the DNS Name for the zone. - Name string `json:"name"` - - // Email for the zone. Used in SOA records for the zone. - Email string `json:"email"` - - // Description for this zone. - Description string `json:"description"` - - // TTL is the Time to Live for the zone. - TTL int `json:"ttl"` - - // Serial is the current serial number for the zone. - Serial int `json:"-"` - - // Status is the status of the resource. - Status string `json:"status"` - - // Action is the current action in progress on the resource. - Action string `json:"action"` - - // Version of the resource. - Version int `json:"version"` - - // Attributes for the zone. - Attributes map[string]string `json:"attributes"` - - // Type of zone. Primary is controlled by Designate. - // Secondary zones are slaved from another DNS Server. - // Defaults to Primary. - Type string `json:"type"` - - // Masters is the servers for slave servers to get DNS information from. - Masters []string `json:"masters"` - - // CreatedAt is the date when the zone was created. - CreatedAt time.Time `json:"-"` - - // UpdatedAt is the date when the last change was made to the zone. - UpdatedAt time.Time `json:"-"` - - // TransferredAt is the last time an update was retrieved from the - // master servers. - TransferredAt time.Time `json:"-"` - - // Links includes HTTP references to the itself, useful for passing along - // to other APIs that might want a server reference. - Links map[string]interface{} `json:"links"` -} - -func (r *Zone) UnmarshalJSON(b []byte) error { - type tmp Zone - var s struct { - tmp - CreatedAt gophercloud.JSONRFC3339MilliNoZ `json:"created_at"` - UpdatedAt gophercloud.JSONRFC3339MilliNoZ `json:"updated_at"` - TransferredAt gophercloud.JSONRFC3339MilliNoZ `json:"transferred_at"` - Serial interface{} `json:"serial"` - } - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - *r = Zone(s.tmp) - - r.CreatedAt = time.Time(s.CreatedAt) - r.UpdatedAt = time.Time(s.UpdatedAt) - r.TransferredAt = time.Time(s.TransferredAt) - - switch t := s.Serial.(type) { - case float64: - r.Serial = int(t) - case string: - switch t { - case "": - r.Serial = 0 - default: - serial, err := strconv.ParseFloat(t, 64) - if err != nil { - return err - } - r.Serial = int(serial) - } - } - - return err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/urls.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/urls.go deleted file mode 100644 index 9bef705..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/dns/v2/zones/urls.go +++ /dev/null @@ -1,11 +0,0 @@ -package zones - -import "github.com/gophercloud/gophercloud" - -func baseURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("zones") -} - -func zoneURL(c *gophercloud.ServiceClient, zoneID string) string { - return c.ServiceURL("zones", zoneID) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/doc.go deleted file mode 100644 index cedf1f4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/doc.go +++ /dev/null @@ -1,14 +0,0 @@ -/* -Package openstack contains resources for the individual OpenStack projects -supported in Gophercloud. It also includes functions to authenticate to an -OpenStack cloud and for provisioning various service-level clients. - -Example of Creating a Service Client - - ao, err := openstack.AuthOptionsFromEnv() - provider, err := openstack.AuthenticatedClient(ao) - client, err := openstack.NewNetworkV2(client, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) -*/ -package openstack diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go deleted file mode 100644 index 12c8aeb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go +++ /dev/null @@ -1,107 +0,0 @@ -package openstack - -import ( - "github.com/gophercloud/gophercloud" - tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens" - tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens" -) - -/* -V2EndpointURL discovers the endpoint URL for a specific service from a -ServiceCatalog acquired during the v2 identity service. - -The specified EndpointOpts are used to identify a unique, unambiguous endpoint -to return. It's an error both when multiple endpoints match the provided -criteria and when none do. The minimum that can be specified is a Type, but you -will also often need to specify a Name and/or a Region depending on what's -available on your OpenStack deployment. -*/ -func V2EndpointURL(catalog *tokens2.ServiceCatalog, opts gophercloud.EndpointOpts) (string, error) { - // Extract Endpoints from the catalog entries that match the requested Type, Name if provided, and Region if provided. - var endpoints = make([]tokens2.Endpoint, 0, 1) - for _, entry := range catalog.Entries { - if (entry.Type == opts.Type) && (opts.Name == "" || entry.Name == opts.Name) { - for _, endpoint := range entry.Endpoints { - if opts.Region == "" || endpoint.Region == opts.Region { - endpoints = append(endpoints, endpoint) - } - } - } - } - - // Report an error if the options were ambiguous. - if len(endpoints) > 1 { - err := &ErrMultipleMatchingEndpointsV2{} - err.Endpoints = endpoints - return "", err - } - - // Extract the appropriate URL from the matching Endpoint. - for _, endpoint := range endpoints { - switch opts.Availability { - case gophercloud.AvailabilityPublic: - return gophercloud.NormalizeURL(endpoint.PublicURL), nil - case gophercloud.AvailabilityInternal: - return gophercloud.NormalizeURL(endpoint.InternalURL), nil - case gophercloud.AvailabilityAdmin: - return gophercloud.NormalizeURL(endpoint.AdminURL), nil - default: - err := &ErrInvalidAvailabilityProvided{} - err.Argument = "Availability" - err.Value = opts.Availability - return "", err - } - } - - // Report an error if there were no matching endpoints. - err := &gophercloud.ErrEndpointNotFound{} - return "", err -} - -/* -V3EndpointURL discovers the endpoint URL for a specific service from a Catalog -acquired during the v3 identity service. - -The specified EndpointOpts are used to identify a unique, unambiguous endpoint -to return. It's an error both when multiple endpoints match the provided -criteria and when none do. The minimum that can be specified is a Type, but you -will also often need to specify a Name and/or a Region depending on what's -available on your OpenStack deployment. -*/ -func V3EndpointURL(catalog *tokens3.ServiceCatalog, opts gophercloud.EndpointOpts) (string, error) { - // Extract Endpoints from the catalog entries that match the requested Type, Interface, - // Name if provided, and Region if provided. - var endpoints = make([]tokens3.Endpoint, 0, 1) - for _, entry := range catalog.Entries { - if (entry.Type == opts.Type) && (opts.Name == "" || entry.Name == opts.Name) { - for _, endpoint := range entry.Endpoints { - if opts.Availability != gophercloud.AvailabilityAdmin && - opts.Availability != gophercloud.AvailabilityPublic && - opts.Availability != gophercloud.AvailabilityInternal { - err := &ErrInvalidAvailabilityProvided{} - err.Argument = "Availability" - err.Value = opts.Availability - return "", err - } - if (opts.Availability == gophercloud.Availability(endpoint.Interface)) && - (opts.Region == "" || endpoint.Region == opts.Region || endpoint.RegionID == opts.Region) { - endpoints = append(endpoints, endpoint) - } - } - } - } - - // Report an error if the options were ambiguous. - if len(endpoints) > 1 { - return "", ErrMultipleMatchingEndpointsV3{Endpoints: endpoints} - } - - // Extract the URL from the matching Endpoint. - for _, endpoint := range endpoints { - return gophercloud.NormalizeURL(endpoint.URL), nil - } - - // Report an error if there were no matching endpoints. - err := &gophercloud.ErrEndpointNotFound{} - return "", err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/errors.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/errors.go deleted file mode 100644 index df410b1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/errors.go +++ /dev/null @@ -1,71 +0,0 @@ -package openstack - -import ( - "fmt" - - "github.com/gophercloud/gophercloud" - tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens" - tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens" -) - -// ErrEndpointNotFound is the error when no suitable endpoint can be found -// in the user's catalog -type ErrEndpointNotFound struct{ gophercloud.BaseError } - -func (e ErrEndpointNotFound) Error() string { - return "No suitable endpoint could be found in the service catalog." -} - -// ErrInvalidAvailabilityProvided is the error when an invalid endpoint -// availability is provided -type ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput } - -func (e ErrInvalidAvailabilityProvided) Error() string { - return fmt.Sprintf("Unexpected availability in endpoint query: %s", e.Value) -} - -// ErrMultipleMatchingEndpointsV2 is the error when more than one endpoint -// for the given options is found in the v2 catalog -type ErrMultipleMatchingEndpointsV2 struct { - gophercloud.BaseError - Endpoints []tokens2.Endpoint -} - -func (e ErrMultipleMatchingEndpointsV2) Error() string { - return fmt.Sprintf("Discovered %d matching endpoints: %#v", len(e.Endpoints), e.Endpoints) -} - -// ErrMultipleMatchingEndpointsV3 is the error when more than one endpoint -// for the given options is found in the v3 catalog -type ErrMultipleMatchingEndpointsV3 struct { - gophercloud.BaseError - Endpoints []tokens3.Endpoint -} - -func (e ErrMultipleMatchingEndpointsV3) Error() string { - return fmt.Sprintf("Discovered %d matching endpoints: %#v", len(e.Endpoints), e.Endpoints) -} - -// ErrNoAuthURL is the error when the OS_AUTH_URL environment variable is not -// found -type ErrNoAuthURL struct{ gophercloud.ErrInvalidInput } - -func (e ErrNoAuthURL) Error() string { - return "Environment variable OS_AUTH_URL needs to be set." -} - -// ErrNoUsername is the error when the OS_USERNAME environment variable is not -// found -type ErrNoUsername struct{ gophercloud.ErrInvalidInput } - -func (e ErrNoUsername) Error() string { - return "Environment variable OS_USERNAME needs to be set." -} - -// ErrNoPassword is the error when the OS_PASSWORD environment variable is not -// found -type ErrNoPassword struct{ gophercloud.ErrInvalidInput } - -func (e ErrNoPassword) Error() string { - return "Environment variable OS_PASSWORD needs to be set." -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/doc.go deleted file mode 100644 index 4562336..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/doc.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Package tenants provides information and interaction with the -tenants API resource for the OpenStack Identity service. - -See http://developer.openstack.org/api-ref-identity-v2.html#identity-auth-v2 -and http://developer.openstack.org/api-ref-identity-v2.html#admin-tenants -for more information. - -Example to List Tenants - - listOpts := tenants.ListOpts{ - Limit: 2, - } - - allPages, err := tenants.List(identityClient, listOpts).AllPages() - if err != nil { - panic(err) - } - - allTenants, err := tenants.ExtractTenants(allPages) - if err != nil { - panic(err) - } - - for _, tenant := range allTenants { - fmt.Printf("%+v\n", tenant) - } - -Example to Create a Tenant - - createOpts := tenants.CreateOpts{ - Name: "tenant_name", - Description: "this is a tenant", - Enabled: gophercloud.Enabled, - } - - tenant, err := tenants.Create(identityClient, createOpts).Extract() - if err != nil { - panic(err) - } - -Example to Update a Tenant - - tenantID := "e6db6ed6277c461a853458589063b295" - - updateOpts := tenants.UpdateOpts{ - Description: "this is a new description", - Enabled: gophercloud.Disabled, - } - - tenant, err := tenants.Update(identityClient, tenantID, updateOpts).Extract() - if err != nil { - panic(err) - } - -Example to Delete a Tenant - - tenantID := "e6db6ed6277c461a853458589063b295" - - err := tenants.Delete(identitYClient, tenantID).ExtractErr() - if err != nil { - panic(err) - } -*/ -package tenants diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/requests.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/requests.go deleted file mode 100644 index f21a58f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/requests.go +++ /dev/null @@ -1,116 +0,0 @@ -package tenants - -import ( - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/pagination" -) - -// ListOpts filters the Tenants that are returned by the List call. -type ListOpts struct { - // Marker is the ID of the last Tenant on the previous page. - Marker string `q:"marker"` - - // Limit specifies the page size. - Limit int `q:"limit"` -} - -// List enumerates the Tenants to which the current token has access. -func List(client *gophercloud.ServiceClient, opts *ListOpts) pagination.Pager { - url := listURL(client) - if opts != nil { - q, err := gophercloud.BuildQueryString(opts) - if err != nil { - return pagination.Pager{Err: err} - } - url += q.String() - } - return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page { - return TenantPage{pagination.LinkedPageBase{PageResult: r}} - }) -} - -// CreateOpts represents the options needed when creating new tenant. -type CreateOpts struct { - // Name is the name of the tenant. - Name string `json:"name" required:"true"` - - // Description is the description of the tenant. - Description string `json:"description,omitempty"` - - // Enabled sets the tenant status to enabled or disabled. - Enabled *bool `json:"enabled,omitempty"` -} - -// CreateOptsBuilder enables extensions to add additional parameters to the -// Create request. -type CreateOptsBuilder interface { - ToTenantCreateMap() (map[string]interface{}, error) -} - -// ToTenantCreateMap assembles a request body based on the contents of -// a CreateOpts. -func (opts CreateOpts) ToTenantCreateMap() (map[string]interface{}, error) { - return gophercloud.BuildRequestBody(opts, "tenant") -} - -// Create is the operation responsible for creating new tenant. -func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) { - b, err := opts.ToTenantCreateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 201}, - }) - return -} - -// Get requests details on a single tenant by ID. -func Get(client *gophercloud.ServiceClient, id string) (r GetResult) { - _, r.Err = client.Get(getURL(client, id), &r.Body, nil) - return -} - -// UpdateOptsBuilder allows extensions to add additional parameters to the -// Update request. -type UpdateOptsBuilder interface { - ToTenantUpdateMap() (map[string]interface{}, error) -} - -// UpdateOpts specifies the base attributes that may be updated on an existing -// tenant. -type UpdateOpts struct { - // Name is the name of the tenant. - Name string `json:"name,omitempty"` - - // Description is the description of the tenant. - Description *string `json:"description,omitempty"` - - // Enabled sets the tenant status to enabled or disabled. - Enabled *bool `json:"enabled,omitempty"` -} - -// ToTenantUpdateMap formats an UpdateOpts structure into a request body. -func (opts UpdateOpts) ToTenantUpdateMap() (map[string]interface{}, error) { - return gophercloud.BuildRequestBody(opts, "tenant") -} - -// Update is the operation responsible for updating exist tenants by their TenantID. -func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) { - b, err := opts.ToTenantUpdateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Put(updateURL(client, id), &b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200}, - }) - return -} - -// Delete is the operation responsible for permanently deleting a tenant. -func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) { - _, r.Err = client.Delete(deleteURL(client, id), nil) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/results.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/results.go deleted file mode 100644 index bb6c2c6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/results.go +++ /dev/null @@ -1,91 +0,0 @@ -package tenants - -import ( - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/pagination" -) - -// Tenant is a grouping of users in the identity service. -type Tenant struct { - // ID is a unique identifier for this tenant. - ID string `json:"id"` - - // Name is a friendlier user-facing name for this tenant. - Name string `json:"name"` - - // Description is a human-readable explanation of this Tenant's purpose. - Description string `json:"description"` - - // Enabled indicates whether or not a tenant is active. - Enabled bool `json:"enabled"` -} - -// TenantPage is a single page of Tenant results. -type TenantPage struct { - pagination.LinkedPageBase -} - -// IsEmpty determines whether or not a page of Tenants contains any results. -func (r TenantPage) IsEmpty() (bool, error) { - tenants, err := ExtractTenants(r) - return len(tenants) == 0, err -} - -// NextPageURL extracts the "next" link from the tenants_links section of the result. -func (r TenantPage) NextPageURL() (string, error) { - var s struct { - Links []gophercloud.Link `json:"tenants_links"` - } - err := r.ExtractInto(&s) - if err != nil { - return "", err - } - return gophercloud.ExtractNextURL(s.Links) -} - -// ExtractTenants returns a slice of Tenants contained in a single page of -// results. -func ExtractTenants(r pagination.Page) ([]Tenant, error) { - var s struct { - Tenants []Tenant `json:"tenants"` - } - err := (r.(TenantPage)).ExtractInto(&s) - return s.Tenants, err -} - -type tenantResult struct { - gophercloud.Result -} - -// Extract interprets any tenantResults as a Tenant. -func (r tenantResult) Extract() (*Tenant, error) { - var s struct { - Tenant *Tenant `json:"tenant"` - } - err := r.ExtractInto(&s) - return s.Tenant, err -} - -// GetResult is the response from a Get request. Call its Extract method to -// interpret it as a Tenant. -type GetResult struct { - tenantResult -} - -// CreateResult is the response from a Create request. Call its Extract method -// to interpret it as a Tenant. -type CreateResult struct { - tenantResult -} - -// DeleteResult is the response from a Get request. Call its ExtractErr method -// to determine if the call succeeded or failed. -type DeleteResult struct { - gophercloud.ErrResult -} - -// UpdateResult is the response from a Update request. Call its Extract method -// to interpret it as a Tenant. -type UpdateResult struct { - tenantResult -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/urls.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/urls.go deleted file mode 100644 index 0f02669..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tenants/urls.go +++ /dev/null @@ -1,23 +0,0 @@ -package tenants - -import "github.com/gophercloud/gophercloud" - -func listURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("tenants") -} - -func getURL(client *gophercloud.ServiceClient, tenantID string) string { - return client.ServiceURL("tenants", tenantID) -} - -func createURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("tenants") -} - -func deleteURL(client *gophercloud.ServiceClient, tenantID string) string { - return client.ServiceURL("tenants", tenantID) -} - -func updateURL(client *gophercloud.ServiceClient, tenantID string) string { - return client.ServiceURL("tenants", tenantID) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/doc.go deleted file mode 100644 index 5375eea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/doc.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Package tokens provides information and interaction with the token API -resource for the OpenStack Identity service. - -For more information, see: -http://developer.openstack.org/api-ref-identity-v2.html#identity-auth-v2 - -Example to Create an Unscoped Token from a Password - - authOpts := gophercloud.AuthOptions{ - Username: "user", - Password: "pass" - } - - token, err := tokens.Create(identityClient, authOpts).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token from a Tenant ID and Password - - authOpts := gophercloud.AuthOptions{ - Username: "user", - Password: "password", - TenantID: "fc394f2ab2df4114bde39905f800dc57" - } - - token, err := tokens.Create(identityClient, authOpts).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token from a Tenant Name and Password - - authOpts := gophercloud.AuthOptions{ - Username: "user", - Password: "password", - TenantName: "tenantname" - } - - token, err := tokens.Create(identityClient, authOpts).ExtractToken() - if err != nil { - panic(err) - } -*/ -package tokens diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/requests.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/requests.go deleted file mode 100644 index ab32368..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/requests.go +++ /dev/null @@ -1,103 +0,0 @@ -package tokens - -import "github.com/gophercloud/gophercloud" - -// PasswordCredentialsV2 represents the required options to authenticate -// with a username and password. -type PasswordCredentialsV2 struct { - Username string `json:"username" required:"true"` - Password string `json:"password" required:"true"` -} - -// TokenCredentialsV2 represents the required options to authenticate -// with a token. -type TokenCredentialsV2 struct { - ID string `json:"id,omitempty" required:"true"` -} - -// AuthOptionsV2 wraps a gophercloud AuthOptions in order to adhere to the -// AuthOptionsBuilder interface. -type AuthOptionsV2 struct { - PasswordCredentials *PasswordCredentialsV2 `json:"passwordCredentials,omitempty" xor:"TokenCredentials"` - - // The TenantID and TenantName fields are optional for the Identity V2 API. - // Some providers allow you to specify a TenantName instead of the TenantId. - // Some require both. Your provider's authentication policies will determine - // how these fields influence authentication. - TenantID string `json:"tenantId,omitempty"` - TenantName string `json:"tenantName,omitempty"` - - // TokenCredentials allows users to authenticate (possibly as another user) - // with an authentication token ID. - TokenCredentials *TokenCredentialsV2 `json:"token,omitempty" xor:"PasswordCredentials"` -} - -// AuthOptionsBuilder allows extensions to add additional parameters to the -// token create request. -type AuthOptionsBuilder interface { - // ToTokenCreateMap assembles the Create request body, returning an error - // if parameters are missing or inconsistent. - ToTokenV2CreateMap() (map[string]interface{}, error) -} - -// AuthOptions are the valid options for Openstack Identity v2 authentication. -// For field descriptions, see gophercloud.AuthOptions. -type AuthOptions struct { - IdentityEndpoint string `json:"-"` - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - TenantID string `json:"tenantId,omitempty"` - TenantName string `json:"tenantName,omitempty"` - AllowReauth bool `json:"-"` - TokenID string -} - -// ToTokenV2CreateMap builds a token request body from the given AuthOptions. -func (opts AuthOptions) ToTokenV2CreateMap() (map[string]interface{}, error) { - v2Opts := AuthOptionsV2{ - TenantID: opts.TenantID, - TenantName: opts.TenantName, - } - - if opts.Password != "" { - v2Opts.PasswordCredentials = &PasswordCredentialsV2{ - Username: opts.Username, - Password: opts.Password, - } - } else { - v2Opts.TokenCredentials = &TokenCredentialsV2{ - ID: opts.TokenID, - } - } - - b, err := gophercloud.BuildRequestBody(v2Opts, "auth") - if err != nil { - return nil, err - } - return b, nil -} - -// Create authenticates to the identity service and attempts to acquire a Token. -// Generally, rather than interact with this call directly, end users should -// call openstack.AuthenticatedClient(), which abstracts all of the gory details -// about navigating service catalogs and such. -func Create(client *gophercloud.ServiceClient, auth AuthOptionsBuilder) (r CreateResult) { - b, err := auth.ToTokenV2CreateMap() - if err != nil { - r.Err = err - return - } - _, r.Err = client.Post(CreateURL(client), b, &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 203}, - MoreHeaders: map[string]string{"X-Auth-Token": ""}, - }) - return -} - -// Get validates and retrieves information for user's token. -func Get(client *gophercloud.ServiceClient, token string) (r GetResult) { - _, r.Err = client.Get(GetURL(client, token), &r.Body, &gophercloud.RequestOpts{ - OkCodes: []int{200, 203}, - }) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/results.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/results.go deleted file mode 100644 index b113267..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/results.go +++ /dev/null @@ -1,159 +0,0 @@ -package tokens - -import ( - "time" - - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/openstack/identity/v2/tenants" -) - -// Token provides only the most basic information related to an authentication -// token. -type Token struct { - // ID provides the primary means of identifying a user to the OpenStack API. - // OpenStack defines this field as an opaque value, so do not depend on its - // content. It is safe, however, to compare for equality. - ID string - - // ExpiresAt provides a timestamp in ISO 8601 format, indicating when the - // authentication token becomes invalid. After this point in time, future - // API requests made using this authentication token will respond with - // errors. Either the caller will need to reauthenticate manually, or more - // preferably, the caller should exploit automatic re-authentication. - // See the AuthOptions structure for more details. - ExpiresAt time.Time - - // Tenant provides information about the tenant to which this token grants - // access. - Tenant tenants.Tenant -} - -// Role is a role for a user. -type Role struct { - Name string `json:"name"` -} - -// User is an OpenStack user. -type User struct { - ID string `json:"id"` - Name string `json:"name"` - UserName string `json:"username"` - Roles []Role `json:"roles"` -} - -// Endpoint represents a single API endpoint offered by a service. -// It provides the public and internal URLs, if supported, along with a region -// specifier, again if provided. -// -// The significance of the Region field will depend upon your provider. -// -// In addition, the interface offered by the service will have version -// information associated with it through the VersionId, VersionInfo, and -// VersionList fields, if provided or supported. -// -// In all cases, fields which aren't supported by the provider and service -// combined will assume a zero-value (""). -type Endpoint struct { - TenantID string `json:"tenantId"` - PublicURL string `json:"publicURL"` - InternalURL string `json:"internalURL"` - AdminURL string `json:"adminURL"` - Region string `json:"region"` - VersionID string `json:"versionId"` - VersionInfo string `json:"versionInfo"` - VersionList string `json:"versionList"` -} - -// CatalogEntry provides a type-safe interface to an Identity API V2 service -// catalog listing. -// -// Each class of service, such as cloud DNS or block storage services, will have -// a single CatalogEntry representing it. -// -// Note: when looking for the desired service, try, whenever possible, to key -// off the type field. Otherwise, you'll tie the representation of the service -// to a specific provider. -type CatalogEntry struct { - // Name will contain the provider-specified name for the service. - Name string `json:"name"` - - // Type will contain a type string if OpenStack defines a type for the - // service. Otherwise, for provider-specific services, the provider may assign - // their own type strings. - Type string `json:"type"` - - // Endpoints will let the caller iterate over all the different endpoints that - // may exist for the service. - Endpoints []Endpoint `json:"endpoints"` -} - -// ServiceCatalog provides a view into the service catalog from a previous, -// successful authentication. -type ServiceCatalog struct { - Entries []CatalogEntry -} - -// CreateResult is the response from a Create request. Use ExtractToken() to -// interpret it as a Token, or ExtractServiceCatalog() to interpret it as a -// service catalog. -type CreateResult struct { - gophercloud.Result -} - -// GetResult is the deferred response from a Get call, which is the same with a -// Created token. Use ExtractUser() to interpret it as a User. -type GetResult struct { - CreateResult -} - -// ExtractToken returns the just-created Token from a CreateResult. -func (r CreateResult) ExtractToken() (*Token, error) { - var s struct { - Access struct { - Token struct { - Expires string `json:"expires"` - ID string `json:"id"` - Tenant tenants.Tenant `json:"tenant"` - } `json:"token"` - } `json:"access"` - } - - err := r.ExtractInto(&s) - if err != nil { - return nil, err - } - - expiresTs, err := time.Parse(gophercloud.RFC3339Milli, s.Access.Token.Expires) - if err != nil { - return nil, err - } - - return &Token{ - ID: s.Access.Token.ID, - ExpiresAt: expiresTs, - Tenant: s.Access.Token.Tenant, - }, nil -} - -// ExtractServiceCatalog returns the ServiceCatalog that was generated along -// with the user's Token. -func (r CreateResult) ExtractServiceCatalog() (*ServiceCatalog, error) { - var s struct { - Access struct { - Entries []CatalogEntry `json:"serviceCatalog"` - } `json:"access"` - } - err := r.ExtractInto(&s) - return &ServiceCatalog{Entries: s.Access.Entries}, err -} - -// ExtractUser returns the User from a GetResult. -func (r GetResult) ExtractUser() (*User, error) { - var s struct { - Access struct { - User User `json:"user"` - } `json:"access"` - } - err := r.ExtractInto(&s) - return &s.Access.User, err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/urls.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/urls.go deleted file mode 100644 index ee0a28f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v2/tokens/urls.go +++ /dev/null @@ -1,13 +0,0 @@ -package tokens - -import "github.com/gophercloud/gophercloud" - -// CreateURL generates the URL used to create new Tokens. -func CreateURL(client *gophercloud.ServiceClient) string { - return client.ServiceURL("tokens") -} - -// GetURL generates the URL used to Validate Tokens. -func GetURL(client *gophercloud.ServiceClient, token string) string { - return client.ServiceURL("tokens", token) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/doc.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/doc.go deleted file mode 100644 index 966e128..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/doc.go +++ /dev/null @@ -1,108 +0,0 @@ -/* -Package tokens provides information and interaction with the token API -resource for the OpenStack Identity service. - -For more information, see: -http://developer.openstack.org/api-ref-identity-v3.html#tokens-v3 - -Example to Create a Token From a Username and Password - - authOptions := tokens.AuthOptions{ - UserID: "username", - Password: "password", - } - - token, err := tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token From a Username, Password, and Domain - - authOptions := tokens.AuthOptions{ - UserID: "username", - Password: "password", - DomainID: "default", - } - - token, err := tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - - authOptions = tokens.AuthOptions{ - UserID: "username", - Password: "password", - DomainName: "default", - } - - token, err = tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token From a Token - - authOptions := tokens.AuthOptions{ - TokenID: "token_id", - } - - token, err := tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token from a Username and Password with Project ID Scope - - scope := tokens.Scope{ - ProjectID: "0fe36e73809d46aeae6705c39077b1b3", - } - - authOptions := tokens.AuthOptions{ - Scope: &scope, - UserID: "username", - Password: "password", - } - - token, err = tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token from a Username and Password with Domain ID Scope - - scope := tokens.Scope{ - DomainID: "default", - } - - authOptions := tokens.AuthOptions{ - Scope: &scope, - UserID: "username", - Password: "password", - } - - token, err = tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - -Example to Create a Token from a Username and Password with Project Name Scope - - scope := tokens.Scope{ - ProjectName: "project_name", - DomainID: "default", - } - - authOptions := tokens.AuthOptions{ - Scope: &scope, - UserID: "username", - Password: "password", - } - - token, err = tokens.Create(identityClient, authOptions).ExtractToken() - if err != nil { - panic(err) - } - -*/ -package tokens diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go deleted file mode 100644 index 2d20fa6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go +++ /dev/null @@ -1,162 +0,0 @@ -package tokens - -import "github.com/gophercloud/gophercloud" - -// Scope allows a created token to be limited to a specific domain or project. -type Scope struct { - ProjectID string - ProjectName string - DomainID string - DomainName string -} - -// AuthOptionsBuilder provides the ability for extensions to add additional -// parameters to AuthOptions. Extensions must satisfy all required methods. -type AuthOptionsBuilder interface { - // ToTokenV3CreateMap assembles the Create request body, returning an error - // if parameters are missing or inconsistent. - ToTokenV3CreateMap(map[string]interface{}) (map[string]interface{}, error) - ToTokenV3ScopeMap() (map[string]interface{}, error) - CanReauth() bool -} - -// AuthOptions represents options for authenticating a user. -type AuthOptions struct { - // IdentityEndpoint specifies the HTTP endpoint that is required to work with - // the Identity API of the appropriate version. While it's ultimately needed - // by all of the identity services, it will often be populated by a - // provider-level function. - IdentityEndpoint string `json:"-"` - - // Username is required if using Identity V2 API. Consult with your provider's - // control panel to discover your account's username. In Identity V3, either - // UserID or a combination of Username and DomainID or DomainName are needed. - Username string `json:"username,omitempty"` - UserID string `json:"id,omitempty"` - - Password string `json:"password,omitempty"` - - // At most one of DomainID and DomainName must be provided if using Username - // with Identity V3. Otherwise, either are optional. - DomainID string `json:"-"` - DomainName string `json:"name,omitempty"` - - // AllowReauth should be set to true if you grant permission for Gophercloud - // to cache your credentials in memory, and to allow Gophercloud to attempt - // to re-authenticate automatically if/when your token expires. If you set - // it to false, it will not cache these settings, but re-authentication will - // not be possible. This setting defaults to false. - AllowReauth bool `json:"-"` - - // TokenID allows users to authenticate (possibly as another user) with an - // authentication token ID. - TokenID string `json:"-"` - - // Authentication through Application Credentials requires supplying name, project and secret - // For project we can use TenantID - ApplicationCredentialID string `json:"-"` - ApplicationCredentialName string `json:"-"` - ApplicationCredentialSecret string `json:"-"` - - Scope Scope `json:"-"` -} - -// ToTokenV3CreateMap builds a request body from AuthOptions. -func (opts *AuthOptions) ToTokenV3CreateMap(scope map[string]interface{}) (map[string]interface{}, error) { - gophercloudAuthOpts := gophercloud.AuthOptions{ - Username: opts.Username, - UserID: opts.UserID, - Password: opts.Password, - DomainID: opts.DomainID, - DomainName: opts.DomainName, - AllowReauth: opts.AllowReauth, - TokenID: opts.TokenID, - ApplicationCredentialID: opts.ApplicationCredentialID, - ApplicationCredentialName: opts.ApplicationCredentialName, - ApplicationCredentialSecret: opts.ApplicationCredentialSecret, - } - - return gophercloudAuthOpts.ToTokenV3CreateMap(scope) -} - -// ToTokenV3CreateMap builds a scope request body from AuthOptions. -func (opts *AuthOptions) ToTokenV3ScopeMap() (map[string]interface{}, error) { - scope := gophercloud.AuthScope(opts.Scope) - - gophercloudAuthOpts := gophercloud.AuthOptions{ - Scope: &scope, - DomainID: opts.DomainID, - DomainName: opts.DomainName, - } - - return gophercloudAuthOpts.ToTokenV3ScopeMap() -} - -func (opts *AuthOptions) CanReauth() bool { - return opts.AllowReauth -} - -func subjectTokenHeaders(c *gophercloud.ServiceClient, subjectToken string) map[string]string { - return map[string]string{ - "X-Subject-Token": subjectToken, - } -} - -// Create authenticates and either generates a new token, or changes the Scope -// of an existing token. -func Create(c *gophercloud.ServiceClient, opts AuthOptionsBuilder) (r CreateResult) { - scope, err := opts.ToTokenV3ScopeMap() - if err != nil { - r.Err = err - return - } - - b, err := opts.ToTokenV3CreateMap(scope) - if err != nil { - r.Err = err - return - } - - resp, err := c.Post(tokenURL(c), b, &r.Body, &gophercloud.RequestOpts{ - MoreHeaders: map[string]string{"X-Auth-Token": ""}, - }) - r.Err = err - if resp != nil { - r.Header = resp.Header - } - return -} - -// Get validates and retrieves information about another token. -func Get(c *gophercloud.ServiceClient, token string) (r GetResult) { - resp, err := c.Get(tokenURL(c), &r.Body, &gophercloud.RequestOpts{ - MoreHeaders: subjectTokenHeaders(c, token), - OkCodes: []int{200, 203}, - }) - if resp != nil { - r.Err = err - r.Header = resp.Header - } - return -} - -// Validate determines if a specified token is valid or not. -func Validate(c *gophercloud.ServiceClient, token string) (bool, error) { - resp, err := c.Head(tokenURL(c), &gophercloud.RequestOpts{ - MoreHeaders: subjectTokenHeaders(c, token), - OkCodes: []int{200, 204, 404}, - }) - if err != nil { - return false, err - } - - return resp.StatusCode == 200 || resp.StatusCode == 204, nil -} - -// Revoke immediately makes specified token invalid. -func Revoke(c *gophercloud.ServiceClient, token string) (r RevokeResult) { - _, r.Err = c.Delete(tokenURL(c), &gophercloud.RequestOpts{ - MoreHeaders: subjectTokenHeaders(c, token), - }) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go deleted file mode 100644 index ebdca58..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go +++ /dev/null @@ -1,171 +0,0 @@ -package tokens - -import ( - "time" - - "github.com/gophercloud/gophercloud" -) - -// Endpoint represents a single API endpoint offered by a service. -// It matches either a public, internal or admin URL. -// If supported, it contains a region specifier, again if provided. -// The significance of the Region field will depend upon your provider. -type Endpoint struct { - ID string `json:"id"` - Region string `json:"region"` - RegionID string `json:"region_id"` - Interface string `json:"interface"` - URL string `json:"url"` -} - -// CatalogEntry provides a type-safe interface to an Identity API V3 service -// catalog listing. Each class of service, such as cloud DNS or block storage -// services, could have multiple CatalogEntry representing it (one by interface -// type, e.g public, admin or internal). -// -// Note: when looking for the desired service, try, whenever possible, to key -// off the type field. Otherwise, you'll tie the representation of the service -// to a specific provider. -type CatalogEntry struct { - // Service ID - ID string `json:"id"` - - // Name will contain the provider-specified name for the service. - Name string `json:"name"` - - // Type will contain a type string if OpenStack defines a type for the - // service. Otherwise, for provider-specific services, the provider may - // assign their own type strings. - Type string `json:"type"` - - // Endpoints will let the caller iterate over all the different endpoints that - // may exist for the service. - Endpoints []Endpoint `json:"endpoints"` -} - -// ServiceCatalog provides a view into the service catalog from a previous, -// successful authentication. -type ServiceCatalog struct { - Entries []CatalogEntry `json:"catalog"` -} - -// Domain provides information about the domain to which this token grants -// access. -type Domain struct { - ID string `json:"id"` - Name string `json:"name"` -} - -// User represents a user resource that exists in the Identity Service. -type User struct { - Domain Domain `json:"domain"` - ID string `json:"id"` - Name string `json:"name"` -} - -// Role provides information about roles to which User is authorized. -type Role struct { - ID string `json:"id"` - Name string `json:"name"` -} - -// Project provides information about project to which User is authorized. -type Project struct { - Domain Domain `json:"domain"` - ID string `json:"id"` - Name string `json:"name"` -} - -// commonResult is the response from a request. A commonResult has various -// methods which can be used to extract different details about the result. -type commonResult struct { - gophercloud.Result -} - -// Extract is a shortcut for ExtractToken. -// This function is deprecated and still present for backward compatibility. -func (r commonResult) Extract() (*Token, error) { - return r.ExtractToken() -} - -// ExtractToken interprets a commonResult as a Token. -func (r commonResult) ExtractToken() (*Token, error) { - var s Token - err := r.ExtractInto(&s) - if err != nil { - return nil, err - } - - // Parse the token itself from the stored headers. - s.ID = r.Header.Get("X-Subject-Token") - - return &s, err -} - -// ExtractServiceCatalog returns the ServiceCatalog that was generated along -// with the user's Token. -func (r commonResult) ExtractServiceCatalog() (*ServiceCatalog, error) { - var s ServiceCatalog - err := r.ExtractInto(&s) - return &s, err -} - -// ExtractUser returns the User that is the owner of the Token. -func (r commonResult) ExtractUser() (*User, error) { - var s struct { - User *User `json:"user"` - } - err := r.ExtractInto(&s) - return s.User, err -} - -// ExtractRoles returns Roles to which User is authorized. -func (r commonResult) ExtractRoles() ([]Role, error) { - var s struct { - Roles []Role `json:"roles"` - } - err := r.ExtractInto(&s) - return s.Roles, err -} - -// ExtractProject returns Project to which User is authorized. -func (r commonResult) ExtractProject() (*Project, error) { - var s struct { - Project *Project `json:"project"` - } - err := r.ExtractInto(&s) - return s.Project, err -} - -// CreateResult is the response from a Create request. Use ExtractToken() -// to interpret it as a Token, or ExtractServiceCatalog() to interpret it -// as a service catalog. -type CreateResult struct { - commonResult -} - -// GetResult is the response from a Get request. Use ExtractToken() -// to interpret it as a Token, or ExtractServiceCatalog() to interpret it -// as a service catalog. -type GetResult struct { - commonResult -} - -// RevokeResult is response from a Revoke request. -type RevokeResult struct { - commonResult -} - -// Token is a string that grants a user access to a controlled set of services -// in an OpenStack provider. Each Token is valid for a set length of time. -type Token struct { - // ID is the issued token. - ID string `json:"id"` - - // ExpiresAt is the timestamp at which this token will no longer be accepted. - ExpiresAt time.Time `json:"expires_at"` -} - -func (r commonResult) ExtractInto(v interface{}) error { - return r.ExtractIntoStructPtr(v, "token") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/urls.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/urls.go deleted file mode 100644 index 2f864a3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/urls.go +++ /dev/null @@ -1,7 +0,0 @@ -package tokens - -import "github.com/gophercloud/gophercloud" - -func tokenURL(c *gophercloud.ServiceClient) string { - return c.ServiceURL("auth", "tokens") -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go deleted file mode 100644 index 40080f7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go +++ /dev/null @@ -1,28 +0,0 @@ -package utils - -import ( - "net/url" - "regexp" - "strings" -) - -// BaseEndpoint will return a URL without the /vX.Y -// portion of the URL. -func BaseEndpoint(endpoint string) (string, error) { - u, err := url.Parse(endpoint) - if err != nil { - return "", err - } - - u.RawQuery, u.Fragment = "", "" - - path := u.Path - versionRe := regexp.MustCompile("v[0-9.]+/?") - - if version := versionRe.FindString(path); version != "" { - versionIndex := strings.Index(path, version) - u.Path = path[:versionIndex] - } - - return u.String(), nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/utils/choose_version.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/utils/choose_version.go deleted file mode 100644 index 27da19f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/openstack/utils/choose_version.go +++ /dev/null @@ -1,111 +0,0 @@ -package utils - -import ( - "fmt" - "strings" - - "github.com/gophercloud/gophercloud" -) - -// Version is a supported API version, corresponding to a vN package within the appropriate service. -type Version struct { - ID string - Suffix string - Priority int -} - -var goodStatus = map[string]bool{ - "current": true, - "supported": true, - "stable": true, -} - -// ChooseVersion queries the base endpoint of an API to choose the most recent non-experimental alternative from a service's -// published versions. -// It returns the highest-Priority Version among the alternatives that are provided, as well as its corresponding endpoint. -func ChooseVersion(client *gophercloud.ProviderClient, recognized []*Version) (*Version, string, error) { - type linkResp struct { - Href string `json:"href"` - Rel string `json:"rel"` - } - - type valueResp struct { - ID string `json:"id"` - Status string `json:"status"` - Links []linkResp `json:"links"` - } - - type versionsResp struct { - Values []valueResp `json:"values"` - } - - type response struct { - Versions versionsResp `json:"versions"` - } - - normalize := func(endpoint string) string { - if !strings.HasSuffix(endpoint, "/") { - return endpoint + "/" - } - return endpoint - } - identityEndpoint := normalize(client.IdentityEndpoint) - - // If a full endpoint is specified, check version suffixes for a match first. - for _, v := range recognized { - if strings.HasSuffix(identityEndpoint, v.Suffix) { - return v, identityEndpoint, nil - } - } - - var resp response - _, err := client.Request("GET", client.IdentityBase, &gophercloud.RequestOpts{ - JSONResponse: &resp, - OkCodes: []int{200, 300}, - }) - - if err != nil { - return nil, "", err - } - - var highest *Version - var endpoint string - - for _, value := range resp.Versions.Values { - href := "" - for _, link := range value.Links { - if link.Rel == "self" { - href = normalize(link.Href) - } - } - - for _, version := range recognized { - if strings.Contains(value.ID, version.ID) { - // Prefer a version that exactly matches the provided endpoint. - if href == identityEndpoint { - if href == "" { - return nil, "", fmt.Errorf("Endpoint missing in version %s response from %s", value.ID, client.IdentityBase) - } - return version, href, nil - } - - // Otherwise, find the highest-priority version with a whitelisted status. - if goodStatus[strings.ToLower(value.Status)] { - if highest == nil || version.Priority > highest.Priority { - highest = version - endpoint = href - } - } - } - } - } - - if highest == nil { - return nil, "", fmt.Errorf("No supported version available from endpoint %s", client.IdentityBase) - } - if endpoint == "" { - return nil, "", fmt.Errorf("Endpoint missing in version %s response from %s", highest.ID, client.IdentityBase) - } - - return highest, endpoint, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/http.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/http.go deleted file mode 100644 index 757295c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/http.go +++ /dev/null @@ -1,60 +0,0 @@ -package pagination - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "github.com/gophercloud/gophercloud" -) - -// PageResult stores the HTTP response that returned the current page of results. -type PageResult struct { - gophercloud.Result - url.URL -} - -// PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the -// results, interpreting it as JSON if the content type indicates. -func PageResultFrom(resp *http.Response) (PageResult, error) { - var parsedBody interface{} - - defer resp.Body.Close() - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return PageResult{}, err - } - - if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { - err = json.Unmarshal(rawBody, &parsedBody) - if err != nil { - return PageResult{}, err - } - } else { - parsedBody = rawBody - } - - return PageResultFromParsed(resp, parsedBody), err -} - -// PageResultFromParsed constructs a PageResult from an HTTP response that has already had its -// body parsed as JSON (and closed). -func PageResultFromParsed(resp *http.Response, body interface{}) PageResult { - return PageResult{ - Result: gophercloud.Result{ - Body: body, - Header: resp.Header, - }, - URL: *resp.Request.URL, - } -} - -// Request performs an HTTP request and extracts the http.Response from the result. -func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) { - return client.Get(url, nil, &gophercloud.RequestOpts{ - MoreHeaders: headers, - OkCodes: []int{200, 204, 300}, - }) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/linked.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/linked.go deleted file mode 100644 index 3656fb7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/linked.go +++ /dev/null @@ -1,92 +0,0 @@ -package pagination - -import ( - "fmt" - "reflect" - - "github.com/gophercloud/gophercloud" -) - -// LinkedPageBase may be embedded to implement a page that provides navigational "Next" and "Previous" links within its result. -type LinkedPageBase struct { - PageResult - - // LinkPath lists the keys that should be traversed within a response to arrive at the "next" pointer. - // If any link along the path is missing, an empty URL will be returned. - // If any link results in an unexpected value type, an error will be returned. - // When left as "nil", []string{"links", "next"} will be used as a default. - LinkPath []string -} - -// NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present. -// It assumes that the links are available in a "links" element of the top-level response object. -// If this is not the case, override NextPageURL on your result type. -func (current LinkedPageBase) NextPageURL() (string, error) { - var path []string - var key string - - if current.LinkPath == nil { - path = []string{"links", "next"} - } else { - path = current.LinkPath - } - - submap, ok := current.Body.(map[string]interface{}) - if !ok { - err := gophercloud.ErrUnexpectedType{} - err.Expected = "map[string]interface{}" - err.Actual = fmt.Sprintf("%v", reflect.TypeOf(current.Body)) - return "", err - } - - for { - key, path = path[0], path[1:len(path)] - - value, ok := submap[key] - if !ok { - return "", nil - } - - if len(path) > 0 { - submap, ok = value.(map[string]interface{}) - if !ok { - err := gophercloud.ErrUnexpectedType{} - err.Expected = "map[string]interface{}" - err.Actual = fmt.Sprintf("%v", reflect.TypeOf(value)) - return "", err - } - } else { - if value == nil { - // Actual null element. - return "", nil - } - - url, ok := value.(string) - if !ok { - err := gophercloud.ErrUnexpectedType{} - err.Expected = "string" - err.Actual = fmt.Sprintf("%v", reflect.TypeOf(value)) - return "", err - } - - return url, nil - } - } -} - -// IsEmpty satisifies the IsEmpty method of the Page interface -func (current LinkedPageBase) IsEmpty() (bool, error) { - if b, ok := current.Body.([]interface{}); ok { - return len(b) == 0, nil - } - err := gophercloud.ErrUnexpectedType{} - err.Expected = "[]interface{}" - err.Actual = fmt.Sprintf("%v", reflect.TypeOf(current.Body)) - return true, err -} - -// GetBody returns the linked page's body. This method is needed to satisfy the -// Page interface. -func (current LinkedPageBase) GetBody() interface{} { - return current.Body -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/marker.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/marker.go deleted file mode 100644 index 52e53ba..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/marker.go +++ /dev/null @@ -1,58 +0,0 @@ -package pagination - -import ( - "fmt" - "reflect" - - "github.com/gophercloud/gophercloud" -) - -// MarkerPage is a stricter Page interface that describes additional functionality required for use with NewMarkerPager. -// For convenience, embed the MarkedPageBase struct. -type MarkerPage interface { - Page - - // LastMarker returns the last "marker" value on this page. - LastMarker() (string, error) -} - -// MarkerPageBase is a page in a collection that's paginated by "limit" and "marker" query parameters. -type MarkerPageBase struct { - PageResult - - // Owner is a reference to the embedding struct. - Owner MarkerPage -} - -// NextPageURL generates the URL for the page of results after this one. -func (current MarkerPageBase) NextPageURL() (string, error) { - currentURL := current.URL - - mark, err := current.Owner.LastMarker() - if err != nil { - return "", err - } - - q := currentURL.Query() - q.Set("marker", mark) - currentURL.RawQuery = q.Encode() - - return currentURL.String(), nil -} - -// IsEmpty satisifies the IsEmpty method of the Page interface -func (current MarkerPageBase) IsEmpty() (bool, error) { - if b, ok := current.Body.([]interface{}); ok { - return len(b) == 0, nil - } - err := gophercloud.ErrUnexpectedType{} - err.Expected = "[]interface{}" - err.Actual = fmt.Sprintf("%v", reflect.TypeOf(current.Body)) - return true, err -} - -// GetBody returns the linked page's body. This method is needed to satisfy the -// Page interface. -func (current MarkerPageBase) GetBody() interface{} { - return current.Body -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/pager.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/pager.go deleted file mode 100644 index 42c0b2d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/pager.go +++ /dev/null @@ -1,251 +0,0 @@ -package pagination - -import ( - "errors" - "fmt" - "net/http" - "reflect" - "strings" - - "github.com/gophercloud/gophercloud" -) - -var ( - // ErrPageNotAvailable is returned from a Pager when a next or previous page is requested, but does not exist. - ErrPageNotAvailable = errors.New("The requested page does not exist.") -) - -// Page must be satisfied by the result type of any resource collection. -// It allows clients to interact with the resource uniformly, regardless of whether or not or how it's paginated. -// Generally, rather than implementing this interface directly, implementors should embed one of the concrete PageBase structs, -// instead. -// Depending on the pagination strategy of a particular resource, there may be an additional subinterface that the result type -// will need to implement. -type Page interface { - // NextPageURL generates the URL for the page of data that follows this collection. - // Return "" if no such page exists. - NextPageURL() (string, error) - - // IsEmpty returns true if this Page has no items in it. - IsEmpty() (bool, error) - - // GetBody returns the Page Body. This is used in the `AllPages` method. - GetBody() interface{} -} - -// Pager knows how to advance through a specific resource collection, one page at a time. -type Pager struct { - client *gophercloud.ServiceClient - - initialURL string - - createPage func(r PageResult) Page - - firstPage Page - - Err error - - // Headers supplies additional HTTP headers to populate on each paged request. - Headers map[string]string -} - -// NewPager constructs a manually-configured pager. -// Supply the URL for the first page, a function that requests a specific page given a URL, and a function that counts a page. -func NewPager(client *gophercloud.ServiceClient, initialURL string, createPage func(r PageResult) Page) Pager { - return Pager{ - client: client, - initialURL: initialURL, - createPage: createPage, - } -} - -// WithPageCreator returns a new Pager that substitutes a different page creation function. This is -// useful for overriding List functions in delegation. -func (p Pager) WithPageCreator(createPage func(r PageResult) Page) Pager { - return Pager{ - client: p.client, - initialURL: p.initialURL, - createPage: createPage, - } -} - -func (p Pager) fetchNextPage(url string) (Page, error) { - resp, err := Request(p.client, p.Headers, url) - if err != nil { - return nil, err - } - - remembered, err := PageResultFrom(resp) - if err != nil { - return nil, err - } - - return p.createPage(remembered), nil -} - -// EachPage iterates over each page returned by a Pager, yielding one at a time to a handler function. -// Return "false" from the handler to prematurely stop iterating. -func (p Pager) EachPage(handler func(Page) (bool, error)) error { - if p.Err != nil { - return p.Err - } - currentURL := p.initialURL - for { - var currentPage Page - - // if first page has already been fetched, no need to fetch it again - if p.firstPage != nil { - currentPage = p.firstPage - p.firstPage = nil - } else { - var err error - currentPage, err = p.fetchNextPage(currentURL) - if err != nil { - return err - } - } - - empty, err := currentPage.IsEmpty() - if err != nil { - return err - } - if empty { - return nil - } - - ok, err := handler(currentPage) - if err != nil { - return err - } - if !ok { - return nil - } - - currentURL, err = currentPage.NextPageURL() - if err != nil { - return err - } - if currentURL == "" { - return nil - } - } -} - -// AllPages returns all the pages from a `List` operation in a single page, -// allowing the user to retrieve all the pages at once. -func (p Pager) AllPages() (Page, error) { - // pagesSlice holds all the pages until they get converted into as Page Body. - var pagesSlice []interface{} - // body will contain the final concatenated Page body. - var body reflect.Value - - // Grab a first page to ascertain the page body type. - firstPage, err := p.fetchNextPage(p.initialURL) - if err != nil { - return nil, err - } - // Store the page type so we can use reflection to create a new mega-page of - // that type. - pageType := reflect.TypeOf(firstPage) - - // if it's a single page, just return the firstPage (first page) - if _, found := pageType.FieldByName("SinglePageBase"); found { - return firstPage, nil - } - - // store the first page to avoid getting it twice - p.firstPage = firstPage - - // Switch on the page body type. Recognized types are `map[string]interface{}`, - // `[]byte`, and `[]interface{}`. - switch pb := firstPage.GetBody().(type) { - case map[string]interface{}: - // key is the map key for the page body if the body type is `map[string]interface{}`. - var key string - // Iterate over the pages to concatenate the bodies. - err = p.EachPage(func(page Page) (bool, error) { - b := page.GetBody().(map[string]interface{}) - for k, v := range b { - // If it's a linked page, we don't want the `links`, we want the other one. - if !strings.HasSuffix(k, "links") { - // check the field's type. we only want []interface{} (which is really []map[string]interface{}) - switch vt := v.(type) { - case []interface{}: - key = k - pagesSlice = append(pagesSlice, vt...) - } - } - } - return true, nil - }) - if err != nil { - return nil, err - } - // Set body to value of type `map[string]interface{}` - body = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(key), reflect.TypeOf(pagesSlice))) - body.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(pagesSlice)) - case []byte: - // Iterate over the pages to concatenate the bodies. - err = p.EachPage(func(page Page) (bool, error) { - b := page.GetBody().([]byte) - pagesSlice = append(pagesSlice, b) - // seperate pages with a comma - pagesSlice = append(pagesSlice, []byte{10}) - return true, nil - }) - if err != nil { - return nil, err - } - if len(pagesSlice) > 0 { - // Remove the trailing comma. - pagesSlice = pagesSlice[:len(pagesSlice)-1] - } - var b []byte - // Combine the slice of slices in to a single slice. - for _, slice := range pagesSlice { - b = append(b, slice.([]byte)...) - } - // Set body to value of type `bytes`. - body = reflect.New(reflect.TypeOf(b)).Elem() - body.SetBytes(b) - case []interface{}: - // Iterate over the pages to concatenate the bodies. - err = p.EachPage(func(page Page) (bool, error) { - b := page.GetBody().([]interface{}) - pagesSlice = append(pagesSlice, b...) - return true, nil - }) - if err != nil { - return nil, err - } - // Set body to value of type `[]interface{}` - body = reflect.MakeSlice(reflect.TypeOf(pagesSlice), len(pagesSlice), len(pagesSlice)) - for i, s := range pagesSlice { - body.Index(i).Set(reflect.ValueOf(s)) - } - default: - err := gophercloud.ErrUnexpectedType{} - err.Expected = "map[string]interface{}/[]byte/[]interface{}" - err.Actual = fmt.Sprintf("%T", pb) - return nil, err - } - - // Each `Extract*` function is expecting a specific type of page coming back, - // otherwise the type assertion in those functions will fail. pageType is needed - // to create a type in this method that has the same type that the `Extract*` - // function is expecting and set the Body of that object to the concatenated - // pages. - page := reflect.New(pageType) - // Set the page body to be the concatenated pages. - page.Elem().FieldByName("Body").Set(body) - // Set any additional headers that were pass along. The `objectstorage` pacakge, - // for example, passes a Content-Type header. - h := make(http.Header) - for k, v := range p.Headers { - h.Add(k, v) - } - page.Elem().FieldByName("Header").Set(reflect.ValueOf(h)) - // Type assert the page to a Page interface so that the type assertion in the - // `Extract*` methods will work. - return page.Elem().Interface().(Page), err -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/pkg.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/pkg.go deleted file mode 100644 index 912daea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/pkg.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs. -*/ -package pagination diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/single.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/single.go deleted file mode 100644 index 4251d64..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/pagination/single.go +++ /dev/null @@ -1,33 +0,0 @@ -package pagination - -import ( - "fmt" - "reflect" - - "github.com/gophercloud/gophercloud" -) - -// SinglePageBase may be embedded in a Page that contains all of the results from an operation at once. -type SinglePageBase PageResult - -// NextPageURL always returns "" to indicate that there are no more pages to return. -func (current SinglePageBase) NextPageURL() (string, error) { - return "", nil -} - -// IsEmpty satisifies the IsEmpty method of the Page interface -func (current SinglePageBase) IsEmpty() (bool, error) { - if b, ok := current.Body.([]interface{}); ok { - return len(b) == 0, nil - } - err := gophercloud.ErrUnexpectedType{} - err.Expected = "[]interface{}" - err.Actual = fmt.Sprintf("%v", reflect.TypeOf(current.Body)) - return true, err -} - -// GetBody returns the single page's body. This method is needed to satisfy the -// Page interface. -func (current SinglePageBase) GetBody() interface{} { - return current.Body -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/params.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/params.go deleted file mode 100644 index b998666..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/params.go +++ /dev/null @@ -1,491 +0,0 @@ -package gophercloud - -import ( - "encoding/json" - "fmt" - "net/url" - "reflect" - "strconv" - "strings" - "time" -) - -/* -BuildRequestBody builds a map[string]interface from the given `struct`. If -parent is not an empty string, the final map[string]interface returned will -encapsulate the built one. For example: - - disk := 1 - createOpts := flavors.CreateOpts{ - ID: "1", - Name: "m1.tiny", - Disk: &disk, - RAM: 512, - VCPUs: 1, - RxTxFactor: 1.0, - } - - body, err := gophercloud.BuildRequestBody(createOpts, "flavor") - -The above example can be run as-is, however it is recommended to look at how -BuildRequestBody is used within Gophercloud to more fully understand how it -fits within the request process as a whole rather than use it directly as shown -above. -*/ -func BuildRequestBody(opts interface{}, parent string) (map[string]interface{}, error) { - optsValue := reflect.ValueOf(opts) - if optsValue.Kind() == reflect.Ptr { - optsValue = optsValue.Elem() - } - - optsType := reflect.TypeOf(opts) - if optsType.Kind() == reflect.Ptr { - optsType = optsType.Elem() - } - - optsMap := make(map[string]interface{}) - if optsValue.Kind() == reflect.Struct { - //fmt.Printf("optsValue.Kind() is a reflect.Struct: %+v\n", optsValue.Kind()) - for i := 0; i < optsValue.NumField(); i++ { - v := optsValue.Field(i) - f := optsType.Field(i) - - if f.Name != strings.Title(f.Name) { - //fmt.Printf("Skipping field: %s...\n", f.Name) - continue - } - - //fmt.Printf("Starting on field: %s...\n", f.Name) - - zero := isZero(v) - //fmt.Printf("v is zero?: %v\n", zero) - - // if the field has a required tag that's set to "true" - if requiredTag := f.Tag.Get("required"); requiredTag == "true" { - //fmt.Printf("Checking required field [%s]:\n\tv: %+v\n\tisZero:%v\n", f.Name, v.Interface(), zero) - // if the field's value is zero, return a missing-argument error - if zero { - // if the field has a 'required' tag, it can't have a zero-value - err := ErrMissingInput{} - err.Argument = f.Name - return nil, err - } - } - - if xorTag := f.Tag.Get("xor"); xorTag != "" { - //fmt.Printf("Checking `xor` tag for field [%s] with value %+v:\n\txorTag: %s\n", f.Name, v, xorTag) - xorField := optsValue.FieldByName(xorTag) - var xorFieldIsZero bool - if reflect.ValueOf(xorField.Interface()) == reflect.Zero(xorField.Type()) { - xorFieldIsZero = true - } else { - if xorField.Kind() == reflect.Ptr { - xorField = xorField.Elem() - } - xorFieldIsZero = isZero(xorField) - } - if !(zero != xorFieldIsZero) { - err := ErrMissingInput{} - err.Argument = fmt.Sprintf("%s/%s", f.Name, xorTag) - err.Info = fmt.Sprintf("Exactly one of %s and %s must be provided", f.Name, xorTag) - return nil, err - } - } - - if orTag := f.Tag.Get("or"); orTag != "" { - //fmt.Printf("Checking `or` tag for field with:\n\tname: %+v\n\torTag:%s\n", f.Name, orTag) - //fmt.Printf("field is zero?: %v\n", zero) - if zero { - orField := optsValue.FieldByName(orTag) - var orFieldIsZero bool - if reflect.ValueOf(orField.Interface()) == reflect.Zero(orField.Type()) { - orFieldIsZero = true - } else { - if orField.Kind() == reflect.Ptr { - orField = orField.Elem() - } - orFieldIsZero = isZero(orField) - } - if orFieldIsZero { - err := ErrMissingInput{} - err.Argument = fmt.Sprintf("%s/%s", f.Name, orTag) - err.Info = fmt.Sprintf("At least one of %s and %s must be provided", f.Name, orTag) - return nil, err - } - } - } - - jsonTag := f.Tag.Get("json") - if jsonTag == "-" { - continue - } - - if v.Kind() == reflect.Slice || (v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Slice) { - sliceValue := v - if sliceValue.Kind() == reflect.Ptr { - sliceValue = sliceValue.Elem() - } - - for i := 0; i < sliceValue.Len(); i++ { - element := sliceValue.Index(i) - if element.Kind() == reflect.Struct || (element.Kind() == reflect.Ptr && element.Elem().Kind() == reflect.Struct) { - _, err := BuildRequestBody(element.Interface(), "") - if err != nil { - return nil, err - } - } - } - } - if v.Kind() == reflect.Struct || (v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct) { - if zero { - //fmt.Printf("value before change: %+v\n", optsValue.Field(i)) - if jsonTag != "" { - jsonTagPieces := strings.Split(jsonTag, ",") - if len(jsonTagPieces) > 1 && jsonTagPieces[1] == "omitempty" { - if v.CanSet() { - if !v.IsNil() { - if v.Kind() == reflect.Ptr { - v.Set(reflect.Zero(v.Type())) - } - } - //fmt.Printf("value after change: %+v\n", optsValue.Field(i)) - } - } - } - continue - } - - //fmt.Printf("Calling BuildRequestBody with:\n\tv: %+v\n\tf.Name:%s\n", v.Interface(), f.Name) - _, err := BuildRequestBody(v.Interface(), f.Name) - if err != nil { - return nil, err - } - } - } - - //fmt.Printf("opts: %+v \n", opts) - - b, err := json.Marshal(opts) - if err != nil { - return nil, err - } - - //fmt.Printf("string(b): %s\n", string(b)) - - err = json.Unmarshal(b, &optsMap) - if err != nil { - return nil, err - } - - //fmt.Printf("optsMap: %+v\n", optsMap) - - if parent != "" { - optsMap = map[string]interface{}{parent: optsMap} - } - //fmt.Printf("optsMap after parent added: %+v\n", optsMap) - return optsMap, nil - } - // Return an error if the underlying type of 'opts' isn't a struct. - return nil, fmt.Errorf("Options type is not a struct.") -} - -// EnabledState is a convenience type, mostly used in Create and Update -// operations. Because the zero value of a bool is FALSE, we need to use a -// pointer instead to indicate zero-ness. -type EnabledState *bool - -// Convenience vars for EnabledState values. -var ( - iTrue = true - iFalse = false - - Enabled EnabledState = &iTrue - Disabled EnabledState = &iFalse -) - -// IPVersion is a type for the possible IP address versions. Valid instances -// are IPv4 and IPv6 -type IPVersion int - -const ( - // IPv4 is used for IP version 4 addresses - IPv4 IPVersion = 4 - // IPv6 is used for IP version 6 addresses - IPv6 IPVersion = 6 -) - -// IntToPointer is a function for converting integers into integer pointers. -// This is useful when passing in options to operations. -func IntToPointer(i int) *int { - return &i -} - -/* -MaybeString is an internal function to be used by request methods in individual -resource packages. - -It takes a string that might be a zero value and returns either a pointer to its -address or nil. This is useful for allowing users to conveniently omit values -from an options struct by leaving them zeroed, but still pass nil to the JSON -serializer so they'll be omitted from the request body. -*/ -func MaybeString(original string) *string { - if original != "" { - return &original - } - return nil -} - -/* -MaybeInt is an internal function to be used by request methods in individual -resource packages. - -Like MaybeString, it accepts an int that may or may not be a zero value, and -returns either a pointer to its address or nil. It's intended to hint that the -JSON serializer should omit its field. -*/ -func MaybeInt(original int) *int { - if original != 0 { - return &original - } - return nil -} - -/* -func isUnderlyingStructZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Ptr: - return isUnderlyingStructZero(v.Elem()) - default: - return isZero(v) - } -} -*/ - -var t time.Time - -func isZero(v reflect.Value) bool { - //fmt.Printf("\n\nchecking isZero for value: %+v\n", v) - switch v.Kind() { - case reflect.Ptr: - if v.IsNil() { - return true - } - return false - case reflect.Func, reflect.Map, reflect.Slice: - return v.IsNil() - case reflect.Array: - z := true - for i := 0; i < v.Len(); i++ { - z = z && isZero(v.Index(i)) - } - return z - case reflect.Struct: - if v.Type() == reflect.TypeOf(t) { - if v.Interface().(time.Time).IsZero() { - return true - } - return false - } - z := true - for i := 0; i < v.NumField(); i++ { - z = z && isZero(v.Field(i)) - } - return z - } - // Compare other types directly: - z := reflect.Zero(v.Type()) - //fmt.Printf("zero type for value: %+v\n\n\n", z) - return v.Interface() == z.Interface() -} - -/* -BuildQueryString is an internal function to be used by request methods in -individual resource packages. - -It accepts a tagged structure and expands it into a URL struct. Field names are -converted into query parameters based on a "q" tag. For example: - - type struct Something { - Bar string `q:"x_bar"` - Baz int `q:"lorem_ipsum"` - } - - instance := Something{ - Bar: "AAA", - Baz: "BBB", - } - -will be converted into "?x_bar=AAA&lorem_ipsum=BBB". - -The struct's fields may be strings, integers, or boolean values. Fields left at -their type's zero value will be omitted from the query. -*/ -func BuildQueryString(opts interface{}) (*url.URL, error) { - optsValue := reflect.ValueOf(opts) - if optsValue.Kind() == reflect.Ptr { - optsValue = optsValue.Elem() - } - - optsType := reflect.TypeOf(opts) - if optsType.Kind() == reflect.Ptr { - optsType = optsType.Elem() - } - - params := url.Values{} - - if optsValue.Kind() == reflect.Struct { - for i := 0; i < optsValue.NumField(); i++ { - v := optsValue.Field(i) - f := optsType.Field(i) - qTag := f.Tag.Get("q") - - // if the field has a 'q' tag, it goes in the query string - if qTag != "" { - tags := strings.Split(qTag, ",") - - // if the field is set, add it to the slice of query pieces - if !isZero(v) { - loop: - switch v.Kind() { - case reflect.Ptr: - v = v.Elem() - goto loop - case reflect.String: - params.Add(tags[0], v.String()) - case reflect.Int: - params.Add(tags[0], strconv.FormatInt(v.Int(), 10)) - case reflect.Bool: - params.Add(tags[0], strconv.FormatBool(v.Bool())) - case reflect.Slice: - switch v.Type().Elem() { - case reflect.TypeOf(0): - for i := 0; i < v.Len(); i++ { - params.Add(tags[0], strconv.FormatInt(v.Index(i).Int(), 10)) - } - default: - for i := 0; i < v.Len(); i++ { - params.Add(tags[0], v.Index(i).String()) - } - } - case reflect.Map: - if v.Type().Key().Kind() == reflect.String && v.Type().Elem().Kind() == reflect.String { - var s []string - for _, k := range v.MapKeys() { - value := v.MapIndex(k).String() - s = append(s, fmt.Sprintf("'%s':'%s'", k.String(), value)) - } - params.Add(tags[0], fmt.Sprintf("{%s}", strings.Join(s, ", "))) - } - } - } else { - // if the field has a 'required' tag, it can't have a zero-value - if requiredTag := f.Tag.Get("required"); requiredTag == "true" { - return &url.URL{}, fmt.Errorf("Required query parameter [%s] not set.", f.Name) - } - } - } - } - - return &url.URL{RawQuery: params.Encode()}, nil - } - // Return an error if the underlying type of 'opts' isn't a struct. - return nil, fmt.Errorf("Options type is not a struct.") -} - -/* -BuildHeaders is an internal function to be used by request methods in -individual resource packages. - -It accepts an arbitrary tagged structure and produces a string map that's -suitable for use as the HTTP headers of an outgoing request. Field names are -mapped to header names based in "h" tags. - - type struct Something { - Bar string `h:"x_bar"` - Baz int `h:"lorem_ipsum"` - } - - instance := Something{ - Bar: "AAA", - Baz: "BBB", - } - -will be converted into: - - map[string]string{ - "x_bar": "AAA", - "lorem_ipsum": "BBB", - } - -Untagged fields and fields left at their zero values are skipped. Integers, -booleans and string values are supported. -*/ -func BuildHeaders(opts interface{}) (map[string]string, error) { - optsValue := reflect.ValueOf(opts) - if optsValue.Kind() == reflect.Ptr { - optsValue = optsValue.Elem() - } - - optsType := reflect.TypeOf(opts) - if optsType.Kind() == reflect.Ptr { - optsType = optsType.Elem() - } - - optsMap := make(map[string]string) - if optsValue.Kind() == reflect.Struct { - for i := 0; i < optsValue.NumField(); i++ { - v := optsValue.Field(i) - f := optsType.Field(i) - hTag := f.Tag.Get("h") - - // if the field has a 'h' tag, it goes in the header - if hTag != "" { - tags := strings.Split(hTag, ",") - - // if the field is set, add it to the slice of query pieces - if !isZero(v) { - switch v.Kind() { - case reflect.String: - optsMap[tags[0]] = v.String() - case reflect.Int: - optsMap[tags[0]] = strconv.FormatInt(v.Int(), 10) - case reflect.Bool: - optsMap[tags[0]] = strconv.FormatBool(v.Bool()) - } - } else { - // if the field has a 'required' tag, it can't have a zero-value - if requiredTag := f.Tag.Get("required"); requiredTag == "true" { - return optsMap, fmt.Errorf("Required header [%s] not set.", f.Name) - } - } - } - - } - return optsMap, nil - } - // Return an error if the underlying type of 'opts' isn't a struct. - return optsMap, fmt.Errorf("Options type is not a struct.") -} - -// IDSliceToQueryString takes a slice of elements and converts them into a query -// string. For example, if name=foo and slice=[]int{20, 40, 60}, then the -// result would be `?name=20&name=40&name=60' -func IDSliceToQueryString(name string, ids []int) string { - str := "" - for k, v := range ids { - if k == 0 { - str += "?" - } else { - str += "&" - } - str += fmt.Sprintf("%s=%s", name, strconv.Itoa(v)) - } - return str -} - -// IntWithinRange returns TRUE if an integer falls within a defined range, and -// FALSE if not. -func IntWithinRange(val, min, max int) bool { - return val > min && val < max -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/provider_client.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/provider_client.go deleted file mode 100644 index 233ade9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/provider_client.go +++ /dev/null @@ -1,431 +0,0 @@ -package gophercloud - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "io/ioutil" - "net/http" - "strings" - "sync" -) - -// DefaultUserAgent is the default User-Agent string set in the request header. -const DefaultUserAgent = "gophercloud/2.0.0" - -// UserAgent represents a User-Agent header. -type UserAgent struct { - // prepend is the slice of User-Agent strings to prepend to DefaultUserAgent. - // All the strings to prepend are accumulated and prepended in the Join method. - prepend []string -} - -// Prepend prepends a user-defined string to the default User-Agent string. Users -// may pass in one or more strings to prepend. -func (ua *UserAgent) Prepend(s ...string) { - ua.prepend = append(s, ua.prepend...) -} - -// Join concatenates all the user-defined User-Agend strings with the default -// Gophercloud User-Agent string. -func (ua *UserAgent) Join() string { - uaSlice := append(ua.prepend, DefaultUserAgent) - return strings.Join(uaSlice, " ") -} - -// ProviderClient stores details that are required to interact with any -// services within a specific provider's API. -// -// Generally, you acquire a ProviderClient by calling the NewClient method in -// the appropriate provider's child package, providing whatever authentication -// credentials are required. -type ProviderClient struct { - // IdentityBase is the base URL used for a particular provider's identity - // service - it will be used when issuing authenticatation requests. It - // should point to the root resource of the identity service, not a specific - // identity version. - IdentityBase string - - // IdentityEndpoint is the identity endpoint. This may be a specific version - // of the identity service. If this is the case, this endpoint is used rather - // than querying versions first. - IdentityEndpoint string - - // TokenID is the ID of the most recently issued valid token. - // NOTE: Aside from within a custom ReauthFunc, this field shouldn't be set by an application. - // To safely read or write this value, call `Token` or `SetToken`, respectively - TokenID string - - // EndpointLocator describes how this provider discovers the endpoints for - // its constituent services. - EndpointLocator EndpointLocator - - // HTTPClient allows users to interject arbitrary http, https, or other transit behaviors. - HTTPClient http.Client - - // UserAgent represents the User-Agent header in the HTTP request. - UserAgent UserAgent - - // ReauthFunc is the function used to re-authenticate the user if the request - // fails with a 401 HTTP response code. This a needed because there may be multiple - // authentication functions for different Identity service versions. - ReauthFunc func() error - - // Throwaway determines whether if this client is a throw-away client. It's a copy of user's provider client - // with the token and reauth func zeroed. Such client can be used to perform reauthorization. - Throwaway bool - - mut *sync.RWMutex - - reauthmut *reauthlock -} - -type reauthlock struct { - sync.RWMutex - reauthing bool - reauthingErr error - done *sync.Cond -} - -// AuthenticatedHeaders returns a map of HTTP headers that are common for all -// authenticated service requests. Blocks if Reauthenticate is in progress. -func (client *ProviderClient) AuthenticatedHeaders() (m map[string]string) { - if client.IsThrowaway() { - return - } - if client.reauthmut != nil { - client.reauthmut.Lock() - for client.reauthmut.reauthing { - client.reauthmut.done.Wait() - } - client.reauthmut.Unlock() - } - t := client.Token() - if t == "" { - return - } - return map[string]string{"X-Auth-Token": t} -} - -// UseTokenLock creates a mutex that is used to allow safe concurrent access to the auth token. -// If the application's ProviderClient is not used concurrently, this doesn't need to be called. -func (client *ProviderClient) UseTokenLock() { - client.mut = new(sync.RWMutex) - client.reauthmut = new(reauthlock) -} - -// Token safely reads the value of the auth token from the ProviderClient. Applications should -// call this method to access the token instead of the TokenID field -func (client *ProviderClient) Token() string { - if client.mut != nil { - client.mut.RLock() - defer client.mut.RUnlock() - } - return client.TokenID -} - -// SetToken safely sets the value of the auth token in the ProviderClient. Applications may -// use this method in a custom ReauthFunc -func (client *ProviderClient) SetToken(t string) { - if client.mut != nil { - client.mut.Lock() - defer client.mut.Unlock() - } - client.TokenID = t -} - -// IsThrowaway safely reads the value of the client Throwaway field. -func (client *ProviderClient) IsThrowaway() bool { - if client.reauthmut != nil { - client.reauthmut.RLock() - defer client.reauthmut.RUnlock() - } - return client.Throwaway -} - -// SetThrowaway safely sets the value of the client Throwaway field. -func (client *ProviderClient) SetThrowaway(v bool) { - if client.reauthmut != nil { - client.reauthmut.Lock() - defer client.reauthmut.Unlock() - } - client.Throwaway = v -} - -// Reauthenticate calls client.ReauthFunc in a thread-safe way. If this is -// called because of a 401 response, the caller may pass the previous token. In -// this case, the reauthentication can be skipped if another thread has already -// reauthenticated in the meantime. If no previous token is known, an empty -// string should be passed instead to force unconditional reauthentication. -func (client *ProviderClient) Reauthenticate(previousToken string) (err error) { - if client.ReauthFunc == nil { - return nil - } - - if client.mut == nil { - return client.ReauthFunc() - } - - client.reauthmut.Lock() - if client.reauthmut.reauthing { - for !client.reauthmut.reauthing { - client.reauthmut.done.Wait() - } - err = client.reauthmut.reauthingErr - client.reauthmut.Unlock() - return err - } - client.reauthmut.Unlock() - - client.mut.Lock() - defer client.mut.Unlock() - - client.reauthmut.Lock() - client.reauthmut.reauthing = true - client.reauthmut.done = sync.NewCond(client.reauthmut) - client.reauthmut.reauthingErr = nil - client.reauthmut.Unlock() - - if previousToken == "" || client.TokenID == previousToken { - err = client.ReauthFunc() - } - - client.reauthmut.Lock() - client.reauthmut.reauthing = false - client.reauthmut.reauthingErr = err - client.reauthmut.done.Broadcast() - client.reauthmut.Unlock() - return -} - -// RequestOpts customizes the behavior of the provider.Request() method. -type RequestOpts struct { - // JSONBody, if provided, will be encoded as JSON and used as the body of the HTTP request. The - // content type of the request will default to "application/json" unless overridden by MoreHeaders. - // It's an error to specify both a JSONBody and a RawBody. - JSONBody interface{} - // RawBody contains an io.Reader that will be consumed by the request directly. No content-type - // will be set unless one is provided explicitly by MoreHeaders. - RawBody io.Reader - // JSONResponse, if provided, will be populated with the contents of the response body parsed as - // JSON. - JSONResponse interface{} - // OkCodes contains a list of numeric HTTP status codes that should be interpreted as success. If - // the response has a different code, an error will be returned. - OkCodes []int - // MoreHeaders specifies additional HTTP headers to be provide on the request. If a header is - // provided with a blank value (""), that header will be *omitted* instead: use this to suppress - // the default Accept header or an inferred Content-Type, for example. - MoreHeaders map[string]string - // ErrorContext specifies the resource error type to return if an error is encountered. - // This lets resources override default error messages based on the response status code. - ErrorContext error -} - -var applicationJSON = "application/json" - -// Request performs an HTTP request using the ProviderClient's current HTTPClient. An authentication -// header will automatically be provided. -func (client *ProviderClient) Request(method, url string, options *RequestOpts) (*http.Response, error) { - var body io.Reader - var contentType *string - - // Derive the content body by either encoding an arbitrary object as JSON, or by taking a provided - // io.ReadSeeker as-is. Default the content-type to application/json. - if options.JSONBody != nil { - if options.RawBody != nil { - return nil, errors.New("please provide only one of JSONBody or RawBody to gophercloud.Request()") - } - - rendered, err := json.Marshal(options.JSONBody) - if err != nil { - return nil, err - } - - body = bytes.NewReader(rendered) - contentType = &applicationJSON - } - - if options.RawBody != nil { - body = options.RawBody - } - - // Construct the http.Request. - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - // Populate the request headers. Apply options.MoreHeaders last, to give the caller the chance to - // modify or omit any header. - if contentType != nil { - req.Header.Set("Content-Type", *contentType) - } - req.Header.Set("Accept", applicationJSON) - - // Set the User-Agent header - req.Header.Set("User-Agent", client.UserAgent.Join()) - - if options.MoreHeaders != nil { - for k, v := range options.MoreHeaders { - if v != "" { - req.Header.Set(k, v) - } else { - req.Header.Del(k) - } - } - } - - // get latest token from client - for k, v := range client.AuthenticatedHeaders() { - req.Header.Set(k, v) - } - - // Set connection parameter to close the connection immediately when we've got the response - req.Close = true - - prereqtok := req.Header.Get("X-Auth-Token") - - // Issue the request. - resp, err := client.HTTPClient.Do(req) - if err != nil { - return nil, err - } - - // Allow default OkCodes if none explicitly set - okc := options.OkCodes - if okc == nil { - okc = defaultOkCodes(method) - } - - // Validate the HTTP response status. - var ok bool - for _, code := range okc { - if resp.StatusCode == code { - ok = true - break - } - } - - if !ok { - body, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - respErr := ErrUnexpectedResponseCode{ - URL: url, - Method: method, - Expected: options.OkCodes, - Actual: resp.StatusCode, - Body: body, - } - - errType := options.ErrorContext - switch resp.StatusCode { - case http.StatusBadRequest: - err = ErrDefault400{respErr} - if error400er, ok := errType.(Err400er); ok { - err = error400er.Error400(respErr) - } - case http.StatusUnauthorized: - if client.ReauthFunc != nil { - err = client.Reauthenticate(prereqtok) - if err != nil { - e := &ErrUnableToReauthenticate{} - e.ErrOriginal = respErr - return nil, e - } - if options.RawBody != nil { - if seeker, ok := options.RawBody.(io.Seeker); ok { - seeker.Seek(0, 0) - } - } - resp, err = client.Request(method, url, options) - if err != nil { - switch err.(type) { - case *ErrUnexpectedResponseCode: - e := &ErrErrorAfterReauthentication{} - e.ErrOriginal = err.(*ErrUnexpectedResponseCode) - return nil, e - default: - e := &ErrErrorAfterReauthentication{} - e.ErrOriginal = err - return nil, e - } - } - return resp, nil - } - err = ErrDefault401{respErr} - if error401er, ok := errType.(Err401er); ok { - err = error401er.Error401(respErr) - } - case http.StatusForbidden: - err = ErrDefault403{respErr} - if error403er, ok := errType.(Err403er); ok { - err = error403er.Error403(respErr) - } - case http.StatusNotFound: - err = ErrDefault404{respErr} - if error404er, ok := errType.(Err404er); ok { - err = error404er.Error404(respErr) - } - case http.StatusMethodNotAllowed: - err = ErrDefault405{respErr} - if error405er, ok := errType.(Err405er); ok { - err = error405er.Error405(respErr) - } - case http.StatusRequestTimeout: - err = ErrDefault408{respErr} - if error408er, ok := errType.(Err408er); ok { - err = error408er.Error408(respErr) - } - case 429: - err = ErrDefault429{respErr} - if error429er, ok := errType.(Err429er); ok { - err = error429er.Error429(respErr) - } - case http.StatusInternalServerError: - err = ErrDefault500{respErr} - if error500er, ok := errType.(Err500er); ok { - err = error500er.Error500(respErr) - } - case http.StatusServiceUnavailable: - err = ErrDefault503{respErr} - if error503er, ok := errType.(Err503er); ok { - err = error503er.Error503(respErr) - } - } - - if err == nil { - err = respErr - } - - return resp, err - } - - // Parse the response body as JSON, if requested to do so. - if options.JSONResponse != nil { - defer resp.Body.Close() - if err := json.NewDecoder(resp.Body).Decode(options.JSONResponse); err != nil { - return nil, err - } - } - - return resp, nil -} - -func defaultOkCodes(method string) []int { - switch { - case method == "GET": - return []int{200} - case method == "POST": - return []int{201, 202} - case method == "PUT": - return []int{201, 202} - case method == "PATCH": - return []int{200, 202, 204} - case method == "DELETE": - return []int{202, 204} - } - - return []int{} -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/results.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/results.go deleted file mode 100644 index 94a16bf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/results.go +++ /dev/null @@ -1,448 +0,0 @@ -package gophercloud - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "reflect" - "strconv" - "time" -) - -/* -Result is an internal type to be used by individual resource packages, but its -methods will be available on a wide variety of user-facing embedding types. - -It acts as a base struct that other Result types, returned from request -functions, can embed for convenience. All Results capture basic information -from the HTTP transaction that was performed, including the response body, -HTTP headers, and any errors that happened. - -Generally, each Result type will have an Extract method that can be used to -further interpret the result's payload in a specific context. Extensions or -providers can then provide additional extraction functions to pull out -provider- or extension-specific information as well. -*/ -type Result struct { - // Body is the payload of the HTTP response from the server. In most cases, - // this will be the deserialized JSON structure. - Body interface{} - - // Header contains the HTTP header structure from the original response. - Header http.Header - - // Err is an error that occurred during the operation. It's deferred until - // extraction to make it easier to chain the Extract call. - Err error -} - -// ExtractInto allows users to provide an object into which `Extract` will extract -// the `Result.Body`. This would be useful for OpenStack providers that have -// different fields in the response object than OpenStack proper. -func (r Result) ExtractInto(to interface{}) error { - if r.Err != nil { - return r.Err - } - - if reader, ok := r.Body.(io.Reader); ok { - if readCloser, ok := reader.(io.Closer); ok { - defer readCloser.Close() - } - return json.NewDecoder(reader).Decode(to) - } - - b, err := json.Marshal(r.Body) - if err != nil { - return err - } - err = json.Unmarshal(b, to) - - return err -} - -func (r Result) extractIntoPtr(to interface{}, label string) error { - if label == "" { - return r.ExtractInto(&to) - } - - var m map[string]interface{} - err := r.ExtractInto(&m) - if err != nil { - return err - } - - b, err := json.Marshal(m[label]) - if err != nil { - return err - } - - toValue := reflect.ValueOf(to) - if toValue.Kind() == reflect.Ptr { - toValue = toValue.Elem() - } - - switch toValue.Kind() { - case reflect.Slice: - typeOfV := toValue.Type().Elem() - if typeOfV.Kind() == reflect.Struct { - if typeOfV.NumField() > 0 && typeOfV.Field(0).Anonymous { - newSlice := reflect.MakeSlice(reflect.SliceOf(typeOfV), 0, 0) - - if mSlice, ok := m[label].([]interface{}); ok { - for _, v := range mSlice { - // For each iteration of the slice, we create a new struct. - // This is to work around a bug where elements of a slice - // are reused and not overwritten when the same copy of the - // struct is used: - // - // https://github.com/golang/go/issues/21092 - // https://github.com/golang/go/issues/24155 - // https://play.golang.org/p/NHo3ywlPZli - newType := reflect.New(typeOfV).Elem() - - b, err := json.Marshal(v) - if err != nil { - return err - } - - // This is needed for structs with an UnmarshalJSON method. - // Technically this is just unmarshalling the response into - // a struct that is never used, but it's good enough to - // trigger the UnmarshalJSON method. - for i := 0; i < newType.NumField(); i++ { - s := newType.Field(i).Addr().Interface() - - // Unmarshal is used rather than NewDecoder to also work - // around the above-mentioned bug. - err = json.Unmarshal(b, s) - if err != nil { - return err - } - } - - newSlice = reflect.Append(newSlice, newType) - } - } - - // "to" should now be properly modeled to receive the - // JSON response body and unmarshal into all the correct - // fields of the struct or composed extension struct - // at the end of this method. - toValue.Set(newSlice) - } - } - case reflect.Struct: - typeOfV := toValue.Type() - if typeOfV.NumField() > 0 && typeOfV.Field(0).Anonymous { - for i := 0; i < toValue.NumField(); i++ { - toField := toValue.Field(i) - if toField.Kind() == reflect.Struct { - s := toField.Addr().Interface() - err = json.NewDecoder(bytes.NewReader(b)).Decode(s) - if err != nil { - return err - } - } - } - } - } - - err = json.Unmarshal(b, &to) - return err -} - -// ExtractIntoStructPtr will unmarshal the Result (r) into the provided -// interface{} (to). -// -// NOTE: For internal use only -// -// `to` must be a pointer to an underlying struct type -// -// If provided, `label` will be filtered out of the response -// body prior to `r` being unmarshalled into `to`. -func (r Result) ExtractIntoStructPtr(to interface{}, label string) error { - if r.Err != nil { - return r.Err - } - - t := reflect.TypeOf(to) - if k := t.Kind(); k != reflect.Ptr { - return fmt.Errorf("Expected pointer, got %v", k) - } - switch t.Elem().Kind() { - case reflect.Struct: - return r.extractIntoPtr(to, label) - default: - return fmt.Errorf("Expected pointer to struct, got: %v", t) - } -} - -// ExtractIntoSlicePtr will unmarshal the Result (r) into the provided -// interface{} (to). -// -// NOTE: For internal use only -// -// `to` must be a pointer to an underlying slice type -// -// If provided, `label` will be filtered out of the response -// body prior to `r` being unmarshalled into `to`. -func (r Result) ExtractIntoSlicePtr(to interface{}, label string) error { - if r.Err != nil { - return r.Err - } - - t := reflect.TypeOf(to) - if k := t.Kind(); k != reflect.Ptr { - return fmt.Errorf("Expected pointer, got %v", k) - } - switch t.Elem().Kind() { - case reflect.Slice: - return r.extractIntoPtr(to, label) - default: - return fmt.Errorf("Expected pointer to slice, got: %v", t) - } -} - -// PrettyPrintJSON creates a string containing the full response body as -// pretty-printed JSON. It's useful for capturing test fixtures and for -// debugging extraction bugs. If you include its output in an issue related to -// a buggy extraction function, we will all love you forever. -func (r Result) PrettyPrintJSON() string { - pretty, err := json.MarshalIndent(r.Body, "", " ") - if err != nil { - panic(err.Error()) - } - return string(pretty) -} - -// ErrResult is an internal type to be used by individual resource packages, but -// its methods will be available on a wide variety of user-facing embedding -// types. -// -// It represents results that only contain a potential error and -// nothing else. Usually, if the operation executed successfully, the Err field -// will be nil; otherwise it will be stocked with a relevant error. Use the -// ExtractErr method -// to cleanly pull it out. -type ErrResult struct { - Result -} - -// ExtractErr is a function that extracts error information, or nil, from a result. -func (r ErrResult) ExtractErr() error { - return r.Err -} - -/* -HeaderResult is an internal type to be used by individual resource packages, but -its methods will be available on a wide variety of user-facing embedding types. - -It represents a result that only contains an error (possibly nil) and an -http.Header. This is used, for example, by the objectstorage packages in -openstack, because most of the operations don't return response bodies, but do -have relevant information in headers. -*/ -type HeaderResult struct { - Result -} - -// ExtractInto allows users to provide an object into which `Extract` will -// extract the http.Header headers of the result. -func (r HeaderResult) ExtractInto(to interface{}) error { - if r.Err != nil { - return r.Err - } - - tmpHeaderMap := map[string]string{} - for k, v := range r.Header { - if len(v) > 0 { - tmpHeaderMap[k] = v[0] - } - } - - b, err := json.Marshal(tmpHeaderMap) - if err != nil { - return err - } - err = json.Unmarshal(b, to) - - return err -} - -// RFC3339Milli describes a common time format used by some API responses. -const RFC3339Milli = "2006-01-02T15:04:05.999999Z" - -type JSONRFC3339Milli time.Time - -func (jt *JSONRFC3339Milli) UnmarshalJSON(data []byte) error { - b := bytes.NewBuffer(data) - dec := json.NewDecoder(b) - var s string - if err := dec.Decode(&s); err != nil { - return err - } - t, err := time.Parse(RFC3339Milli, s) - if err != nil { - return err - } - *jt = JSONRFC3339Milli(t) - return nil -} - -const RFC3339MilliNoZ = "2006-01-02T15:04:05.999999" - -type JSONRFC3339MilliNoZ time.Time - -func (jt *JSONRFC3339MilliNoZ) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - if s == "" { - return nil - } - t, err := time.Parse(RFC3339MilliNoZ, s) - if err != nil { - return err - } - *jt = JSONRFC3339MilliNoZ(t) - return nil -} - -type JSONRFC1123 time.Time - -func (jt *JSONRFC1123) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - if s == "" { - return nil - } - t, err := time.Parse(time.RFC1123, s) - if err != nil { - return err - } - *jt = JSONRFC1123(t) - return nil -} - -type JSONUnix time.Time - -func (jt *JSONUnix) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - if s == "" { - return nil - } - unix, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return err - } - t = time.Unix(unix, 0) - *jt = JSONUnix(t) - return nil -} - -// RFC3339NoZ is the time format used in Heat (Orchestration). -const RFC3339NoZ = "2006-01-02T15:04:05" - -type JSONRFC3339NoZ time.Time - -func (jt *JSONRFC3339NoZ) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - if s == "" { - return nil - } - t, err := time.Parse(RFC3339NoZ, s) - if err != nil { - return err - } - *jt = JSONRFC3339NoZ(t) - return nil -} - -// RFC3339ZNoT is the time format used in Zun (Containers Service). -const RFC3339ZNoT = "2006-01-02 15:04:05-07:00" - -type JSONRFC3339ZNoT time.Time - -func (jt *JSONRFC3339ZNoT) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - if s == "" { - return nil - } - t, err := time.Parse(RFC3339ZNoT, s) - if err != nil { - return err - } - *jt = JSONRFC3339ZNoT(t) - return nil -} - -// RFC3339ZNoTNoZ is another time format used in Zun (Containers Service). -const RFC3339ZNoTNoZ = "2006-01-02 15:04:05" - -type JSONRFC3339ZNoTNoZ time.Time - -func (jt *JSONRFC3339ZNoTNoZ) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - if s == "" { - return nil - } - t, err := time.Parse(RFC3339ZNoTNoZ, s) - if err != nil { - return err - } - *jt = JSONRFC3339ZNoTNoZ(t) - return nil -} - -/* -Link is an internal type to be used in packages of collection resources that are -paginated in a certain way. - -It's a response substructure common to many paginated collection results that is -used to point to related pages. Usually, the one we care about is the one with -Rel field set to "next". -*/ -type Link struct { - Href string `json:"href"` - Rel string `json:"rel"` -} - -/* -ExtractNextURL is an internal function useful for packages of collection -resources that are paginated in a certain way. - -It attempts to extract the "next" URL from slice of Link structs, or -"" if no such URL is present. -*/ -func ExtractNextURL(links []Link) (string, error) { - var url string - - for _, l := range links { - if l.Rel == "next" { - url = l.Href - } - } - - if url == "" { - return "", nil - } - - return url, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/service_client.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/service_client.go deleted file mode 100644 index 2734510..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/service_client.go +++ /dev/null @@ -1,150 +0,0 @@ -package gophercloud - -import ( - "io" - "net/http" - "strings" -) - -// ServiceClient stores details required to interact with a specific service API implemented by a provider. -// Generally, you'll acquire these by calling the appropriate `New` method on a ProviderClient. -type ServiceClient struct { - // ProviderClient is a reference to the provider that implements this service. - *ProviderClient - - // Endpoint is the base URL of the service's API, acquired from a service catalog. - // It MUST end with a /. - Endpoint string - - // ResourceBase is the base URL shared by the resources within a service's API. It should include - // the API version and, like Endpoint, MUST end with a / if set. If not set, the Endpoint is used - // as-is, instead. - ResourceBase string - - // This is the service client type (e.g. compute, sharev2). - // NOTE: FOR INTERNAL USE ONLY. DO NOT SET. GOPHERCLOUD WILL SET THIS. - // It is only exported because it gets set in a different package. - Type string - - // The microversion of the service to use. Set this to use a particular microversion. - Microversion string - - // MoreHeaders allows users (or Gophercloud) to set service-wide headers on requests. Put another way, - // values set in this field will be set on all the HTTP requests the service client sends. - MoreHeaders map[string]string -} - -// ResourceBaseURL returns the base URL of any resources used by this service. It MUST end with a /. -func (client *ServiceClient) ResourceBaseURL() string { - if client.ResourceBase != "" { - return client.ResourceBase - } - return client.Endpoint -} - -// ServiceURL constructs a URL for a resource belonging to this provider. -func (client *ServiceClient) ServiceURL(parts ...string) string { - return client.ResourceBaseURL() + strings.Join(parts, "/") -} - -func (client *ServiceClient) initReqOpts(url string, JSONBody interface{}, JSONResponse interface{}, opts *RequestOpts) { - if v, ok := (JSONBody).(io.Reader); ok { - opts.RawBody = v - } else if JSONBody != nil { - opts.JSONBody = JSONBody - } - - if JSONResponse != nil { - opts.JSONResponse = JSONResponse - } - - if opts.MoreHeaders == nil { - opts.MoreHeaders = make(map[string]string) - } - - if client.Microversion != "" { - client.setMicroversionHeader(opts) - } -} - -// Get calls `Request` with the "GET" HTTP verb. -func (client *ServiceClient) Get(url string, JSONResponse interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = new(RequestOpts) - } - client.initReqOpts(url, nil, JSONResponse, opts) - return client.Request("GET", url, opts) -} - -// Post calls `Request` with the "POST" HTTP verb. -func (client *ServiceClient) Post(url string, JSONBody interface{}, JSONResponse interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = new(RequestOpts) - } - client.initReqOpts(url, JSONBody, JSONResponse, opts) - return client.Request("POST", url, opts) -} - -// Put calls `Request` with the "PUT" HTTP verb. -func (client *ServiceClient) Put(url string, JSONBody interface{}, JSONResponse interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = new(RequestOpts) - } - client.initReqOpts(url, JSONBody, JSONResponse, opts) - return client.Request("PUT", url, opts) -} - -// Patch calls `Request` with the "PATCH" HTTP verb. -func (client *ServiceClient) Patch(url string, JSONBody interface{}, JSONResponse interface{}, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = new(RequestOpts) - } - client.initReqOpts(url, JSONBody, JSONResponse, opts) - return client.Request("PATCH", url, opts) -} - -// Delete calls `Request` with the "DELETE" HTTP verb. -func (client *ServiceClient) Delete(url string, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = new(RequestOpts) - } - client.initReqOpts(url, nil, nil, opts) - return client.Request("DELETE", url, opts) -} - -// Head calls `Request` with the "HEAD" HTTP verb. -func (client *ServiceClient) Head(url string, opts *RequestOpts) (*http.Response, error) { - if opts == nil { - opts = new(RequestOpts) - } - client.initReqOpts(url, nil, nil, opts) - return client.Request("HEAD", url, opts) -} - -func (client *ServiceClient) setMicroversionHeader(opts *RequestOpts) { - switch client.Type { - case "compute": - opts.MoreHeaders["X-OpenStack-Nova-API-Version"] = client.Microversion - case "sharev2": - opts.MoreHeaders["X-OpenStack-Manila-API-Version"] = client.Microversion - case "volume": - opts.MoreHeaders["X-OpenStack-Volume-API-Version"] = client.Microversion - } - - if client.Type != "" { - opts.MoreHeaders["OpenStack-API-Version"] = client.Type + " " + client.Microversion - } -} - -// Request carries out the HTTP operation for the service client -func (client *ServiceClient) Request(method, url string, options *RequestOpts) (*http.Response, error) { - if len(client.MoreHeaders) > 0 { - if options == nil { - options = new(RequestOpts) - } - for k, v := range client.MoreHeaders { - options.MoreHeaders[k] = v - } - } - return client.ProviderClient.Request(method, url, options) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/util.go b/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/util.go deleted file mode 100644 index 68f9a5d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/gophercloud/gophercloud/util.go +++ /dev/null @@ -1,102 +0,0 @@ -package gophercloud - -import ( - "fmt" - "net/url" - "path/filepath" - "strings" - "time" -) - -// WaitFor polls a predicate function, once per second, up to a timeout limit. -// This is useful to wait for a resource to transition to a certain state. -// To handle situations when the predicate might hang indefinitely, the -// predicate will be prematurely cancelled after the timeout. -// Resource packages will wrap this in a more convenient function that's -// specific to a certain resource, but it can also be useful on its own. -func WaitFor(timeout int, predicate func() (bool, error)) error { - type WaitForResult struct { - Success bool - Error error - } - - start := time.Now().Unix() - - for { - // If a timeout is set, and that's been exceeded, shut it down. - if timeout >= 0 && time.Now().Unix()-start >= int64(timeout) { - return fmt.Errorf("A timeout occurred") - } - - time.Sleep(1 * time.Second) - - var result WaitForResult - ch := make(chan bool, 1) - go func() { - defer close(ch) - satisfied, err := predicate() - result.Success = satisfied - result.Error = err - }() - - select { - case <-ch: - if result.Error != nil { - return result.Error - } - if result.Success { - return nil - } - // If the predicate has not finished by the timeout, cancel it. - case <-time.After(time.Duration(timeout) * time.Second): - return fmt.Errorf("A timeout occurred") - } - } -} - -// NormalizeURL is an internal function to be used by provider clients. -// -// It ensures that each endpoint URL has a closing `/`, as expected by -// ServiceClient's methods. -func NormalizeURL(url string) string { - if !strings.HasSuffix(url, "/") { - return url + "/" - } - return url -} - -// NormalizePathURL is used to convert rawPath to a fqdn, using basePath as -// a reference in the filesystem, if necessary. basePath is assumed to contain -// either '.' when first used, or the file:// type fqdn of the parent resource. -// e.g. myFavScript.yaml => file://opt/lib/myFavScript.yaml -func NormalizePathURL(basePath, rawPath string) (string, error) { - u, err := url.Parse(rawPath) - if err != nil { - return "", err - } - // if a scheme is defined, it must be a fqdn already - if u.Scheme != "" { - return u.String(), nil - } - // if basePath is a url, then child resources are assumed to be relative to it - bu, err := url.Parse(basePath) - if err != nil { - return "", err - } - var basePathSys, absPathSys string - if bu.Scheme != "" { - basePathSys = filepath.FromSlash(bu.Path) - absPathSys = filepath.Join(basePathSys, rawPath) - bu.Path = filepath.ToSlash(absPathSys) - return bu.String(), nil - } - - absPathSys = filepath.Join(basePath, rawPath) - u.Path = filepath.ToSlash(absPathSys) - if err != nil { - return "", err - } - u.Scheme = "file" - return u.String(), nil - -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/LICENSE deleted file mode 100644 index be2cc4d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/LICENSE +++ /dev/null @@ -1,362 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go deleted file mode 100644 index 5673773..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go +++ /dev/null @@ -1,161 +0,0 @@ -package simplelru - -import ( - "container/list" - "errors" -) - -// EvictCallback is used to get a callback when a cache entry is evicted -type EvictCallback func(key interface{}, value interface{}) - -// LRU implements a non-thread safe fixed size LRU cache -type LRU struct { - size int - evictList *list.List - items map[interface{}]*list.Element - onEvict EvictCallback -} - -// entry is used to hold a value in the evictList -type entry struct { - key interface{} - value interface{} -} - -// NewLRU constructs an LRU of the given size -func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { - if size <= 0 { - return nil, errors.New("Must provide a positive size") - } - c := &LRU{ - size: size, - evictList: list.New(), - items: make(map[interface{}]*list.Element), - onEvict: onEvict, - } - return c, nil -} - -// Purge is used to completely clear the cache. -func (c *LRU) Purge() { - for k, v := range c.items { - if c.onEvict != nil { - c.onEvict(k, v.Value.(*entry).value) - } - delete(c.items, k) - } - c.evictList.Init() -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *LRU) Add(key, value interface{}) (evicted bool) { - // Check for existing item - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - ent.Value.(*entry).value = value - return false - } - - // Add new item - ent := &entry{key, value} - entry := c.evictList.PushFront(ent) - c.items[key] = entry - - evict := c.evictList.Len() > c.size - // Verify size not exceeded - if evict { - c.removeOldest() - } - return evict -} - -// Get looks up a key's value from the cache. -func (c *LRU) Get(key interface{}) (value interface{}, ok bool) { - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - return ent.Value.(*entry).value, true - } - return -} - -// Contains checks if a key is in the cache, without updating the recent-ness -// or deleting it for being stale. -func (c *LRU) Contains(key interface{}) (ok bool) { - _, ok = c.items[key] - return ok -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { - var ent *list.Element - if ent, ok = c.items[key]; ok { - return ent.Value.(*entry).value, true - } - return nil, ok -} - -// Remove removes the provided key from the cache, returning if the -// key was contained. -func (c *LRU) Remove(key interface{}) (present bool) { - if ent, ok := c.items[key]; ok { - c.removeElement(ent) - return true - } - return false -} - -// RemoveOldest removes the oldest item from the cache. -func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) { - ent := c.evictList.Back() - if ent != nil { - c.removeElement(ent) - kv := ent.Value.(*entry) - return kv.key, kv.value, true - } - return nil, nil, false -} - -// GetOldest returns the oldest entry -func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) { - ent := c.evictList.Back() - if ent != nil { - kv := ent.Value.(*entry) - return kv.key, kv.value, true - } - return nil, nil, false -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *LRU) Keys() []interface{} { - keys := make([]interface{}, len(c.items)) - i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() { - keys[i] = ent.Value.(*entry).key - i++ - } - return keys -} - -// Len returns the number of items in the cache. -func (c *LRU) Len() int { - return c.evictList.Len() -} - -// removeOldest removes the oldest item from the cache. -func (c *LRU) removeOldest() { - ent := c.evictList.Back() - if ent != nil { - c.removeElement(ent) - } -} - -// removeElement is used to remove a given list element from the cache -func (c *LRU) removeElement(e *list.Element) { - c.evictList.Remove(e) - kv := e.Value.(*entry) - delete(c.items, kv.key) - if c.onEvict != nil { - c.onEvict(kv.key, kv.value) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go b/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go deleted file mode 100644 index 74c7077..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go +++ /dev/null @@ -1,36 +0,0 @@ -package simplelru - -// LRUCache is the interface for simple LRU cache. -type LRUCache interface { - // Adds a value to the cache, returns true if an eviction occurred and - // updates the "recently used"-ness of the key. - Add(key, value interface{}) bool - - // Returns key's value from the cache and - // updates the "recently used"-ness of the key. #value, isFound - Get(key interface{}) (value interface{}, ok bool) - - // Check if a key exsists in cache without updating the recent-ness. - Contains(key interface{}) (ok bool) - - // Returns key's value without updating the "recently used"-ness of the key. - Peek(key interface{}) (value interface{}, ok bool) - - // Removes a key from the cache. - Remove(key interface{}) bool - - // Removes the oldest entry from cache. - RemoveOldest() (interface{}, interface{}, bool) - - // Returns the oldest entry from the cache. #key, value, isFound - GetOldest() (interface{}, interface{}, bool) - - // Returns a slice of the keys in the cache, from oldest to newest. - Keys() []interface{} - - // Returns the number of items in the cache. - Len() int - - // Clear all cache entries - Purge() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/api.go deleted file mode 100644 index 796e066..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/api.go +++ /dev/null @@ -1,170 +0,0 @@ -// Package doapi : DO APIクライアントモジュール -package doapi - -import ( - "bytes" - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "crypto/tls" - "encoding/base64" - "encoding/json" - "fmt" - "hash" - "io" - "net/http" - "net/url" - "sort" - "strings" - "time" - - log "github.com/sirupsen/logrus" -) - -const ( - HmacSHA1 = "HmacSHA1" - HmacSHA256 = "HmacSHA256" - SignatureVersion2 = "2" - APIVersion = "20140601" - EndpointJSON = "https://do.api.iij.jp/" - // EndpointJSON = "http://localhost:9999/" - TimeLayout = "2006-01-02T15:04:05Z" - PostContentType = "application/json" -) - -// API の呼び出し先に関連する構造 -type API struct { - AccessKey string - SecretKey string - Endpoint string - SignMethod string - Expires time.Duration - Insecure bool -} - -// NewAPI API構造体のコンストラクタ -func NewAPI(accesskey, secretkey string) *API { - dur, _ := time.ParseDuration("1h") - return &API{AccessKey: accesskey, - SecretKey: secretkey, - Endpoint: EndpointJSON, - SignMethod: HmacSHA256, - Expires: dur, - } -} - -func convert1(r byte) string { - passchar := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~.-" - if strings.ContainsRune(passchar, rune(r)) { - return string(r) - } - return fmt.Sprintf("%%%02X", r) -} - -// CustomEscape escape string -func CustomEscape(v string) string { - res := "" - for _, c := range []byte(v) { - res += convert1(c) - } - return res -} - -// String2Sign get string to calculate signature -func String2Sign(method string, header http.Header, param url.URL) string { - var keys []string - ctflag := false - for k := range header { - hdr := strings.ToLower(k) - if strings.HasPrefix(hdr, "x-iijapi-") { - keys = append(keys, hdr) - } else if hdr == "content-type" || hdr == "content-md5" { - keys = append(keys, hdr) - ctflag = true - } - } - sort.Strings(keys) - var target []string - target = append(target, method) - target = append(target, "") - if !ctflag { - target = append(target, "") - } - for _, k := range keys { - if k == "content-type" || k == "content-md5" { - target = append(target, header.Get(k)) - } else { - target = append(target, k+":"+header.Get(k)) - } - } - target = append(target, param.Path) - return strings.Join(target, "\n") -} - -// Sign get signature string -func (a API) Sign(method string, header http.Header, param url.URL, signmethod string) http.Header { - header.Set("x-iijapi-Expire", time.Now().Add(a.Expires).UTC().Format(TimeLayout)) - header.Set("x-iijapi-SignatureMethod", signmethod) - header.Set("x-iijapi-SignatureVersion", SignatureVersion2) - tgtstr := String2Sign(method, header, param) - var hfn func() hash.Hash - switch signmethod { - case HmacSHA1: - hfn = sha1.New - case HmacSHA256: - hfn = sha256.New - } - mac := hmac.New(hfn, []byte(a.SecretKey)) - io.WriteString(mac, tgtstr) - macstr := mac.Sum(nil) - header.Set("Authorization", "IIJAPI "+a.AccessKey+":"+base64.StdEncoding.EncodeToString(macstr)) - return header -} - -// Get : low-level Get -func (a API) Get(param url.URL) (resp *http.Response, err error) { - return a.PostSome("GET", param, nil) -} - -// PostSome : low-level Call -func (a API) PostSome(method string, param url.URL, body interface{}) (resp *http.Response, err error) { - cl := http.Client{} - if a.Insecure { - tr := &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - cl.Transport = tr - } - log.Debug("param", param) - var buf *bytes.Buffer - if body != nil { - var bufb []byte - bufb, err = json.Marshal(body) - if err != nil { - return nil, err - } - if len(bufb) > 2 { - log.Debug("call with body", method, string(bufb)) - buf = bytes.NewBuffer(bufb) - } else { - // string(bufb)=="{}" - log.Debug("call without body(empty)", method) - buf = bytes.NewBufferString("") - body = nil - } - } else { - log.Debug("call without body(nil)", method) - buf = bytes.NewBufferString("") - } - req, err := http.NewRequest(method, param.String(), buf) - if err != nil { - return nil, err - } - if body != nil { - req.Header.Add("content-type", PostContentType) - } - req.Header = a.Sign(method, req.Header, param, HmacSHA256) - log.Debug("sign", req.Header) - resp, err = cl.Do(req) - return -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/parse.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/parse.go deleted file mode 100644 index 61401e3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/parse.go +++ /dev/null @@ -1,267 +0,0 @@ -package doapi - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strings" - "text/template" - - log "github.com/sirupsen/logrus" - - "github.com/iij/doapi/protocol" -) - -func execTemplate(name string, tmplstr string, arg interface{}) string { - tmpl, err := template.New(name).Parse(tmplstr) - if err != nil { - panic(err) - } - buf := new(bytes.Buffer) - if err = tmpl.Execute(buf, arg); err != nil { - panic(err) - } - return buf.String() -} - -// GetPath APIのURIのパス部分を求める -func GetPath(arg protocol.CommonArg) string { - return "/r/" + APIVersion + execTemplate(arg.APIName(), arg.URI(), arg) -} - -// GetParam APIのクエリストリング部分を求める -func GetParam(api API, arg protocol.CommonArg) *url.URL { - param, err := url.Parse(api.Endpoint) - if err != nil { - panic(err) - } - param.Path = GetPath(arg) - q := param.Query() - _, toQuery, _ := ArgumentListType(arg) - typs := reflect.TypeOf(arg) - vals := reflect.ValueOf(arg) - for _, key := range toQuery { - if _, flag := typs.FieldByName(key); !flag { - log.Info("no field", key) - continue - } - if val := vals.FieldByName(key).String(); len(val) != 0 { - q.Set(key, val) - } - } - param.RawQuery = q.Encode() - return param -} - -// GetBody API呼び出しのリクエストボディ(JSON文字列)を求める -func GetBody(arg protocol.CommonArg) string { - b, err := json.Marshal(arg) - if err != nil { - panic(err) - } - return string(b) -} - -// Call API呼び出しを実行し、レスポンスを得る -func Call(api API, arg protocol.CommonArg, resp interface{}) (err error) { - if err = Validate(arg); err != nil { - return - } - var res *http.Response - param := GetParam(api, arg) - log.Debug("method", arg.Method(), "param", param, "arg", arg) - if res, err = api.PostSome(arg.Method(), *param, arg); err != nil { - log.Error("PostSome", err) - return - } - log.Debug("res", res, "err", err) - var b []byte - if b, err = ioutil.ReadAll(res.Body); err != nil { - log.Error("ioutil.ReadAll", err) - return - } - log.Debug("data", string(b)) - if err = json.Unmarshal(b, &resp); err != nil { - log.Error("json.Unmarshal", err) - return - } - var cresp = protocol.CommonResponse{} - err = json.Unmarshal(b, &cresp) - if err == nil && cresp.ErrorResponse.ErrorType != "" { - return fmt.Errorf("%s: %s", cresp.ErrorResponse.ErrorType, cresp.ErrorResponse.ErrorMessage) - } - return -} - -// Validate APIの必須引数が入っているかどうかをチェック -func Validate(arg protocol.CommonArg) error { - var res []string - typs := reflect.TypeOf(arg) - vals := reflect.ValueOf(arg) - for i := 0; i < typs.NumField(); i++ { - fld := typs.Field(i) - tagstrJSON := fld.Tag.Get("json") - tagstrP2 := fld.Tag.Get("p2pub") - if strings.Contains(tagstrJSON, "omitempty") { - // optional argument - continue - } - if strings.Contains(tagstrP2, "query") { - // optional argument - continue - } - if val := vals.Field(i).String(); len(val) == 0 { - res = append(res, fld.Name) - } - } - if len(res) != 0 { - return fmt.Errorf("missing arguments: %+v", res) - } - return nil -} - -// ArgumentList API引数のリストを求める。必須とオプションに分類 -func ArgumentList(arg protocol.CommonArg) (required, optional []string) { - typs := reflect.TypeOf(arg) - for i := 0; i < typs.NumField(); i++ { - fld := typs.Field(i) - tagstrJSON := fld.Tag.Get("json") - tagstrP2 := fld.Tag.Get("p2pub") - if strings.Contains(tagstrJSON, "omitempty") || strings.Contains(tagstrP2, "query") { - optional = append(optional, fld.Name) - } else { - required = append(required, fld.Name) - } - } - return -} - -// ArgumentListType API引数のリストを求める。URI埋め込み、クエリストリング、JSONに分類 -func ArgumentListType(arg protocol.CommonArg) (toURI, toQuery, toJSON []string) { - typs := reflect.TypeOf(arg) - for i := 0; i < typs.NumField(); i++ { - fld := typs.Field(i) - tagstrJSON := fld.Tag.Get("json") - tagstrP2 := fld.Tag.Get("p2pub") - if strings.Contains(tagstrP2, "query") { - toQuery = append(toQuery, fld.Name) - } else if strings.HasPrefix(tagstrJSON, "-") { - toURI = append(toURI, fld.Name) - } else { - toJSON = append(toJSON, fld.Name) - } - } - return -} - -func argumentAltKeyList(arg protocol.CommonArg) (toAltQuery, toAltJSON map[string]string) { - toAltQuery = make(map[string]string) - toAltJSON = make(map[string]string) - typs := reflect.TypeOf(arg) - for i := 0; i < typs.NumField(); i++ { - fld := typs.Field(i) - tagstrJSON := fld.Tag.Get("json") - tagstrP2 := fld.Tag.Get("p2pub") - altKey := strings.Split(tagstrJSON, ",")[0] - if altKey == "" || altKey == "-" { - continue - } - if strings.Contains(tagstrP2, "query") { - toAltQuery[fld.Name] = altKey - } else { - toAltJSON[fld.Name] = altKey - } - } - return -} - -// ValidateMap APIの必須引数が入っているかどうかをチェック -func ValidateMap(name string, data map[string]string) error { - var res []string - typs := protocol.TypeMap[name] - for i := 0; i < typs.NumField(); i++ { - fld := typs.Field(i) - tagstrJSON := fld.Tag.Get("json") - tagstrP2 := fld.Tag.Get("p2pub") - if strings.Contains(tagstrJSON, "omitempty") { - // optional argument - continue - } - if strings.Contains(tagstrP2, "query") { - // optional argument - continue - } - if data[fld.Name] == "" { - res = append(res, fld.Name) - } - } - if len(res) != 0 { - return fmt.Errorf("missing arguments: %+v", res) - } - return nil -} - -// CallWithMap API呼び出しを実行する。引数と戻り値が構造体ではなくmap -func CallWithMap(api API, name string, data map[string]string, resp map[string]interface{}) error { - if err := ValidateMap(name, data); err != nil { - return err - } - argt := protocol.TypeMap[name] - arg := reflect.Zero(argt).Interface().(protocol.CommonArg) - var res *http.Response - param, err := url.Parse(api.Endpoint) - if err != nil { - panic(err) - } - param.Path = "/r/" + APIVersion + execTemplate(name, arg.URI(), data) - q := param.Query() - _, toQuery, toJSON := ArgumentListType(arg) - log.Debug("query", toQuery, "json", toJSON, "path", param.Path) - toAltQuery, toAltJSON := argumentAltKeyList(arg) - log.Debug("query altkey - ", toAltQuery, " json altkey - ", toAltJSON) - var jsonmap = map[string]interface{}{} - for _, v := range toJSON { - if len(data[v]) != 0 { - if altkey, ok := toAltJSON[v]; ok { - jsonmap[altkey] = data[v] - } else { - jsonmap[v] = data[v] - } - } - } - for _, v := range toQuery { - if len(data[v]) != 0 { - if altkey, ok := toAltQuery[v]; ok { - q.Set(altkey, data[v]) - } else { - q.Set(v, data[v]) - } - } - } - param.RawQuery = q.Encode() - if res, err = api.PostSome(arg.Method(), *param, jsonmap); err != nil { - log.Error("PostSome", err) - return err - } - log.Debug("res", res) - var b []byte - if b, err = ioutil.ReadAll(res.Body); err != nil { - log.Error("ioutil.ReadAll", err) - return err - } - log.Debug("data", string(b)) - if err = json.Unmarshal(b, &resp); err != nil { - log.Error("json.Unmarshal", err) - return err - } - if val, ok := resp["ErrorResponse"]; ok { - errstr := execTemplate("ErrorResponse", "{{.ErrorType}}: {{.ErrorMessage}}", val) - return errors.New(errstr) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/Commit.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/Commit.go deleted file mode 100644 index 2b23bb8..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/Commit.go +++ /dev/null @@ -1,44 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// Commit -type Commit struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) -} - -// URI /{{.DoServiceCode}}/commit.json -func (t Commit) URI() string { - return "/{{.DoServiceCode}}/commit.json" -} - -// APIName Commit -func (t Commit) APIName() string { - return "Commit" -} - -// Method PUT -func (t Commit) Method() string { - return "PUT" -} - -// http://manual.iij.jp/dns/doapi/754632.html -func (t Commit) Document() string { - return "http://manual.iij.jp/dns/doapi/754632.html" -} - -// JPName PUT Commit -func (t Commit) JPName() string { - return "PUT commit" -} -func init() { - APIlist = append(APIlist, Commit{}) - TypeMap["Commit"] = reflect.TypeOf(Commit{}) -} - -// CommitResponse PUT Commitのレスポンス -type CommitResponse struct { - *CommonResponse -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordAdd.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordAdd.go deleted file mode 100644 index 0f165b0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordAdd.go +++ /dev/null @@ -1,51 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// RecordAdd POST record (同期) -// http://manual.iij.jp/dns/doapi/754517.html -type RecordAdd struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) - ZoneName string `json:"-"` // Zone Name - Owner string // owner of record - TTL string // TTL of record - RecordType string // type of record - RData string // data of record -} - -// URI /:GisServiceCode/fw-lbs/:IflServiceCode/filters/:IpVersion/:Direction.json -func (t RecordAdd) URI() string { - return "/{{.DoServiceCode}}/{{.ZoneName}}/record.json" -} - -// APIName RecordAdd -func (t RecordAdd) APIName() string { - return "RecordAdd" -} - -// Method POST -func (t RecordAdd) Method() string { - return "POST" -} - -// http://manual.iij.jp/dns/doapi/754517.html -func (t RecordAdd) Document() string { - return "http://manual.iij.jp/dns/doapi/754517.html" -} - -// JPName POST record -func (t RecordAdd) JPName() string { - return "POST record" -} -func init() { - APIlist = append(APIlist, RecordAdd{}) - TypeMap["RecordAdd"] = reflect.TypeOf(RecordAdd{}) -} - -// RecordAddResponse POST recordのレスポンス -type RecordAddResponse struct { - *CommonResponse - Record ResourceRecord -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordDelete.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordDelete.go deleted file mode 100644 index 5d087df..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordDelete.go +++ /dev/null @@ -1,47 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// RecordDelete DELETE record -// http://manual.iij.jp/dns/doapi/754525.html -type RecordDelete struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) - ZoneName string `json:"-"` // Zone Name - RecordID string `json:"-"` // Record ID -} - -// URI /{{.DoServiceCode}}/{{.ZoneName}}/record/{{.RecordID}}.json -func (t RecordDelete) URI() string { - return "/{{.DoServiceCode}}/{{.ZoneName}}/record/{{.RecordID}}.json" -} - -// APIName RecordDelete -func (t RecordDelete) APIName() string { - return "RecordDelete" -} - -// Method DELETE -func (t RecordDelete) Method() string { - return "DELETE" -} - -// http://manual.iij.jp/dns/doapi/754525.html -func (t RecordDelete) Document() string { - return "http://manual.iij.jp/dns/doapi/754525.html" -} - -// JPName DELETE record -func (t RecordDelete) JPName() string { - return "DELETE record" -} -func init() { - APIlist = append(APIlist, RecordDelete{}) - TypeMap["RecordDelete"] = reflect.TypeOf(RecordDelete{}) -} - -// RecordDeleteResponse DELETE recordのレスポンス -type RecordDeleteResponse struct { - *CommonResponse -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordGet.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordGet.go deleted file mode 100644 index 051bb65..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordGet.go +++ /dev/null @@ -1,48 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// GET records -// http://manual.iij.jp/dns/doapi/754619.html -type RecordGet struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) - ZoneName string `json:"-"` // ゾーン名 - RecordID string `json:"-"` // -} - -// URI /{{.DoServiceCode}}/{{.ZoneName}}/record/{{.RecordID}}.json -func (t RecordGet) URI() string { - return "/{{.DoServiceCode}}/{{.ZoneName}}/record/{{.RecordID}}.json" -} - -// APIName RecordGet -func (t RecordGet) APIName() string { - return "RecordGet" -} - -// Method GET -func (t RecordGet) Method() string { - return "GET" -} - -// http://manual.iij.jp/dns/doapi/754503.html -func (t RecordGet) Document() string { - return "http://manual.iij.jp/dns/doapi/754503.html" -} - -// JPName GET record -func (t RecordGet) JPName() string { - return "GET record" -} -func init() { - APIlist = append(APIlist, RecordGet{}) - TypeMap["RecordGet"] = reflect.TypeOf(RecordGet{}) -} - -// RecordGetResponse フィルタリングルール情報取得のレスポンス -type RecordGetResponse struct { - *CommonResponse - Record ResourceRecord -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordListGet.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordListGet.go deleted file mode 100644 index 3e4b9d6..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/RecordListGet.go +++ /dev/null @@ -1,47 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// GET records -type RecordListGet struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) - ZoneName string `json:"-"` // ゾーン名 -} - -// URI /{{.DoServiceCode}}/{{.ZoneName}}/records/DETAIL.json -func (t RecordListGet) URI() string { - return "/{{.DoServiceCode}}/{{.ZoneName}}/records/DETAIL.json" -} - -// APIName RecordListGet -func (t RecordListGet) APIName() string { - return "RecordListGet" -} - -// Method GET -func (t RecordListGet) Method() string { - return "GET" -} - -// http://manual.iij.jp/dns/doapi/754619.html -func (t RecordListGet) Document() string { - return "http://manual.iij.jp/dns/doapi/754619.html" -} - -// JPName GET records -func (t RecordListGet) JPName() string { - return "GET records" -} -func init() { - APIlist = append(APIlist, RecordListGet{}) - TypeMap["RecordListGet"] = reflect.TypeOf(RecordListGet{}) -} - -// RecordListGetResponse GET recordsのレスポンス -type RecordListGetResponse struct { - *CommonResponse - RecordList []ResourceRecord - StaticRecordList []ResourceRecord -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/Reset.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/Reset.go deleted file mode 100644 index 0a26056..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/Reset.go +++ /dev/null @@ -1,45 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// Reset PUT reset (同期) -type Reset struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) - ZoneName string `json:"-"` // Zone name -} - -// URI /{{.DoServiceCode}}/{{.ZoneName}}/reset.json -func (t Reset) URI() string { - return "/{{.DoServiceCode}}/{{.ZoneName}}/reset.json" -} - -// APIName Reset -func (t Reset) APIName() string { - return "Reset" -} - -// Method PUT -func (t Reset) Method() string { - return "PUT" -} - -// http://manual.iij.jp/dns/doapi/754610.html -func (t Reset) Document() string { - return "http://manual.iij.jp/dns/doapi/754610.html" -} - -// JPName PUT reset -func (t Reset) JPName() string { - return "PUT Reset" -} -func init() { - APIlist = append(APIlist, Reset{}) - TypeMap["Reset"] = reflect.TypeOf(Reset{}) -} - -// ResetResponse PUT resetのレスポンス -type ResetResponse struct { - *CommonResponse -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/ZoneListGet.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/ZoneListGet.go deleted file mode 100644 index 20258a4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/ZoneListGet.go +++ /dev/null @@ -1,45 +0,0 @@ -package protocol - -import ( - "reflect" -) - -// GET zones -type ZoneListGet struct { - DoServiceCode string `json:"-"` // DO契約のサービスコード(do########) -} - -// URI /{{.DoServiceCode}}/zones.json -func (t ZoneListGet) URI() string { - return "/{{.DoServiceCode}}/zones.json" -} - -// APIName ZoneListGet -func (t ZoneListGet) APIName() string { - return "ZoneListGet" -} - -// Method GET -func (t ZoneListGet) Method() string { - return "GET" -} - -// http://manual.iij.jp/dns/doapi/754466.html -func (t ZoneListGet) Document() string { - return "http://manual.iij.jp/dns/doapi/754466.html" -} - -// JPName GET zones -func (t ZoneListGet) JPName() string { - return "GET zones" -} -func init() { - APIlist = append(APIlist, ZoneListGet{}) - TypeMap["ZoneListGet"] = reflect.TypeOf(ZoneListGet{}) -} - -// ZoneListGetResponse GET zonesのレスポンス -type ZoneListGetResponse struct { - *CommonResponse - ZoneList []string -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/common.go b/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/common.go deleted file mode 100644 index 77f7a2e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/iij/doapi/protocol/common.go +++ /dev/null @@ -1,53 +0,0 @@ -package protocol - -//go:generate python doc2struct.py - -import ( - "fmt" - "reflect" -) - -type CommonArg interface { - APIName() string - Method() string - URI() string - Document() string - JPName() string -} - -type CommonResponse struct { - RequestId string - ErrorResponse struct { - RequestId string - ErrorType string - ErrorMessage string - } -} - -var APIlist []CommonArg - -var TypeMap = map[string]reflect.Type{} - -type ResourceRecord struct { - Id string `json:",omitempty"` - Status string - Owner string - TTL string - RecordType string - RData string -} - -func (r *ResourceRecord) String() string { - return fmt.Sprintf("%s %s IN %s %s", r.Owner, r.TTL, r.RecordType, r.RData) -} - -func (r *ResourceRecord) FQDN(zone string) string { - return fmt.Sprintf("%s.%s %s IN %s %s", r.Owner, zone, r.TTL, r.RecordType, r.RData) -} - -const ( - UNCAHNGED = "UNCHANGED" - ADDING = "ADDING" - DELETING = "DELETING" - DELETED = "DELETED" -) diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/LICENSE deleted file mode 100644 index b03310a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015 James Saryerwinnie - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/api.go deleted file mode 100644 index 9cfa988..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/api.go +++ /dev/null @@ -1,49 +0,0 @@ -package jmespath - -import "strconv" - -// JmesPath is the epresentation of a compiled JMES path query. A JmesPath is -// safe for concurrent use by multiple goroutines. -type JMESPath struct { - ast ASTNode - intr *treeInterpreter -} - -// Compile parses a JMESPath expression and returns, if successful, a JMESPath -// object that can be used to match against data. -func Compile(expression string) (*JMESPath, error) { - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - jmespath := &JMESPath{ast: ast, intr: newInterpreter()} - return jmespath, nil -} - -// MustCompile is like Compile but panics if the expression cannot be parsed. -// It simplifies safe initialization of global variables holding compiled -// JMESPaths. -func MustCompile(expression string) *JMESPath { - jmespath, err := Compile(expression) - if err != nil { - panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) - } - return jmespath -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func (jp *JMESPath) Search(data interface{}) (interface{}, error) { - return jp.intr.Execute(jp.ast, data) -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func Search(expression string, data interface{}) (interface{}, error) { - intr := newInterpreter() - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - return intr.Execute(ast, data) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go deleted file mode 100644 index 1cd2d23..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type astNodeType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection" - -var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307} - -func (i astNodeType) String() string { - if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) { - return fmt.Sprintf("astNodeType(%d)", i) - } - return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/functions.go deleted file mode 100644 index 9b7cd89..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/functions.go +++ /dev/null @@ -1,842 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "unicode/utf8" -) - -type jpFunction func(arguments []interface{}) (interface{}, error) - -type jpType string - -const ( - jpUnknown jpType = "unknown" - jpNumber jpType = "number" - jpString jpType = "string" - jpArray jpType = "array" - jpObject jpType = "object" - jpArrayNumber jpType = "array[number]" - jpArrayString jpType = "array[string]" - jpExpref jpType = "expref" - jpAny jpType = "any" -) - -type functionEntry struct { - name string - arguments []argSpec - handler jpFunction - hasExpRef bool -} - -type argSpec struct { - types []jpType - variadic bool -} - -type byExprString struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprString) Len() int { - return len(a.items) -} -func (a *byExprString) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprString) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(string) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(string) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type byExprFloat struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprFloat) Len() int { - return len(a.items) -} -func (a *byExprFloat) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprFloat) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(float64) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(float64) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type functionCaller struct { - functionTable map[string]functionEntry -} - -func newFunctionCaller() *functionCaller { - caller := &functionCaller{} - caller.functionTable = map[string]functionEntry{ - "length": { - name: "length", - arguments: []argSpec{ - {types: []jpType{jpString, jpArray, jpObject}}, - }, - handler: jpfLength, - }, - "starts_with": { - name: "starts_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfStartsWith, - }, - "abs": { - name: "abs", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfAbs, - }, - "avg": { - name: "avg", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfAvg, - }, - "ceil": { - name: "ceil", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfCeil, - }, - "contains": { - name: "contains", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - {types: []jpType{jpAny}}, - }, - handler: jpfContains, - }, - "ends_with": { - name: "ends_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfEndsWith, - }, - "floor": { - name: "floor", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfFloor, - }, - "map": { - name: "amp", - arguments: []argSpec{ - {types: []jpType{jpExpref}}, - {types: []jpType{jpArray}}, - }, - handler: jpfMap, - hasExpRef: true, - }, - "max": { - name: "max", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMax, - }, - "merge": { - name: "merge", - arguments: []argSpec{ - {types: []jpType{jpObject}, variadic: true}, - }, - handler: jpfMerge, - }, - "max_by": { - name: "max_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMaxBy, - hasExpRef: true, - }, - "sum": { - name: "sum", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfSum, - }, - "min": { - name: "min", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMin, - }, - "min_by": { - name: "min_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMinBy, - hasExpRef: true, - }, - "type": { - name: "type", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfType, - }, - "keys": { - name: "keys", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfKeys, - }, - "values": { - name: "values", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfValues, - }, - "sort": { - name: "sort", - arguments: []argSpec{ - {types: []jpType{jpArrayString, jpArrayNumber}}, - }, - handler: jpfSort, - }, - "sort_by": { - name: "sort_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfSortBy, - hasExpRef: true, - }, - "join": { - name: "join", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpArrayString}}, - }, - handler: jpfJoin, - }, - "reverse": { - name: "reverse", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - }, - handler: jpfReverse, - }, - "to_array": { - name: "to_array", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToArray, - }, - "to_string": { - name: "to_string", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToString, - }, - "to_number": { - name: "to_number", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToNumber, - }, - "not_null": { - name: "not_null", - arguments: []argSpec{ - {types: []jpType{jpAny}, variadic: true}, - }, - handler: jpfNotNull, - }, - } - return caller -} - -func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) { - if len(e.arguments) == 0 { - return arguments, nil - } - if !e.arguments[len(e.arguments)-1].variadic { - if len(e.arguments) != len(arguments) { - return nil, errors.New("incorrect number of args") - } - for i, spec := range e.arguments { - userArg := arguments[i] - err := spec.typeCheck(userArg) - if err != nil { - return nil, err - } - } - return arguments, nil - } - if len(arguments) < len(e.arguments) { - return nil, errors.New("Invalid arity.") - } - return arguments, nil -} - -func (a *argSpec) typeCheck(arg interface{}) error { - for _, t := range a.types { - switch t { - case jpNumber: - if _, ok := arg.(float64); ok { - return nil - } - case jpString: - if _, ok := arg.(string); ok { - return nil - } - case jpArray: - if isSliceType(arg) { - return nil - } - case jpObject: - if _, ok := arg.(map[string]interface{}); ok { - return nil - } - case jpArrayNumber: - if _, ok := toArrayNum(arg); ok { - return nil - } - case jpArrayString: - if _, ok := toArrayStr(arg); ok { - return nil - } - case jpAny: - return nil - case jpExpref: - if _, ok := arg.(expRef); ok { - return nil - } - } - } - return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types) -} - -func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) { - entry, ok := f.functionTable[name] - if !ok { - return nil, errors.New("unknown function: " + name) - } - resolvedArgs, err := entry.resolveArgs(arguments) - if err != nil { - return nil, err - } - if entry.hasExpRef { - var extra []interface{} - extra = append(extra, intr) - resolvedArgs = append(extra, resolvedArgs...) - } - return entry.handler(resolvedArgs) -} - -func jpfAbs(arguments []interface{}) (interface{}, error) { - num := arguments[0].(float64) - return math.Abs(num), nil -} - -func jpfLength(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if c, ok := arg.(string); ok { - return float64(utf8.RuneCountInString(c)), nil - } else if isSliceType(arg) { - v := reflect.ValueOf(arg) - return float64(v.Len()), nil - } else if c, ok := arg.(map[string]interface{}); ok { - return float64(len(c)), nil - } - return nil, errors.New("could not compute length()") -} - -func jpfStartsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - prefix := arguments[1].(string) - return strings.HasPrefix(search, prefix), nil -} - -func jpfAvg(arguments []interface{}) (interface{}, error) { - // We've already type checked the value so we can safely use - // type assertions. - args := arguments[0].([]interface{}) - length := float64(len(args)) - numerator := 0.0 - for _, n := range args { - numerator += n.(float64) - } - return numerator / length, nil -} -func jpfCeil(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Ceil(val), nil -} -func jpfContains(arguments []interface{}) (interface{}, error) { - search := arguments[0] - el := arguments[1] - if searchStr, ok := search.(string); ok { - if elStr, ok := el.(string); ok { - return strings.Index(searchStr, elStr) != -1, nil - } - return false, nil - } - // Otherwise this is a generic contains for []interface{} - general := search.([]interface{}) - for _, item := range general { - if item == el { - return true, nil - } - } - return false, nil -} -func jpfEndsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - suffix := arguments[1].(string) - return strings.HasSuffix(search, suffix), nil -} -func jpfFloor(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Floor(val), nil -} -func jpfMap(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - exp := arguments[1].(expRef) - node := exp.ref - arr := arguments[2].([]interface{}) - mapped := make([]interface{}, 0, len(arr)) - for _, value := range arr { - current, err := intr.Execute(node, value) - if err != nil { - return nil, err - } - mapped = append(mapped, current) - } - return mapped, nil -} -func jpfMax(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil - } - // Otherwise we're dealing with a max() of strings. - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil -} -func jpfMerge(arguments []interface{}) (interface{}, error) { - final := make(map[string]interface{}) - for _, m := range arguments { - mapped := m.(map[string]interface{}) - for key, value := range mapped { - final[key] = value - } - } - return final, nil -} -func jpfMaxBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - switch t := start.(type) { - case float64: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - case string: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - default: - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfSum(arguments []interface{}) (interface{}, error) { - items, _ := toArrayNum(arguments[0]) - sum := 0.0 - for _, item := range items { - sum += item - } - return sum, nil -} - -func jpfMin(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil - } - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil -} - -func jpfMinBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if t, ok := start.(float64); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else if t, ok := start.(string); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfType(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if _, ok := arg.(float64); ok { - return "number", nil - } - if _, ok := arg.(string); ok { - return "string", nil - } - if _, ok := arg.([]interface{}); ok { - return "array", nil - } - if _, ok := arg.(map[string]interface{}); ok { - return "object", nil - } - if arg == nil { - return "null", nil - } - if arg == true || arg == false { - return "boolean", nil - } - return nil, errors.New("unknown type") -} -func jpfKeys(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for key := range arg { - collected = append(collected, key) - } - return collected, nil -} -func jpfValues(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for _, value := range arg { - collected = append(collected, value) - } - return collected, nil -} -func jpfSort(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - d := sort.Float64Slice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil - } - // Otherwise we're dealing with sort()'ing strings. - items, _ := toArrayStr(arguments[0]) - d := sort.StringSlice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil -} -func jpfSortBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return arr, nil - } else if len(arr) == 1 { - return arr, nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if _, ok := start.(float64); ok { - sortable := &byExprFloat{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else if _, ok := start.(string); ok { - sortable := &byExprString{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfJoin(arguments []interface{}) (interface{}, error) { - sep := arguments[0].(string) - // We can't just do arguments[1].([]string), we have to - // manually convert each item to a string. - arrayStr := []string{} - for _, item := range arguments[1].([]interface{}) { - arrayStr = append(arrayStr, item.(string)) - } - return strings.Join(arrayStr, sep), nil -} -func jpfReverse(arguments []interface{}) (interface{}, error) { - if s, ok := arguments[0].(string); ok { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r), nil - } - items := arguments[0].([]interface{}) - length := len(items) - reversed := make([]interface{}, length) - for i, item := range items { - reversed[length-(i+1)] = item - } - return reversed, nil -} -func jpfToArray(arguments []interface{}) (interface{}, error) { - if _, ok := arguments[0].([]interface{}); ok { - return arguments[0], nil - } - return arguments[:1:1], nil -} -func jpfToString(arguments []interface{}) (interface{}, error) { - if v, ok := arguments[0].(string); ok { - return v, nil - } - result, err := json.Marshal(arguments[0]) - if err != nil { - return nil, err - } - return string(result), nil -} -func jpfToNumber(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if v, ok := arg.(float64); ok { - return v, nil - } - if v, ok := arg.(string); ok { - conv, err := strconv.ParseFloat(v, 64) - if err != nil { - return nil, nil - } - return conv, nil - } - if _, ok := arg.([]interface{}); ok { - return nil, nil - } - if _, ok := arg.(map[string]interface{}); ok { - return nil, nil - } - if arg == nil { - return nil, nil - } - if arg == true || arg == false { - return nil, nil - } - return nil, errors.New("unknown type") -} -func jpfNotNull(arguments []interface{}) (interface{}, error) { - for _, arg := range arguments { - if arg != nil { - return arg, nil - } - } - return nil, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/interpreter.go deleted file mode 100644 index 13c7460..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/interpreter.go +++ /dev/null @@ -1,418 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" - "unicode" - "unicode/utf8" -) - -/* This is a tree based interpreter. It walks the AST and directly - interprets the AST to search through a JSON document. -*/ - -type treeInterpreter struct { - fCall *functionCaller -} - -func newInterpreter() *treeInterpreter { - interpreter := treeInterpreter{} - interpreter.fCall = newFunctionCaller() - return &interpreter -} - -type expRef struct { - ref ASTNode -} - -// Execute takes an ASTNode and input data and interprets the AST directly. -// It will produce the result of applying the JMESPath expression associated -// with the ASTNode to the input data "value". -func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) { - switch node.nodeType { - case ASTComparator: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - right, err := intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - switch node.value { - case tEQ: - return objsEqual(left, right), nil - case tNE: - return !objsEqual(left, right), nil - } - leftNum, ok := left.(float64) - if !ok { - return nil, nil - } - rightNum, ok := right.(float64) - if !ok { - return nil, nil - } - switch node.value { - case tGT: - return leftNum > rightNum, nil - case tGTE: - return leftNum >= rightNum, nil - case tLT: - return leftNum < rightNum, nil - case tLTE: - return leftNum <= rightNum, nil - } - case ASTExpRef: - return expRef{ref: node.children[0]}, nil - case ASTFunctionExpression: - resolvedArgs := []interface{}{} - for _, arg := range node.children { - current, err := intr.Execute(arg, value) - if err != nil { - return nil, err - } - resolvedArgs = append(resolvedArgs, current) - } - return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr) - case ASTField: - if m, ok := value.(map[string]interface{}); ok { - key := node.value.(string) - return m[key], nil - } - return intr.fieldFromStruct(node.value.(string), value) - case ASTFilterProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.filterProjectionWithReflection(node, left) - } - return nil, nil - } - compareNode := node.children[2] - collected := []interface{}{} - for _, element := range sliceType { - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil - case ASTFlatten: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - // If we can't type convert to []interface{}, there's - // a chance this could still work via reflection if we're - // dealing with user provided types. - if isSliceType(left) { - return intr.flattenWithReflection(left) - } - return nil, nil - } - flattened := []interface{}{} - for _, element := range sliceType { - if elementSlice, ok := element.([]interface{}); ok { - flattened = append(flattened, elementSlice...) - } else if isSliceType(element) { - reflectFlat := []interface{}{} - v := reflect.ValueOf(element) - for i := 0; i < v.Len(); i++ { - reflectFlat = append(reflectFlat, v.Index(i).Interface()) - } - flattened = append(flattened, reflectFlat...) - } else { - flattened = append(flattened, element) - } - } - return flattened, nil - case ASTIdentity, ASTCurrentNode: - return value, nil - case ASTIndex: - if sliceType, ok := value.([]interface{}); ok { - index := node.value.(int) - if index < 0 { - index += len(sliceType) - } - if index < len(sliceType) && index >= 0 { - return sliceType[index], nil - } - return nil, nil - } - // Otherwise try via reflection. - rv := reflect.ValueOf(value) - if rv.Kind() == reflect.Slice { - index := node.value.(int) - if index < 0 { - index += rv.Len() - } - if index < rv.Len() && index >= 0 { - v := rv.Index(index) - return v.Interface(), nil - } - } - return nil, nil - case ASTKeyValPair: - return intr.Execute(node.children[0], value) - case ASTLiteral: - return node.value, nil - case ASTMultiSelectHash: - if value == nil { - return nil, nil - } - collected := make(map[string]interface{}) - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - key := child.value.(string) - collected[key] = current - } - return collected, nil - case ASTMultiSelectList: - if value == nil { - return nil, nil - } - collected := []interface{}{} - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - collected = append(collected, current) - } - return collected, nil - case ASTOrExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - matched, err = intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - } - return matched, nil - case ASTAndExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return matched, nil - } - return intr.Execute(node.children[1], value) - case ASTNotExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return true, nil - } - return false, nil - case ASTPipe: - result := value - var err error - for _, child := range node.children { - result, err = intr.Execute(child, result) - if err != nil { - return nil, err - } - } - return result, nil - case ASTProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.projectWithReflection(node, left) - } - return nil, nil - } - collected := []interface{}{} - var current interface{} - for _, element := range sliceType { - current, err = intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - case ASTSubexpression, ASTIndexExpression: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - return intr.Execute(node.children[1], left) - case ASTSlice: - sliceType, ok := value.([]interface{}) - if !ok { - if isSliceType(value) { - return intr.sliceWithReflection(node, value) - } - return nil, nil - } - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - return slice(sliceType, sliceParams) - case ASTValueProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - mapType, ok := left.(map[string]interface{}) - if !ok { - return nil, nil - } - values := make([]interface{}, len(mapType)) - for _, value := range mapType { - values = append(values, value) - } - collected := []interface{}{} - for _, element := range values { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - } - return nil, errors.New("Unknown AST node: " + node.nodeType.String()) -} - -func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) { - rv := reflect.ValueOf(value) - first, n := utf8.DecodeRuneInString(key) - fieldName := string(unicode.ToUpper(first)) + key[n:] - if rv.Kind() == reflect.Struct { - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } else if rv.Kind() == reflect.Ptr { - // Handle multiple levels of indirection? - if rv.IsNil() { - return nil, nil - } - rv = rv.Elem() - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } - return nil, nil -} - -func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - flattened := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - if reflect.TypeOf(element).Kind() == reflect.Slice { - // Then insert the contents of the element - // slice into the flattened slice, - // i.e flattened = append(flattened, mySlice...) - elementV := reflect.ValueOf(element) - for j := 0; j < elementV.Len(); j++ { - flattened = append( - flattened, elementV.Index(j).Interface()) - } - } else { - flattened = append(flattened, element) - } - } - return flattened, nil -} - -func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - final := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - final = append(final, element) - } - return slice(final, sliceParams) -} - -func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) { - compareNode := node.children[2] - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil -} - -func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) { - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if result != nil { - collected = append(collected, result) - } - } - return collected, nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/lexer.go deleted file mode 100644 index 817900c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/lexer.go +++ /dev/null @@ -1,420 +0,0 @@ -package jmespath - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - "unicode/utf8" -) - -type token struct { - tokenType tokType - value string - position int - length int -} - -type tokType int - -const eof = -1 - -// Lexer contains information about the expression being tokenized. -type Lexer struct { - expression string // The expression provided by the user. - currentPos int // The current position in the string. - lastWidth int // The width of the current rune. This - buf bytes.Buffer // Internal buffer used for building up values. -} - -// SyntaxError is the main error used whenever a lexing or parsing error occurs. -type SyntaxError struct { - msg string // Error message displayed to user - Expression string // Expression that generated a SyntaxError - Offset int // The location in the string where the error occurred -} - -func (e SyntaxError) Error() string { - // In the future, it would be good to underline the specific - // location where the error occurred. - return "SyntaxError: " + e.msg -} - -// HighlightLocation will show where the syntax error occurred. -// It will place a "^" character on a line below the expression -// at the point where the syntax error occurred. -func (e SyntaxError) HighlightLocation() string { - return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^" -} - -//go:generate stringer -type=tokType -const ( - tUnknown tokType = iota - tStar - tDot - tFilter - tFlatten - tLparen - tRparen - tLbracket - tRbracket - tLbrace - tRbrace - tOr - tPipe - tNumber - tUnquotedIdentifier - tQuotedIdentifier - tComma - tColon - tLT - tLTE - tGT - tGTE - tEQ - tNE - tJSONLiteral - tStringLiteral - tCurrent - tExpref - tAnd - tNot - tEOF -) - -var basicTokens = map[rune]tokType{ - '.': tDot, - '*': tStar, - ',': tComma, - ':': tColon, - '{': tLbrace, - '}': tRbrace, - ']': tRbracket, // tLbracket not included because it could be "[]" - '(': tLparen, - ')': tRparen, - '@': tCurrent, -} - -// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64. -// When using this bitmask just be sure to shift the rune down 64 bits -// before checking against identifierStartBits. -const identifierStartBits uint64 = 576460745995190270 - -// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s. -var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270} - -var whiteSpace = map[rune]bool{ - ' ': true, '\t': true, '\n': true, '\r': true, -} - -func (t token) String() string { - return fmt.Sprintf("Token{%+v, %s, %d, %d}", - t.tokenType, t.value, t.position, t.length) -} - -// NewLexer creates a new JMESPath lexer. -func NewLexer() *Lexer { - lexer := Lexer{} - return &lexer -} - -func (lexer *Lexer) next() rune { - if lexer.currentPos >= len(lexer.expression) { - lexer.lastWidth = 0 - return eof - } - r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:]) - lexer.lastWidth = w - lexer.currentPos += w - return r -} - -func (lexer *Lexer) back() { - lexer.currentPos -= lexer.lastWidth -} - -func (lexer *Lexer) peek() rune { - t := lexer.next() - lexer.back() - return t -} - -// tokenize takes an expression and returns corresponding tokens. -func (lexer *Lexer) tokenize(expression string) ([]token, error) { - var tokens []token - lexer.expression = expression - lexer.currentPos = 0 - lexer.lastWidth = 0 -loop: - for { - r := lexer.next() - if identifierStartBits&(1<<(uint64(r)-64)) > 0 { - t := lexer.consumeUnquotedIdentifier() - tokens = append(tokens, t) - } else if val, ok := basicTokens[r]; ok { - // Basic single char token. - t := token{ - tokenType: val, - value: string(r), - position: lexer.currentPos - lexer.lastWidth, - length: 1, - } - tokens = append(tokens, t) - } else if r == '-' || (r >= '0' && r <= '9') { - t := lexer.consumeNumber() - tokens = append(tokens, t) - } else if r == '[' { - t := lexer.consumeLBracket() - tokens = append(tokens, t) - } else if r == '"' { - t, err := lexer.consumeQuotedIdentifier() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '\'' { - t, err := lexer.consumeRawStringLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '`' { - t, err := lexer.consumeLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '|' { - t := lexer.matchOrElse(r, '|', tOr, tPipe) - tokens = append(tokens, t) - } else if r == '<' { - t := lexer.matchOrElse(r, '=', tLTE, tLT) - tokens = append(tokens, t) - } else if r == '>' { - t := lexer.matchOrElse(r, '=', tGTE, tGT) - tokens = append(tokens, t) - } else if r == '!' { - t := lexer.matchOrElse(r, '=', tNE, tNot) - tokens = append(tokens, t) - } else if r == '=' { - t := lexer.matchOrElse(r, '=', tEQ, tUnknown) - tokens = append(tokens, t) - } else if r == '&' { - t := lexer.matchOrElse(r, '&', tAnd, tExpref) - tokens = append(tokens, t) - } else if r == eof { - break loop - } else if _, ok := whiteSpace[r]; ok { - // Ignore whitespace - } else { - return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) - } - } - tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) - return tokens, nil -} - -// Consume characters until the ending rune "r" is reached. -// If the end of the expression is reached before seeing the -// terminating rune "r", then an error is returned. -// If no error occurs then the matching substring is returned. -// The returned string will not include the ending rune. -func (lexer *Lexer) consumeUntil(end rune) (string, error) { - start := lexer.currentPos - current := lexer.next() - for current != end && current != eof { - if current == '\\' && lexer.peek() != eof { - lexer.next() - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return "", SyntaxError{ - msg: "Unclosed delimiter: " + string(end), - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil -} - -func (lexer *Lexer) consumeLiteral() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('`') - if err != nil { - return token{}, err - } - value = strings.Replace(value, "\\`", "`", -1) - return token{ - tokenType: tJSONLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) consumeRawStringLiteral() (token, error) { - start := lexer.currentPos - currentIndex := start - current := lexer.next() - for current != '\'' && lexer.peek() != eof { - if current == '\\' && lexer.peek() == '\'' { - chunk := lexer.expression[currentIndex : lexer.currentPos-1] - lexer.buf.WriteString(chunk) - lexer.buf.WriteString("'") - lexer.next() - currentIndex = lexer.currentPos - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return token{}, SyntaxError{ - msg: "Unclosed delimiter: '", - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - if currentIndex < lexer.currentPos { - lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1]) - } - value := lexer.buf.String() - // Reset the buffer so it can reused again. - lexer.buf.Reset() - return token{ - tokenType: tStringLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: lexer.expression, - Offset: lexer.currentPos - 1, - } -} - -// Checks for a two char token, otherwise matches a single character -// token. This is used whenever a two char token overlaps a single -// char token, e.g. "||" -> tPipe, "|" -> tOr. -func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token { - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == second { - t = token{ - tokenType: matchedType, - value: string(first) + string(second), - position: start, - length: 2, - } - } else { - lexer.back() - t = token{ - tokenType: singleCharType, - value: string(first), - position: start, - length: 1, - } - } - return t -} - -func (lexer *Lexer) consumeLBracket() token { - // There's three options here: - // 1. A filter expression "[?" - // 2. A flatten operator "[]" - // 3. A bare rbracket "[" - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == '?' { - t = token{ - tokenType: tFilter, - value: "[?", - position: start, - length: 2, - } - } else if nextRune == ']' { - t = token{ - tokenType: tFlatten, - value: "[]", - position: start, - length: 2, - } - } else { - t = token{ - tokenType: tLbracket, - value: "[", - position: start, - length: 1, - } - lexer.back() - } - return t -} - -func (lexer *Lexer) consumeQuotedIdentifier() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('"') - if err != nil { - return token{}, err - } - var decoded string - asJSON := []byte("\"" + value + "\"") - if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil { - return token{}, err - } - return token{ - tokenType: tQuotedIdentifier, - value: decoded, - position: start - 1, - length: len(decoded), - }, nil -} - -func (lexer *Lexer) consumeUnquotedIdentifier() token { - // Consume runes until we reach the end of an unquoted - // identifier. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tUnquotedIdentifier, - value: value, - position: start, - length: lexer.currentPos - start, - } -} - -func (lexer *Lexer) consumeNumber() token { - // Consume runes until we reach something that's not a number. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < '0' || r > '9' { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tNumber, - value: value, - position: start, - length: lexer.currentPos - start, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/parser.go deleted file mode 100644 index 1240a17..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/parser.go +++ /dev/null @@ -1,603 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" -) - -type astNodeType int - -//go:generate stringer -type astNodeType -const ( - ASTEmpty astNodeType = iota - ASTComparator - ASTCurrentNode - ASTExpRef - ASTFunctionExpression - ASTField - ASTFilterProjection - ASTFlatten - ASTIdentity - ASTIndex - ASTIndexExpression - ASTKeyValPair - ASTLiteral - ASTMultiSelectHash - ASTMultiSelectList - ASTOrExpression - ASTAndExpression - ASTNotExpression - ASTPipe - ASTProjection - ASTSubexpression - ASTSlice - ASTValueProjection -) - -// ASTNode represents the abstract syntax tree of a JMESPath expression. -type ASTNode struct { - nodeType astNodeType - value interface{} - children []ASTNode -} - -func (node ASTNode) String() string { - return node.PrettyPrint(0) -} - -// PrettyPrint will pretty print the parsed AST. -// The AST is an implementation detail and this pretty print -// function is provided as a convenience method to help with -// debugging. You should not rely on its output as the internal -// structure of the AST may change at any time. -func (node ASTNode) PrettyPrint(indent int) string { - spaces := strings.Repeat(" ", indent) - output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType) - nextIndent := indent + 2 - if node.value != nil { - if converted, ok := node.value.(fmt.Stringer); ok { - // Account for things like comparator nodes - // that are enums with a String() method. - output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String()) - } else { - output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value) - } - } - lastIndex := len(node.children) - if lastIndex > 0 { - output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent)) - childIndent := nextIndent + 2 - for _, elem := range node.children { - output += elem.PrettyPrint(childIndent) - } - } - output += fmt.Sprintf("%s}\n", spaces) - return output -} - -var bindingPowers = map[tokType]int{ - tEOF: 0, - tUnquotedIdentifier: 0, - tQuotedIdentifier: 0, - tRbracket: 0, - tRparen: 0, - tComma: 0, - tRbrace: 0, - tNumber: 0, - tCurrent: 0, - tExpref: 0, - tColon: 0, - tPipe: 1, - tOr: 2, - tAnd: 3, - tEQ: 5, - tLT: 5, - tLTE: 5, - tGT: 5, - tGTE: 5, - tNE: 5, - tFlatten: 9, - tStar: 20, - tFilter: 21, - tDot: 40, - tNot: 45, - tLbrace: 50, - tLbracket: 55, - tLparen: 60, -} - -// Parser holds state about the current expression being parsed. -type Parser struct { - expression string - tokens []token - index int -} - -// NewParser creates a new JMESPath parser. -func NewParser() *Parser { - p := Parser{} - return &p -} - -// Parse will compile a JMESPath expression. -func (p *Parser) Parse(expression string) (ASTNode, error) { - lexer := NewLexer() - p.expression = expression - p.index = 0 - tokens, err := lexer.tokenize(expression) - if err != nil { - return ASTNode{}, err - } - p.tokens = tokens - parsed, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() != tEOF { - return ASTNode{}, p.syntaxError(fmt.Sprintf( - "Unexpected token at the end of the expresssion: %s", p.current())) - } - return parsed, nil -} - -func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) { - var err error - leftToken := p.lookaheadToken(0) - p.advance() - leftNode, err := p.nud(leftToken) - if err != nil { - return ASTNode{}, err - } - currentToken := p.current() - for bindingPower < bindingPowers[currentToken] { - p.advance() - leftNode, err = p.led(currentToken, leftNode) - if err != nil { - return ASTNode{}, err - } - currentToken = p.current() - } - return leftNode, nil -} - -func (p *Parser) parseIndexExpression() (ASTNode, error) { - if p.lookahead(0) == tColon || p.lookahead(1) == tColon { - return p.parseSliceExpression() - } - indexStr := p.lookaheadToken(0).value - parsedInt, err := strconv.Atoi(indexStr) - if err != nil { - return ASTNode{}, err - } - indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt} - p.advance() - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return indexNode, nil -} - -func (p *Parser) parseSliceExpression() (ASTNode, error) { - parts := []*int{nil, nil, nil} - index := 0 - current := p.current() - for current != tRbracket && index < 3 { - if current == tColon { - index++ - p.advance() - } else if current == tNumber { - parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value) - if err != nil { - return ASTNode{}, err - } - parts[index] = &parsedInt - p.advance() - } else { - return ASTNode{}, p.syntaxError( - "Expected tColon or tNumber" + ", received: " + p.current().String()) - } - current = p.current() - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTSlice, - value: parts, - }, nil -} - -func (p *Parser) match(tokenType tokType) error { - if p.current() == tokenType { - p.advance() - return nil - } - return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String()) -} - -func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) { - switch tokenType { - case tDot: - if p.current() != tStar { - right, err := p.parseDotRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTSubexpression, - children: []ASTNode{node, right}, - }, err - } - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTValueProjection, - children: []ASTNode{node, right}, - }, err - case tPipe: - right, err := p.parseExpression(bindingPowers[tPipe]) - return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err - case tOr: - right, err := p.parseExpression(bindingPowers[tOr]) - return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err - case tAnd: - right, err := p.parseExpression(bindingPowers[tAnd]) - return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err - case tLparen: - name := node.value - var args []ASTNode - for p.current() != tRparen { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() == tComma { - if err := p.match(tComma); err != nil { - return ASTNode{}, err - } - } - args = append(args, expression) - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTFunctionExpression, - value: name, - children: args, - }, nil - case tFilter: - return p.parseFilter(node) - case tFlatten: - left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}} - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{left, right}, - }, err - case tEQ, tNE, tGT, tGTE, tLT, tLTE: - right, err := p.parseExpression(bindingPowers[tokenType]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTComparator, - value: tokenType, - children: []ASTNode{node, right}, - }, nil - case tLbracket: - tokenType := p.current() - var right ASTNode - var err error - if tokenType == tNumber || tokenType == tColon { - right, err = p.parseIndexExpression() - if err != nil { - return ASTNode{}, err - } - return p.projectIfSlice(node, right) - } - // Otherwise this is a projection. - if err := p.match(tStar); err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{node, right}, - }, nil - } - return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String()) -} - -func (p *Parser) nud(token token) (ASTNode, error) { - switch token.tokenType { - case tJSONLiteral: - var parsed interface{} - err := json.Unmarshal([]byte(token.value), &parsed) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTLiteral, value: parsed}, nil - case tStringLiteral: - return ASTNode{nodeType: ASTLiteral, value: token.value}, nil - case tUnquotedIdentifier: - return ASTNode{ - nodeType: ASTField, - value: token.value, - }, nil - case tQuotedIdentifier: - node := ASTNode{nodeType: ASTField, value: token.value} - if p.current() == tLparen { - return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token) - } - return node, nil - case tStar: - left := ASTNode{nodeType: ASTIdentity} - var right ASTNode - var err error - if p.current() == tRbracket { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - } - return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err - case tFilter: - return p.parseFilter(ASTNode{nodeType: ASTIdentity}) - case tLbrace: - return p.parseMultiSelectHash() - case tFlatten: - left := ASTNode{ - nodeType: ASTFlatten, - children: []ASTNode{{nodeType: ASTIdentity}}, - } - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil - case tLbracket: - tokenType := p.current() - //var right ASTNode - if tokenType == tNumber || tokenType == tColon { - right, err := p.parseIndexExpression() - if err != nil { - return ASTNode{}, nil - } - return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right) - } else if tokenType == tStar && p.lookahead(1) == tRbracket { - p.advance() - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{{nodeType: ASTIdentity}, right}, - }, nil - } else { - return p.parseMultiSelectList() - } - case tCurrent: - return ASTNode{nodeType: ASTCurrentNode}, nil - case tExpref: - expression, err := p.parseExpression(bindingPowers[tExpref]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil - case tNot: - expression, err := p.parseExpression(bindingPowers[tNot]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil - case tLparen: - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return expression, nil - case tEOF: - return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token) - } - - return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token) -} - -func (p *Parser) parseMultiSelectList() (ASTNode, error) { - var expressions []ASTNode - for { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - expressions = append(expressions, expression) - if p.current() == tRbracket { - break - } - err = p.match(tComma) - if err != nil { - return ASTNode{}, err - } - } - err := p.match(tRbracket) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTMultiSelectList, - children: expressions, - }, nil -} - -func (p *Parser) parseMultiSelectHash() (ASTNode, error) { - var children []ASTNode - for { - keyToken := p.lookaheadToken(0) - if err := p.match(tUnquotedIdentifier); err != nil { - if err := p.match(tQuotedIdentifier); err != nil { - return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier") - } - } - keyName := keyToken.value - err := p.match(tColon) - if err != nil { - return ASTNode{}, err - } - value, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - node := ASTNode{ - nodeType: ASTKeyValPair, - value: keyName, - children: []ASTNode{value}, - } - children = append(children, node) - if p.current() == tComma { - err := p.match(tComma) - if err != nil { - return ASTNode{}, nil - } - } else if p.current() == tRbrace { - err := p.match(tRbrace) - if err != nil { - return ASTNode{}, nil - } - break - } - } - return ASTNode{ - nodeType: ASTMultiSelectHash, - children: children, - }, nil -} - -func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) { - indexExpr := ASTNode{ - nodeType: ASTIndexExpression, - children: []ASTNode{left, right}, - } - if right.nodeType == ASTSlice { - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{indexExpr, right}, - }, err - } - return indexExpr, nil -} -func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) { - var right, condition ASTNode - var err error - condition, err = p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - if p.current() == tFlatten { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tFilter]) - if err != nil { - return ASTNode{}, err - } - } - - return ASTNode{ - nodeType: ASTFilterProjection, - children: []ASTNode{node, right, condition}, - }, nil -} - -func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) { - lookahead := p.current() - if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) { - return p.parseExpression(bindingPower) - } else if lookahead == tLbracket { - if err := p.match(tLbracket); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectList() - } else if lookahead == tLbrace { - if err := p.match(tLbrace); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectHash() - } - return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace") -} - -func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) { - current := p.current() - if bindingPowers[current] < 10 { - return ASTNode{nodeType: ASTIdentity}, nil - } else if current == tLbracket { - return p.parseExpression(bindingPower) - } else if current == tFilter { - return p.parseExpression(bindingPower) - } else if current == tDot { - err := p.match(tDot) - if err != nil { - return ASTNode{}, err - } - return p.parseDotRHS(bindingPower) - } else { - return ASTNode{}, p.syntaxError("Error") - } -} - -func (p *Parser) lookahead(number int) tokType { - return p.lookaheadToken(number).tokenType -} - -func (p *Parser) current() tokType { - return p.lookahead(0) -} - -func (p *Parser) lookaheadToken(number int) token { - return p.tokens[p.index+number] -} - -func (p *Parser) advance() { - p.index++ -} - -func tokensOneOf(elements []tokType, token tokType) bool { - for _, elem := range elements { - if elem == token { - return true - } - } - return false -} - -func (p *Parser) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: p.lookaheadToken(0).position, - } -} - -// Create a SyntaxError based on the provided token. -// This differs from syntaxError() which creates a SyntaxError -// based on the current lookahead token. -func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: t.position, - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/toktype_string.go deleted file mode 100644 index dae79cb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/toktype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type=tokType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF" - -var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214} - -func (i tokType) String() string { - if i < 0 || i >= tokType(len(_tokType_index)-1) { - return fmt.Sprintf("tokType(%d)", i) - } - return _tokType_name[_tokType_index[i]:_tokType_index[i+1]] -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/util.go deleted file mode 100644 index ddc1b7d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/jmespath/go-jmespath/util.go +++ /dev/null @@ -1,185 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" -) - -// IsFalse determines if an object is false based on the JMESPath spec. -// JMESPath defines false values to be any of: -// - An empty string array, or hash. -// - The boolean value false. -// - nil -func isFalse(value interface{}) bool { - switch v := value.(type) { - case bool: - return !v - case []interface{}: - return len(v) == 0 - case map[string]interface{}: - return len(v) == 0 - case string: - return len(v) == 0 - case nil: - return true - } - // Try the reflection cases before returning false. - rv := reflect.ValueOf(value) - switch rv.Kind() { - case reflect.Struct: - // A struct type will never be false, even if - // all of its values are the zero type. - return false - case reflect.Slice, reflect.Map: - return rv.Len() == 0 - case reflect.Ptr: - if rv.IsNil() { - return true - } - // If it's a pointer type, we'll try to deref the pointer - // and evaluate the pointer value for isFalse. - element := rv.Elem() - return isFalse(element.Interface()) - } - return false -} - -// ObjsEqual is a generic object equality check. -// It will take two arbitrary objects and recursively determine -// if they are equal. -func objsEqual(left interface{}, right interface{}) bool { - return reflect.DeepEqual(left, right) -} - -// SliceParam refers to a single part of a slice. -// A slice consists of a start, a stop, and a step, similar to -// python slices. -type sliceParam struct { - N int - Specified bool -} - -// Slice supports [start:stop:step] style slicing that's supported in JMESPath. -func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) { - computed, err := computeSliceParams(len(slice), parts) - if err != nil { - return nil, err - } - start, stop, step := computed[0], computed[1], computed[2] - result := []interface{}{} - if step > 0 { - for i := start; i < stop; i += step { - result = append(result, slice[i]) - } - } else { - for i := start; i > stop; i += step { - result = append(result, slice[i]) - } - } - return result, nil -} - -func computeSliceParams(length int, parts []sliceParam) ([]int, error) { - var start, stop, step int - if !parts[2].Specified { - step = 1 - } else if parts[2].N == 0 { - return nil, errors.New("Invalid slice, step cannot be 0") - } else { - step = parts[2].N - } - var stepValueNegative bool - if step < 0 { - stepValueNegative = true - } else { - stepValueNegative = false - } - - if !parts[0].Specified { - if stepValueNegative { - start = length - 1 - } else { - start = 0 - } - } else { - start = capSlice(length, parts[0].N, step) - } - - if !parts[1].Specified { - if stepValueNegative { - stop = -1 - } else { - stop = length - } - } else { - stop = capSlice(length, parts[1].N, step) - } - return []int{start, stop, step}, nil -} - -func capSlice(length int, actual int, step int) int { - if actual < 0 { - actual += length - if actual < 0 { - if step < 0 { - actual = -1 - } else { - actual = 0 - } - } - } else if actual >= length { - if step < 0 { - actual = length - 1 - } else { - actual = length - } - } - return actual -} - -// ToArrayNum converts an empty interface type to a slice of float64. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. -func toArrayNum(data interface{}) ([]float64, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]float64, len(d)) - for i, el := range d { - item, ok := el.(float64) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -// ToArrayStr converts an empty interface type to a slice of strings. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. If the input data could be entirely -// converted, then the converted data, along with a second value of true, -// will be returned. -func toArrayStr(data interface{}) ([]string, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]string, len(d)) - for i, el := range d { - item, ok := el.(string) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -func isSliceType(v interface{}) bool { - if v == nil { - return false - } - return reflect.TypeOf(v).Kind() == reflect.Slice -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/LICENSE b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/LICENSE deleted file mode 100644 index 2cf4f5a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 json-iterator - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/adapter.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/adapter.go deleted file mode 100644 index e674d0f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/adapter.go +++ /dev/null @@ -1,150 +0,0 @@ -package jsoniter - -import ( - "bytes" - "io" -) - -// RawMessage to make replace json with jsoniter -type RawMessage []byte - -// Unmarshal adapts to json/encoding Unmarshal API -// -// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. -// Refer to https://godoc.org/encoding/json#Unmarshal for more information -func Unmarshal(data []byte, v interface{}) error { - return ConfigDefault.Unmarshal(data, v) -} - -// UnmarshalFromString convenient method to read from string instead of []byte -func UnmarshalFromString(str string, v interface{}) error { - return ConfigDefault.UnmarshalFromString(str, v) -} - -// Get quick method to get value from deeply nested JSON structure -func Get(data []byte, path ...interface{}) Any { - return ConfigDefault.Get(data, path...) -} - -// Marshal adapts to json/encoding Marshal API -// -// Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API -// Refer to https://godoc.org/encoding/json#Marshal for more information -func Marshal(v interface{}) ([]byte, error) { - return ConfigDefault.Marshal(v) -} - -// MarshalIndent same as json.MarshalIndent. Prefix is not supported. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - return ConfigDefault.MarshalIndent(v, prefix, indent) -} - -// MarshalToString convenient method to write as string instead of []byte -func MarshalToString(v interface{}) (string, error) { - return ConfigDefault.MarshalToString(v) -} - -// NewDecoder adapts to json/stream NewDecoder API. -// -// NewDecoder returns a new decoder that reads from r. -// -// Instead of a json/encoding Decoder, an Decoder is returned -// Refer to https://godoc.org/encoding/json#NewDecoder for more information -func NewDecoder(reader io.Reader) *Decoder { - return ConfigDefault.NewDecoder(reader) -} - -// Decoder reads and decodes JSON values from an input stream. -// Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress) -type Decoder struct { - iter *Iterator -} - -// Decode decode JSON into interface{} -func (adapter *Decoder) Decode(obj interface{}) error { - if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil { - if !adapter.iter.loadMore() { - return io.EOF - } - } - adapter.iter.ReadVal(obj) - err := adapter.iter.Error - if err == io.EOF { - return nil - } - return adapter.iter.Error -} - -// More is there more? -func (adapter *Decoder) More() bool { - iter := adapter.iter - if iter.Error != nil { - return false - } - c := iter.nextToken() - if c == 0 { - return false - } - iter.unreadByte() - return c != ']' && c != '}' -} - -// Buffered remaining buffer -func (adapter *Decoder) Buffered() io.Reader { - remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail] - return bytes.NewReader(remaining) -} - -// UseNumber causes the Decoder to unmarshal a number into an interface{} as a -// Number instead of as a float64. -func (adapter *Decoder) UseNumber() { - cfg := adapter.iter.cfg.configBeforeFrozen - cfg.UseNumber = true - adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) -} - -// DisallowUnknownFields causes the Decoder to return an error when the destination -// is a struct and the input contains object keys which do not match any -// non-ignored, exported fields in the destination. -func (adapter *Decoder) DisallowUnknownFields() { - cfg := adapter.iter.cfg.configBeforeFrozen - cfg.DisallowUnknownFields = true - adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) -} - -// NewEncoder same as json.NewEncoder -func NewEncoder(writer io.Writer) *Encoder { - return ConfigDefault.NewEncoder(writer) -} - -// Encoder same as json.Encoder -type Encoder struct { - stream *Stream -} - -// Encode encode interface{} as JSON to io.Writer -func (adapter *Encoder) Encode(val interface{}) error { - adapter.stream.WriteVal(val) - adapter.stream.WriteRaw("\n") - adapter.stream.Flush() - return adapter.stream.Error -} - -// SetIndent set the indention. Prefix is not supported -func (adapter *Encoder) SetIndent(prefix, indent string) { - config := adapter.stream.cfg.configBeforeFrozen - config.IndentionStep = len(indent) - adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) -} - -// SetEscapeHTML escape html by default, set to false to disable -func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { - config := adapter.stream.cfg.configBeforeFrozen - config.EscapeHTML = escapeHTML - adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) -} - -// Valid reports whether data is a valid JSON encoding. -func Valid(data []byte) bool { - return ConfigDefault.Valid(data) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any.go deleted file mode 100644 index daecfed..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any.go +++ /dev/null @@ -1,321 +0,0 @@ -package jsoniter - -import ( - "errors" - "fmt" - "github.com/modern-go/reflect2" - "io" - "reflect" - "strconv" - "unsafe" -) - -// Any generic object representation. -// The lazy json implementation holds []byte and parse lazily. -type Any interface { - LastError() error - ValueType() ValueType - MustBeValid() Any - ToBool() bool - ToInt() int - ToInt32() int32 - ToInt64() int64 - ToUint() uint - ToUint32() uint32 - ToUint64() uint64 - ToFloat32() float32 - ToFloat64() float64 - ToString() string - ToVal(val interface{}) - Get(path ...interface{}) Any - Size() int - Keys() []string - GetInterface() interface{} - WriteTo(stream *Stream) -} - -type baseAny struct{} - -func (any *baseAny) Get(path ...interface{}) Any { - return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} -} - -func (any *baseAny) Size() int { - return 0 -} - -func (any *baseAny) Keys() []string { - return []string{} -} - -func (any *baseAny) ToVal(obj interface{}) { - panic("not implemented") -} - -// WrapInt32 turn int32 into Any interface -func WrapInt32(val int32) Any { - return &int32Any{baseAny{}, val} -} - -// WrapInt64 turn int64 into Any interface -func WrapInt64(val int64) Any { - return &int64Any{baseAny{}, val} -} - -// WrapUint32 turn uint32 into Any interface -func WrapUint32(val uint32) Any { - return &uint32Any{baseAny{}, val} -} - -// WrapUint64 turn uint64 into Any interface -func WrapUint64(val uint64) Any { - return &uint64Any{baseAny{}, val} -} - -// WrapFloat64 turn float64 into Any interface -func WrapFloat64(val float64) Any { - return &floatAny{baseAny{}, val} -} - -// WrapString turn string into Any interface -func WrapString(val string) Any { - return &stringAny{baseAny{}, val} -} - -// Wrap turn a go object into Any interface -func Wrap(val interface{}) Any { - if val == nil { - return &nilAny{} - } - asAny, isAny := val.(Any) - if isAny { - return asAny - } - typ := reflect2.TypeOf(val) - switch typ.Kind() { - case reflect.Slice: - return wrapArray(val) - case reflect.Struct: - return wrapStruct(val) - case reflect.Map: - return wrapMap(val) - case reflect.String: - return WrapString(val.(string)) - case reflect.Int: - if strconv.IntSize == 32 { - return WrapInt32(int32(val.(int))) - } - return WrapInt64(int64(val.(int))) - case reflect.Int8: - return WrapInt32(int32(val.(int8))) - case reflect.Int16: - return WrapInt32(int32(val.(int16))) - case reflect.Int32: - return WrapInt32(val.(int32)) - case reflect.Int64: - return WrapInt64(val.(int64)) - case reflect.Uint: - if strconv.IntSize == 32 { - return WrapUint32(uint32(val.(uint))) - } - return WrapUint64(uint64(val.(uint))) - case reflect.Uintptr: - if ptrSize == 32 { - return WrapUint32(uint32(val.(uintptr))) - } - return WrapUint64(uint64(val.(uintptr))) - case reflect.Uint8: - return WrapUint32(uint32(val.(uint8))) - case reflect.Uint16: - return WrapUint32(uint32(val.(uint16))) - case reflect.Uint32: - return WrapUint32(uint32(val.(uint32))) - case reflect.Uint64: - return WrapUint64(val.(uint64)) - case reflect.Float32: - return WrapFloat64(float64(val.(float32))) - case reflect.Float64: - return WrapFloat64(val.(float64)) - case reflect.Bool: - if val.(bool) == true { - return &trueAny{} - } - return &falseAny{} - } - return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} -} - -// ReadAny read next JSON element as an Any object. It is a better json.RawMessage. -func (iter *Iterator) ReadAny() Any { - return iter.readAny() -} - -func (iter *Iterator) readAny() Any { - c := iter.nextToken() - switch c { - case '"': - iter.unreadByte() - return &stringAny{baseAny{}, iter.ReadString()} - case 'n': - iter.skipThreeBytes('u', 'l', 'l') // null - return &nilAny{} - case 't': - iter.skipThreeBytes('r', 'u', 'e') // true - return &trueAny{} - case 'f': - iter.skipFourBytes('a', 'l', 's', 'e') // false - return &falseAny{} - case '{': - return iter.readObjectAny() - case '[': - return iter.readArrayAny() - case '-': - return iter.readNumberAny(false) - case 0: - return &invalidAny{baseAny{}, errors.New("input is empty")} - default: - return iter.readNumberAny(true) - } -} - -func (iter *Iterator) readNumberAny(positive bool) Any { - iter.startCapture(iter.head - 1) - iter.skipNumber() - lazyBuf := iter.stopCapture() - return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} -} - -func (iter *Iterator) readObjectAny() Any { - iter.startCapture(iter.head - 1) - iter.skipObject() - lazyBuf := iter.stopCapture() - return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} -} - -func (iter *Iterator) readArrayAny() Any { - iter.startCapture(iter.head - 1) - iter.skipArray() - lazyBuf := iter.stopCapture() - return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} -} - -func locateObjectField(iter *Iterator, target string) []byte { - var found []byte - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - if field == target { - found = iter.SkipAndReturnBytes() - return false - } - iter.Skip() - return true - }) - return found -} - -func locateArrayElement(iter *Iterator, target int) []byte { - var found []byte - n := 0 - iter.ReadArrayCB(func(iter *Iterator) bool { - if n == target { - found = iter.SkipAndReturnBytes() - return false - } - iter.Skip() - n++ - return true - }) - return found -} - -func locatePath(iter *Iterator, path []interface{}) Any { - for i, pathKeyObj := range path { - switch pathKey := pathKeyObj.(type) { - case string: - valueBytes := locateObjectField(iter, pathKey) - if valueBytes == nil { - return newInvalidAny(path[i:]) - } - iter.ResetBytes(valueBytes) - case int: - valueBytes := locateArrayElement(iter, pathKey) - if valueBytes == nil { - return newInvalidAny(path[i:]) - } - iter.ResetBytes(valueBytes) - case int32: - if '*' == pathKey { - return iter.readAny().Get(path[i:]...) - } - return newInvalidAny(path[i:]) - default: - return newInvalidAny(path[i:]) - } - } - if iter.Error != nil && iter.Error != io.EOF { - return &invalidAny{baseAny{}, iter.Error} - } - return iter.readAny() -} - -var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem() - -func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ == anyType { - return &directAnyCodec{} - } - if typ.Implements(anyType) { - return &anyCodec{ - valType: typ, - } - } - return nil -} - -func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ == anyType { - return &directAnyCodec{} - } - if typ.Implements(anyType) { - return &anyCodec{ - valType: typ, - } - } - return nil -} - -type anyCodec struct { - valType reflect2.Type -} - -func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - panic("not implemented") -} - -func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := codec.valType.UnsafeIndirect(ptr) - any := obj.(Any) - any.WriteTo(stream) -} - -func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { - obj := codec.valType.UnsafeIndirect(ptr) - any := obj.(Any) - return any.Size() == 0 -} - -type directAnyCodec struct { -} - -func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *(*Any)(ptr) = iter.readAny() -} - -func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - any := *(*Any)(ptr) - any.WriteTo(stream) -} - -func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool { - any := *(*Any)(ptr) - return any.Size() == 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_array.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_array.go deleted file mode 100644 index 0449e9a..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_array.go +++ /dev/null @@ -1,278 +0,0 @@ -package jsoniter - -import ( - "reflect" - "unsafe" -) - -type arrayLazyAny struct { - baseAny - cfg *frozenConfig - buf []byte - err error -} - -func (any *arrayLazyAny) ValueType() ValueType { - return ArrayValue -} - -func (any *arrayLazyAny) MustBeValid() Any { - return any -} - -func (any *arrayLazyAny) LastError() error { - return any.err -} - -func (any *arrayLazyAny) ToBool() bool { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.ReadArray() -} - -func (any *arrayLazyAny) ToInt() int { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToInt32() int32 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToInt64() int64 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToUint() uint { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToUint32() uint32 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToUint64() uint64 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToFloat32() float32 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToFloat64() float64 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToString() string { - return *(*string)(unsafe.Pointer(&any.buf)) -} - -func (any *arrayLazyAny) ToVal(val interface{}) { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadVal(val) -} - -func (any *arrayLazyAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case int: - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - valueBytes := locateArrayElement(iter, firstPath) - if valueBytes == nil { - return newInvalidAny(path) - } - iter.ResetBytes(valueBytes) - return locatePath(iter, path[1:]) - case int32: - if '*' == firstPath { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - arr := make([]Any, 0) - iter.ReadArrayCB(func(iter *Iterator) bool { - found := iter.readAny().Get(path[1:]...) - if found.ValueType() != InvalidValue { - arr = append(arr, found) - } - return true - }) - return wrapArray(arr) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *arrayLazyAny) Size() int { - size := 0 - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadArrayCB(func(iter *Iterator) bool { - size++ - iter.Skip() - return true - }) - return size -} - -func (any *arrayLazyAny) WriteTo(stream *Stream) { - stream.Write(any.buf) -} - -func (any *arrayLazyAny) GetInterface() interface{} { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.Read() -} - -type arrayAny struct { - baseAny - val reflect.Value -} - -func wrapArray(val interface{}) *arrayAny { - return &arrayAny{baseAny{}, reflect.ValueOf(val)} -} - -func (any *arrayAny) ValueType() ValueType { - return ArrayValue -} - -func (any *arrayAny) MustBeValid() Any { - return any -} - -func (any *arrayAny) LastError() error { - return nil -} - -func (any *arrayAny) ToBool() bool { - return any.val.Len() != 0 -} - -func (any *arrayAny) ToInt() int { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToInt32() int32 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToInt64() int64 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToUint() uint { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToUint32() uint32 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToUint64() uint64 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToFloat32() float32 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToFloat64() float64 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToString() string { - str, _ := MarshalToString(any.val.Interface()) - return str -} - -func (any *arrayAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case int: - if firstPath < 0 || firstPath >= any.val.Len() { - return newInvalidAny(path) - } - return Wrap(any.val.Index(firstPath).Interface()) - case int32: - if '*' == firstPath { - mappedAll := make([]Any, 0) - for i := 0; i < any.val.Len(); i++ { - mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...) - if mapped.ValueType() != InvalidValue { - mappedAll = append(mappedAll, mapped) - } - } - return wrapArray(mappedAll) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *arrayAny) Size() int { - return any.val.Len() -} - -func (any *arrayAny) WriteTo(stream *Stream) { - stream.WriteVal(any.val) -} - -func (any *arrayAny) GetInterface() interface{} { - return any.val.Interface() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_bool.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_bool.go deleted file mode 100644 index 9452324..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_bool.go +++ /dev/null @@ -1,137 +0,0 @@ -package jsoniter - -type trueAny struct { - baseAny -} - -func (any *trueAny) LastError() error { - return nil -} - -func (any *trueAny) ToBool() bool { - return true -} - -func (any *trueAny) ToInt() int { - return 1 -} - -func (any *trueAny) ToInt32() int32 { - return 1 -} - -func (any *trueAny) ToInt64() int64 { - return 1 -} - -func (any *trueAny) ToUint() uint { - return 1 -} - -func (any *trueAny) ToUint32() uint32 { - return 1 -} - -func (any *trueAny) ToUint64() uint64 { - return 1 -} - -func (any *trueAny) ToFloat32() float32 { - return 1 -} - -func (any *trueAny) ToFloat64() float64 { - return 1 -} - -func (any *trueAny) ToString() string { - return "true" -} - -func (any *trueAny) WriteTo(stream *Stream) { - stream.WriteTrue() -} - -func (any *trueAny) Parse() *Iterator { - return nil -} - -func (any *trueAny) GetInterface() interface{} { - return true -} - -func (any *trueAny) ValueType() ValueType { - return BoolValue -} - -func (any *trueAny) MustBeValid() Any { - return any -} - -type falseAny struct { - baseAny -} - -func (any *falseAny) LastError() error { - return nil -} - -func (any *falseAny) ToBool() bool { - return false -} - -func (any *falseAny) ToInt() int { - return 0 -} - -func (any *falseAny) ToInt32() int32 { - return 0 -} - -func (any *falseAny) ToInt64() int64 { - return 0 -} - -func (any *falseAny) ToUint() uint { - return 0 -} - -func (any *falseAny) ToUint32() uint32 { - return 0 -} - -func (any *falseAny) ToUint64() uint64 { - return 0 -} - -func (any *falseAny) ToFloat32() float32 { - return 0 -} - -func (any *falseAny) ToFloat64() float64 { - return 0 -} - -func (any *falseAny) ToString() string { - return "false" -} - -func (any *falseAny) WriteTo(stream *Stream) { - stream.WriteFalse() -} - -func (any *falseAny) Parse() *Iterator { - return nil -} - -func (any *falseAny) GetInterface() interface{} { - return false -} - -func (any *falseAny) ValueType() ValueType { - return BoolValue -} - -func (any *falseAny) MustBeValid() Any { - return any -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_float.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_float.go deleted file mode 100644 index 35fdb09..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_float.go +++ /dev/null @@ -1,83 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type floatAny struct { - baseAny - val float64 -} - -func (any *floatAny) Parse() *Iterator { - return nil -} - -func (any *floatAny) ValueType() ValueType { - return NumberValue -} - -func (any *floatAny) MustBeValid() Any { - return any -} - -func (any *floatAny) LastError() error { - return nil -} - -func (any *floatAny) ToBool() bool { - return any.ToFloat64() != 0 -} - -func (any *floatAny) ToInt() int { - return int(any.val) -} - -func (any *floatAny) ToInt32() int32 { - return int32(any.val) -} - -func (any *floatAny) ToInt64() int64 { - return int64(any.val) -} - -func (any *floatAny) ToUint() uint { - if any.val > 0 { - return uint(any.val) - } - return 0 -} - -func (any *floatAny) ToUint32() uint32 { - if any.val > 0 { - return uint32(any.val) - } - return 0 -} - -func (any *floatAny) ToUint64() uint64 { - if any.val > 0 { - return uint64(any.val) - } - return 0 -} - -func (any *floatAny) ToFloat32() float32 { - return float32(any.val) -} - -func (any *floatAny) ToFloat64() float64 { - return any.val -} - -func (any *floatAny) ToString() string { - return strconv.FormatFloat(any.val, 'E', -1, 64) -} - -func (any *floatAny) WriteTo(stream *Stream) { - stream.WriteFloat64(any.val) -} - -func (any *floatAny) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_int32.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_int32.go deleted file mode 100644 index 1b56f39..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_int32.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type int32Any struct { - baseAny - val int32 -} - -func (any *int32Any) LastError() error { - return nil -} - -func (any *int32Any) ValueType() ValueType { - return NumberValue -} - -func (any *int32Any) MustBeValid() Any { - return any -} - -func (any *int32Any) ToBool() bool { - return any.val != 0 -} - -func (any *int32Any) ToInt() int { - return int(any.val) -} - -func (any *int32Any) ToInt32() int32 { - return any.val -} - -func (any *int32Any) ToInt64() int64 { - return int64(any.val) -} - -func (any *int32Any) ToUint() uint { - return uint(any.val) -} - -func (any *int32Any) ToUint32() uint32 { - return uint32(any.val) -} - -func (any *int32Any) ToUint64() uint64 { - return uint64(any.val) -} - -func (any *int32Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *int32Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *int32Any) ToString() string { - return strconv.FormatInt(int64(any.val), 10) -} - -func (any *int32Any) WriteTo(stream *Stream) { - stream.WriteInt32(any.val) -} - -func (any *int32Any) Parse() *Iterator { - return nil -} - -func (any *int32Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_int64.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_int64.go deleted file mode 100644 index c440d72..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_int64.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type int64Any struct { - baseAny - val int64 -} - -func (any *int64Any) LastError() error { - return nil -} - -func (any *int64Any) ValueType() ValueType { - return NumberValue -} - -func (any *int64Any) MustBeValid() Any { - return any -} - -func (any *int64Any) ToBool() bool { - return any.val != 0 -} - -func (any *int64Any) ToInt() int { - return int(any.val) -} - -func (any *int64Any) ToInt32() int32 { - return int32(any.val) -} - -func (any *int64Any) ToInt64() int64 { - return any.val -} - -func (any *int64Any) ToUint() uint { - return uint(any.val) -} - -func (any *int64Any) ToUint32() uint32 { - return uint32(any.val) -} - -func (any *int64Any) ToUint64() uint64 { - return uint64(any.val) -} - -func (any *int64Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *int64Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *int64Any) ToString() string { - return strconv.FormatInt(any.val, 10) -} - -func (any *int64Any) WriteTo(stream *Stream) { - stream.WriteInt64(any.val) -} - -func (any *int64Any) Parse() *Iterator { - return nil -} - -func (any *int64Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_invalid.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_invalid.go deleted file mode 100644 index 1d859ea..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_invalid.go +++ /dev/null @@ -1,82 +0,0 @@ -package jsoniter - -import "fmt" - -type invalidAny struct { - baseAny - err error -} - -func newInvalidAny(path []interface{}) *invalidAny { - return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)} -} - -func (any *invalidAny) LastError() error { - return any.err -} - -func (any *invalidAny) ValueType() ValueType { - return InvalidValue -} - -func (any *invalidAny) MustBeValid() Any { - panic(any.err) -} - -func (any *invalidAny) ToBool() bool { - return false -} - -func (any *invalidAny) ToInt() int { - return 0 -} - -func (any *invalidAny) ToInt32() int32 { - return 0 -} - -func (any *invalidAny) ToInt64() int64 { - return 0 -} - -func (any *invalidAny) ToUint() uint { - return 0 -} - -func (any *invalidAny) ToUint32() uint32 { - return 0 -} - -func (any *invalidAny) ToUint64() uint64 { - return 0 -} - -func (any *invalidAny) ToFloat32() float32 { - return 0 -} - -func (any *invalidAny) ToFloat64() float64 { - return 0 -} - -func (any *invalidAny) ToString() string { - return "" -} - -func (any *invalidAny) WriteTo(stream *Stream) { -} - -func (any *invalidAny) Get(path ...interface{}) Any { - if any.err == nil { - return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)} - } - return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)} -} - -func (any *invalidAny) Parse() *Iterator { - return nil -} - -func (any *invalidAny) GetInterface() interface{} { - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_nil.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_nil.go deleted file mode 100644 index d04cb54..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_nil.go +++ /dev/null @@ -1,69 +0,0 @@ -package jsoniter - -type nilAny struct { - baseAny -} - -func (any *nilAny) LastError() error { - return nil -} - -func (any *nilAny) ValueType() ValueType { - return NilValue -} - -func (any *nilAny) MustBeValid() Any { - return any -} - -func (any *nilAny) ToBool() bool { - return false -} - -func (any *nilAny) ToInt() int { - return 0 -} - -func (any *nilAny) ToInt32() int32 { - return 0 -} - -func (any *nilAny) ToInt64() int64 { - return 0 -} - -func (any *nilAny) ToUint() uint { - return 0 -} - -func (any *nilAny) ToUint32() uint32 { - return 0 -} - -func (any *nilAny) ToUint64() uint64 { - return 0 -} - -func (any *nilAny) ToFloat32() float32 { - return 0 -} - -func (any *nilAny) ToFloat64() float64 { - return 0 -} - -func (any *nilAny) ToString() string { - return "" -} - -func (any *nilAny) WriteTo(stream *Stream) { - stream.WriteNil() -} - -func (any *nilAny) Parse() *Iterator { - return nil -} - -func (any *nilAny) GetInterface() interface{} { - return nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_number.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_number.go deleted file mode 100644 index 9d1e901..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_number.go +++ /dev/null @@ -1,123 +0,0 @@ -package jsoniter - -import ( - "io" - "unsafe" -) - -type numberLazyAny struct { - baseAny - cfg *frozenConfig - buf []byte - err error -} - -func (any *numberLazyAny) ValueType() ValueType { - return NumberValue -} - -func (any *numberLazyAny) MustBeValid() Any { - return any -} - -func (any *numberLazyAny) LastError() error { - return any.err -} - -func (any *numberLazyAny) ToBool() bool { - return any.ToFloat64() != 0 -} - -func (any *numberLazyAny) ToInt() int { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadInt() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToInt32() int32 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadInt32() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToInt64() int64 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadInt64() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToUint() uint { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadUint() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToUint32() uint32 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadUint32() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToUint64() uint64 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadUint64() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToFloat32() float32 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadFloat32() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToFloat64() float64 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadFloat64() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToString() string { - return *(*string)(unsafe.Pointer(&any.buf)) -} - -func (any *numberLazyAny) WriteTo(stream *Stream) { - stream.Write(any.buf) -} - -func (any *numberLazyAny) GetInterface() interface{} { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.Read() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_object.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_object.go deleted file mode 100644 index c44ef5c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_object.go +++ /dev/null @@ -1,374 +0,0 @@ -package jsoniter - -import ( - "reflect" - "unsafe" -) - -type objectLazyAny struct { - baseAny - cfg *frozenConfig - buf []byte - err error -} - -func (any *objectLazyAny) ValueType() ValueType { - return ObjectValue -} - -func (any *objectLazyAny) MustBeValid() Any { - return any -} - -func (any *objectLazyAny) LastError() error { - return any.err -} - -func (any *objectLazyAny) ToBool() bool { - return true -} - -func (any *objectLazyAny) ToInt() int { - return 0 -} - -func (any *objectLazyAny) ToInt32() int32 { - return 0 -} - -func (any *objectLazyAny) ToInt64() int64 { - return 0 -} - -func (any *objectLazyAny) ToUint() uint { - return 0 -} - -func (any *objectLazyAny) ToUint32() uint32 { - return 0 -} - -func (any *objectLazyAny) ToUint64() uint64 { - return 0 -} - -func (any *objectLazyAny) ToFloat32() float32 { - return 0 -} - -func (any *objectLazyAny) ToFloat64() float64 { - return 0 -} - -func (any *objectLazyAny) ToString() string { - return *(*string)(unsafe.Pointer(&any.buf)) -} - -func (any *objectLazyAny) ToVal(obj interface{}) { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadVal(obj) -} - -func (any *objectLazyAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case string: - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - valueBytes := locateObjectField(iter, firstPath) - if valueBytes == nil { - return newInvalidAny(path) - } - iter.ResetBytes(valueBytes) - return locatePath(iter, path[1:]) - case int32: - if '*' == firstPath { - mappedAll := map[string]Any{} - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadMapCB(func(iter *Iterator, field string) bool { - mapped := locatePath(iter, path[1:]) - if mapped.ValueType() != InvalidValue { - mappedAll[field] = mapped - } - return true - }) - return wrapMap(mappedAll) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *objectLazyAny) Keys() []string { - keys := []string{} - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadMapCB(func(iter *Iterator, field string) bool { - iter.Skip() - keys = append(keys, field) - return true - }) - return keys -} - -func (any *objectLazyAny) Size() int { - size := 0 - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - iter.Skip() - size++ - return true - }) - return size -} - -func (any *objectLazyAny) WriteTo(stream *Stream) { - stream.Write(any.buf) -} - -func (any *objectLazyAny) GetInterface() interface{} { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.Read() -} - -type objectAny struct { - baseAny - err error - val reflect.Value -} - -func wrapStruct(val interface{}) *objectAny { - return &objectAny{baseAny{}, nil, reflect.ValueOf(val)} -} - -func (any *objectAny) ValueType() ValueType { - return ObjectValue -} - -func (any *objectAny) MustBeValid() Any { - return any -} - -func (any *objectAny) Parse() *Iterator { - return nil -} - -func (any *objectAny) LastError() error { - return any.err -} - -func (any *objectAny) ToBool() bool { - return any.val.NumField() != 0 -} - -func (any *objectAny) ToInt() int { - return 0 -} - -func (any *objectAny) ToInt32() int32 { - return 0 -} - -func (any *objectAny) ToInt64() int64 { - return 0 -} - -func (any *objectAny) ToUint() uint { - return 0 -} - -func (any *objectAny) ToUint32() uint32 { - return 0 -} - -func (any *objectAny) ToUint64() uint64 { - return 0 -} - -func (any *objectAny) ToFloat32() float32 { - return 0 -} - -func (any *objectAny) ToFloat64() float64 { - return 0 -} - -func (any *objectAny) ToString() string { - str, err := MarshalToString(any.val.Interface()) - any.err = err - return str -} - -func (any *objectAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case string: - field := any.val.FieldByName(firstPath) - if !field.IsValid() { - return newInvalidAny(path) - } - return Wrap(field.Interface()) - case int32: - if '*' == firstPath { - mappedAll := map[string]Any{} - for i := 0; i < any.val.NumField(); i++ { - field := any.val.Field(i) - if field.CanInterface() { - mapped := Wrap(field.Interface()).Get(path[1:]...) - if mapped.ValueType() != InvalidValue { - mappedAll[any.val.Type().Field(i).Name] = mapped - } - } - } - return wrapMap(mappedAll) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *objectAny) Keys() []string { - keys := make([]string, 0, any.val.NumField()) - for i := 0; i < any.val.NumField(); i++ { - keys = append(keys, any.val.Type().Field(i).Name) - } - return keys -} - -func (any *objectAny) Size() int { - return any.val.NumField() -} - -func (any *objectAny) WriteTo(stream *Stream) { - stream.WriteVal(any.val) -} - -func (any *objectAny) GetInterface() interface{} { - return any.val.Interface() -} - -type mapAny struct { - baseAny - err error - val reflect.Value -} - -func wrapMap(val interface{}) *mapAny { - return &mapAny{baseAny{}, nil, reflect.ValueOf(val)} -} - -func (any *mapAny) ValueType() ValueType { - return ObjectValue -} - -func (any *mapAny) MustBeValid() Any { - return any -} - -func (any *mapAny) Parse() *Iterator { - return nil -} - -func (any *mapAny) LastError() error { - return any.err -} - -func (any *mapAny) ToBool() bool { - return true -} - -func (any *mapAny) ToInt() int { - return 0 -} - -func (any *mapAny) ToInt32() int32 { - return 0 -} - -func (any *mapAny) ToInt64() int64 { - return 0 -} - -func (any *mapAny) ToUint() uint { - return 0 -} - -func (any *mapAny) ToUint32() uint32 { - return 0 -} - -func (any *mapAny) ToUint64() uint64 { - return 0 -} - -func (any *mapAny) ToFloat32() float32 { - return 0 -} - -func (any *mapAny) ToFloat64() float64 { - return 0 -} - -func (any *mapAny) ToString() string { - str, err := MarshalToString(any.val.Interface()) - any.err = err - return str -} - -func (any *mapAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case int32: - if '*' == firstPath { - mappedAll := map[string]Any{} - for _, key := range any.val.MapKeys() { - keyAsStr := key.String() - element := Wrap(any.val.MapIndex(key).Interface()) - mapped := element.Get(path[1:]...) - if mapped.ValueType() != InvalidValue { - mappedAll[keyAsStr] = mapped - } - } - return wrapMap(mappedAll) - } - return newInvalidAny(path) - default: - value := any.val.MapIndex(reflect.ValueOf(firstPath)) - if !value.IsValid() { - return newInvalidAny(path) - } - return Wrap(value.Interface()) - } -} - -func (any *mapAny) Keys() []string { - keys := make([]string, 0, any.val.Len()) - for _, key := range any.val.MapKeys() { - keys = append(keys, key.String()) - } - return keys -} - -func (any *mapAny) Size() int { - return any.val.Len() -} - -func (any *mapAny) WriteTo(stream *Stream) { - stream.WriteVal(any.val) -} - -func (any *mapAny) GetInterface() interface{} { - return any.val.Interface() -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_str.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_str.go deleted file mode 100644 index a4b93c7..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_str.go +++ /dev/null @@ -1,166 +0,0 @@ -package jsoniter - -import ( - "fmt" - "strconv" -) - -type stringAny struct { - baseAny - val string -} - -func (any *stringAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} -} - -func (any *stringAny) Parse() *Iterator { - return nil -} - -func (any *stringAny) ValueType() ValueType { - return StringValue -} - -func (any *stringAny) MustBeValid() Any { - return any -} - -func (any *stringAny) LastError() error { - return nil -} - -func (any *stringAny) ToBool() bool { - str := any.ToString() - if str == "0" { - return false - } - for _, c := range str { - switch c { - case ' ', '\n', '\r', '\t': - default: - return true - } - } - return false -} - -func (any *stringAny) ToInt() int { - return int(any.ToInt64()) - -} - -func (any *stringAny) ToInt32() int32 { - return int32(any.ToInt64()) -} - -func (any *stringAny) ToInt64() int64 { - if any.val == "" { - return 0 - } - - flag := 1 - startPos := 0 - endPos := 0 - if any.val[0] == '+' || any.val[0] == '-' { - startPos = 1 - } - - if any.val[0] == '-' { - flag = -1 - } - - for i := startPos; i < len(any.val); i++ { - if any.val[i] >= '0' && any.val[i] <= '9' { - endPos = i + 1 - } else { - break - } - } - parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64) - return int64(flag) * parsed -} - -func (any *stringAny) ToUint() uint { - return uint(any.ToUint64()) -} - -func (any *stringAny) ToUint32() uint32 { - return uint32(any.ToUint64()) -} - -func (any *stringAny) ToUint64() uint64 { - if any.val == "" { - return 0 - } - - startPos := 0 - endPos := 0 - - if any.val[0] == '-' { - return 0 - } - if any.val[0] == '+' { - startPos = 1 - } - - for i := startPos; i < len(any.val); i++ { - if any.val[i] >= '0' && any.val[i] <= '9' { - endPos = i + 1 - } else { - break - } - } - parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64) - return parsed -} - -func (any *stringAny) ToFloat32() float32 { - return float32(any.ToFloat64()) -} - -func (any *stringAny) ToFloat64() float64 { - if len(any.val) == 0 { - return 0 - } - - // first char invalid - if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') { - return 0 - } - - // extract valid num expression from string - // eg 123true => 123, -12.12xxa => -12.12 - endPos := 1 - for i := 1; i < len(any.val); i++ { - if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' { - endPos = i + 1 - continue - } - - // end position is the first char which is not digit - if any.val[i] >= '0' && any.val[i] <= '9' { - endPos = i + 1 - } else { - endPos = i - break - } - } - parsed, _ := strconv.ParseFloat(any.val[:endPos], 64) - return parsed -} - -func (any *stringAny) ToString() string { - return any.val -} - -func (any *stringAny) WriteTo(stream *Stream) { - stream.WriteString(any.val) -} - -func (any *stringAny) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_uint32.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_uint32.go deleted file mode 100644 index 656bbd3..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_uint32.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type uint32Any struct { - baseAny - val uint32 -} - -func (any *uint32Any) LastError() error { - return nil -} - -func (any *uint32Any) ValueType() ValueType { - return NumberValue -} - -func (any *uint32Any) MustBeValid() Any { - return any -} - -func (any *uint32Any) ToBool() bool { - return any.val != 0 -} - -func (any *uint32Any) ToInt() int { - return int(any.val) -} - -func (any *uint32Any) ToInt32() int32 { - return int32(any.val) -} - -func (any *uint32Any) ToInt64() int64 { - return int64(any.val) -} - -func (any *uint32Any) ToUint() uint { - return uint(any.val) -} - -func (any *uint32Any) ToUint32() uint32 { - return any.val -} - -func (any *uint32Any) ToUint64() uint64 { - return uint64(any.val) -} - -func (any *uint32Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *uint32Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *uint32Any) ToString() string { - return strconv.FormatInt(int64(any.val), 10) -} - -func (any *uint32Any) WriteTo(stream *Stream) { - stream.WriteUint32(any.val) -} - -func (any *uint32Any) Parse() *Iterator { - return nil -} - -func (any *uint32Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_uint64.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_uint64.go deleted file mode 100644 index 7df2fce..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/any_uint64.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type uint64Any struct { - baseAny - val uint64 -} - -func (any *uint64Any) LastError() error { - return nil -} - -func (any *uint64Any) ValueType() ValueType { - return NumberValue -} - -func (any *uint64Any) MustBeValid() Any { - return any -} - -func (any *uint64Any) ToBool() bool { - return any.val != 0 -} - -func (any *uint64Any) ToInt() int { - return int(any.val) -} - -func (any *uint64Any) ToInt32() int32 { - return int32(any.val) -} - -func (any *uint64Any) ToInt64() int64 { - return int64(any.val) -} - -func (any *uint64Any) ToUint() uint { - return uint(any.val) -} - -func (any *uint64Any) ToUint32() uint32 { - return uint32(any.val) -} - -func (any *uint64Any) ToUint64() uint64 { - return any.val -} - -func (any *uint64Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *uint64Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *uint64Any) ToString() string { - return strconv.FormatUint(any.val, 10) -} - -func (any *uint64Any) WriteTo(stream *Stream) { - stream.WriteUint64(any.val) -} - -func (any *uint64Any) Parse() *Iterator { - return nil -} - -func (any *uint64Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/config.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/config.go deleted file mode 100644 index 8c58fcb..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/config.go +++ /dev/null @@ -1,375 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "io" - "reflect" - "sync" - "unsafe" - - "github.com/modern-go/concurrent" - "github.com/modern-go/reflect2" -) - -// Config customize how the API should behave. -// The API is created from Config by Froze. -type Config struct { - IndentionStep int - MarshalFloatWith6Digits bool - EscapeHTML bool - SortMapKeys bool - UseNumber bool - DisallowUnknownFields bool - TagKey string - OnlyTaggedField bool - ValidateJsonRawMessage bool - ObjectFieldMustBeSimpleString bool - CaseSensitive bool -} - -// API the public interface of this package. -// Primary Marshal and Unmarshal. -type API interface { - IteratorPool - StreamPool - MarshalToString(v interface{}) (string, error) - Marshal(v interface{}) ([]byte, error) - MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) - UnmarshalFromString(str string, v interface{}) error - Unmarshal(data []byte, v interface{}) error - Get(data []byte, path ...interface{}) Any - NewEncoder(writer io.Writer) *Encoder - NewDecoder(reader io.Reader) *Decoder - Valid(data []byte) bool - RegisterExtension(extension Extension) - DecoderOf(typ reflect2.Type) ValDecoder - EncoderOf(typ reflect2.Type) ValEncoder -} - -// ConfigDefault the default API -var ConfigDefault = Config{ - EscapeHTML: true, -}.Froze() - -// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior -var ConfigCompatibleWithStandardLibrary = Config{ - EscapeHTML: true, - SortMapKeys: true, - ValidateJsonRawMessage: true, -}.Froze() - -// ConfigFastest marshals float with only 6 digits precision -var ConfigFastest = Config{ - EscapeHTML: false, - MarshalFloatWith6Digits: true, // will lose precession - ObjectFieldMustBeSimpleString: true, // do not unescape object field -}.Froze() - -type frozenConfig struct { - configBeforeFrozen Config - sortMapKeys bool - indentionStep int - objectFieldMustBeSimpleString bool - onlyTaggedField bool - disallowUnknownFields bool - decoderCache *concurrent.Map - encoderCache *concurrent.Map - encoderExtension Extension - decoderExtension Extension - extraExtensions []Extension - streamPool *sync.Pool - iteratorPool *sync.Pool - caseSensitive bool -} - -func (cfg *frozenConfig) initCache() { - cfg.decoderCache = concurrent.NewMap() - cfg.encoderCache = concurrent.NewMap() -} - -func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { - cfg.decoderCache.Store(cacheKey, decoder) -} - -func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { - cfg.encoderCache.Store(cacheKey, encoder) -} - -func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { - decoder, found := cfg.decoderCache.Load(cacheKey) - if found { - return decoder.(ValDecoder) - } - return nil -} - -func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { - encoder, found := cfg.encoderCache.Load(cacheKey) - if found { - return encoder.(ValEncoder) - } - return nil -} - -var cfgCache = concurrent.NewMap() - -func getFrozenConfigFromCache(cfg Config) *frozenConfig { - obj, found := cfgCache.Load(cfg) - if found { - return obj.(*frozenConfig) - } - return nil -} - -func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { - cfgCache.Store(cfg, frozenConfig) -} - -// Froze forge API from config -func (cfg Config) Froze() API { - api := &frozenConfig{ - sortMapKeys: cfg.SortMapKeys, - indentionStep: cfg.IndentionStep, - objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, - onlyTaggedField: cfg.OnlyTaggedField, - disallowUnknownFields: cfg.DisallowUnknownFields, - caseSensitive: cfg.CaseSensitive, - } - api.streamPool = &sync.Pool{ - New: func() interface{} { - return NewStream(api, nil, 512) - }, - } - api.iteratorPool = &sync.Pool{ - New: func() interface{} { - return NewIterator(api) - }, - } - api.initCache() - encoderExtension := EncoderExtension{} - decoderExtension := DecoderExtension{} - if cfg.MarshalFloatWith6Digits { - api.marshalFloatWith6Digits(encoderExtension) - } - if cfg.EscapeHTML { - api.escapeHTML(encoderExtension) - } - if cfg.UseNumber { - api.useNumber(decoderExtension) - } - if cfg.ValidateJsonRawMessage { - api.validateJsonRawMessage(encoderExtension) - } - api.encoderExtension = encoderExtension - api.decoderExtension = decoderExtension - api.configBeforeFrozen = cfg - return api -} - -func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { - api := getFrozenConfigFromCache(cfg) - if api != nil { - return api - } - api = cfg.Froze().(*frozenConfig) - for _, extension := range extraExtensions { - api.RegisterExtension(extension) - } - addFrozenConfigToCache(cfg, api) - return api -} - -func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { - encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { - rawMessage := *(*json.RawMessage)(ptr) - iter := cfg.BorrowIterator([]byte(rawMessage)) - iter.Read() - if iter.Error != nil { - stream.WriteRaw("null") - } else { - cfg.ReturnIterator(iter) - stream.WriteRaw(string(rawMessage)) - } - }, func(ptr unsafe.Pointer) bool { - return len(*((*json.RawMessage)(ptr))) == 0 - }} - extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder - extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder -} - -func (cfg *frozenConfig) useNumber(extension DecoderExtension) { - extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { - exitingValue := *((*interface{})(ptr)) - if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { - iter.ReadVal(exitingValue) - return - } - if iter.WhatIsNext() == NumberValue { - *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) - } else { - *((*interface{})(ptr)) = iter.Read() - } - }} -} -func (cfg *frozenConfig) getTagKey() string { - tagKey := cfg.configBeforeFrozen.TagKey - if tagKey == "" { - return "json" - } - return tagKey -} - -func (cfg *frozenConfig) RegisterExtension(extension Extension) { - cfg.extraExtensions = append(cfg.extraExtensions, extension) - copied := cfg.configBeforeFrozen - cfg.configBeforeFrozen = copied -} - -type lossyFloat32Encoder struct { -} - -func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat32Lossy(*((*float32)(ptr))) -} - -func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float32)(ptr)) == 0 -} - -type lossyFloat64Encoder struct { -} - -func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat64Lossy(*((*float64)(ptr))) -} - -func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float64)(ptr)) == 0 -} - -// EnableLossyFloatMarshalling keeps 10**(-6) precision -// for float variables for better performance. -func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { - // for better performance - extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} - extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} -} - -type htmlEscapedStringEncoder struct { -} - -func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - str := *((*string)(ptr)) - stream.WriteStringWithHTMLEscaped(str) -} - -func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*string)(ptr)) == "" -} - -func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { - encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} -} - -func (cfg *frozenConfig) cleanDecoders() { - typeDecoders = map[string]ValDecoder{} - fieldDecoders = map[string]ValDecoder{} - *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) -} - -func (cfg *frozenConfig) cleanEncoders() { - typeEncoders = map[string]ValEncoder{} - fieldEncoders = map[string]ValEncoder{} - *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) -} - -func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { - stream := cfg.BorrowStream(nil) - defer cfg.ReturnStream(stream) - stream.WriteVal(v) - if stream.Error != nil { - return "", stream.Error - } - return string(stream.Buffer()), nil -} - -func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { - stream := cfg.BorrowStream(nil) - defer cfg.ReturnStream(stream) - stream.WriteVal(v) - if stream.Error != nil { - return nil, stream.Error - } - result := stream.Buffer() - copied := make([]byte, len(result)) - copy(copied, result) - return copied, nil -} - -func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - if prefix != "" { - panic("prefix is not supported") - } - for _, r := range indent { - if r != ' ' { - panic("indent can only be space") - } - } - newCfg := cfg.configBeforeFrozen - newCfg.IndentionStep = len(indent) - return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) -} - -func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { - data := []byte(str) - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - iter.ReadVal(v) - c := iter.nextToken() - if c == 0 { - if iter.Error == io.EOF { - return nil - } - return iter.Error - } - iter.ReportError("Unmarshal", "there are bytes left after unmarshal") - return iter.Error -} - -func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - return locatePath(iter, path) -} - -func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - iter.ReadVal(v) - c := iter.nextToken() - if c == 0 { - if iter.Error == io.EOF { - return nil - } - return iter.Error - } - iter.ReportError("Unmarshal", "there are bytes left after unmarshal") - return iter.Error -} - -func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { - stream := NewStream(cfg, writer, 512) - return &Encoder{stream} -} - -func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { - iter := Parse(cfg, reader, 512) - return &Decoder{iter} -} - -func (cfg *frozenConfig) Valid(data []byte) bool { - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - iter.Skip() - return iter.Error == nil -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter.go deleted file mode 100644 index 95ae54f..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter.go +++ /dev/null @@ -1,322 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "fmt" - "io" -) - -// ValueType the type for JSON element -type ValueType int - -const ( - // InvalidValue invalid JSON element - InvalidValue ValueType = iota - // StringValue JSON element "string" - StringValue - // NumberValue JSON element 100 or 0.10 - NumberValue - // NilValue JSON element null - NilValue - // BoolValue JSON element true or false - BoolValue - // ArrayValue JSON element [] - ArrayValue - // ObjectValue JSON element {} - ObjectValue -) - -var hexDigits []byte -var valueTypes []ValueType - -func init() { - hexDigits = make([]byte, 256) - for i := 0; i < len(hexDigits); i++ { - hexDigits[i] = 255 - } - for i := '0'; i <= '9'; i++ { - hexDigits[i] = byte(i - '0') - } - for i := 'a'; i <= 'f'; i++ { - hexDigits[i] = byte((i - 'a') + 10) - } - for i := 'A'; i <= 'F'; i++ { - hexDigits[i] = byte((i - 'A') + 10) - } - valueTypes = make([]ValueType, 256) - for i := 0; i < len(valueTypes); i++ { - valueTypes[i] = InvalidValue - } - valueTypes['"'] = StringValue - valueTypes['-'] = NumberValue - valueTypes['0'] = NumberValue - valueTypes['1'] = NumberValue - valueTypes['2'] = NumberValue - valueTypes['3'] = NumberValue - valueTypes['4'] = NumberValue - valueTypes['5'] = NumberValue - valueTypes['6'] = NumberValue - valueTypes['7'] = NumberValue - valueTypes['8'] = NumberValue - valueTypes['9'] = NumberValue - valueTypes['t'] = BoolValue - valueTypes['f'] = BoolValue - valueTypes['n'] = NilValue - valueTypes['['] = ArrayValue - valueTypes['{'] = ObjectValue -} - -// Iterator is a io.Reader like object, with JSON specific read functions. -// Error is not returned as return value, but stored as Error member on this iterator instance. -type Iterator struct { - cfg *frozenConfig - reader io.Reader - buf []byte - head int - tail int - captureStartedAt int - captured []byte - Error error - Attachment interface{} // open for customized decoder -} - -// NewIterator creates an empty Iterator instance -func NewIterator(cfg API) *Iterator { - return &Iterator{ - cfg: cfg.(*frozenConfig), - reader: nil, - buf: nil, - head: 0, - tail: 0, - } -} - -// Parse creates an Iterator instance from io.Reader -func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { - return &Iterator{ - cfg: cfg.(*frozenConfig), - reader: reader, - buf: make([]byte, bufSize), - head: 0, - tail: 0, - } -} - -// ParseBytes creates an Iterator instance from byte array -func ParseBytes(cfg API, input []byte) *Iterator { - return &Iterator{ - cfg: cfg.(*frozenConfig), - reader: nil, - buf: input, - head: 0, - tail: len(input), - } -} - -// ParseString creates an Iterator instance from string -func ParseString(cfg API, input string) *Iterator { - return ParseBytes(cfg, []byte(input)) -} - -// Pool returns a pool can provide more iterator with same configuration -func (iter *Iterator) Pool() IteratorPool { - return iter.cfg -} - -// Reset reuse iterator instance by specifying another reader -func (iter *Iterator) Reset(reader io.Reader) *Iterator { - iter.reader = reader - iter.head = 0 - iter.tail = 0 - return iter -} - -// ResetBytes reuse iterator instance by specifying another byte array as input -func (iter *Iterator) ResetBytes(input []byte) *Iterator { - iter.reader = nil - iter.buf = input - iter.head = 0 - iter.tail = len(input) - return iter -} - -// WhatIsNext gets ValueType of relatively next json element -func (iter *Iterator) WhatIsNext() ValueType { - valueType := valueTypes[iter.nextToken()] - iter.unreadByte() - return valueType -} - -func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case ' ', '\n', '\t', '\r': - continue - } - iter.head = i - return false - } - return true -} - -func (iter *Iterator) isObjectEnd() bool { - c := iter.nextToken() - if c == ',' { - return false - } - if c == '}' { - return true - } - iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c})) - return true -} - -func (iter *Iterator) nextToken() byte { - // a variation of skip whitespaces, returning the next non-whitespace token - for { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case ' ', '\n', '\t', '\r': - continue - } - iter.head = i + 1 - return c - } - if !iter.loadMore() { - return 0 - } - } -} - -// ReportError record a error in iterator instance with current position. -func (iter *Iterator) ReportError(operation string, msg string) { - if iter.Error != nil { - if iter.Error != io.EOF { - return - } - } - peekStart := iter.head - 10 - if peekStart < 0 { - peekStart = 0 - } - peekEnd := iter.head + 10 - if peekEnd > iter.tail { - peekEnd = iter.tail - } - parsing := string(iter.buf[peekStart:peekEnd]) - contextStart := iter.head - 50 - if contextStart < 0 { - contextStart = 0 - } - contextEnd := iter.head + 50 - if contextEnd > iter.tail { - contextEnd = iter.tail - } - context := string(iter.buf[contextStart:contextEnd]) - iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", - operation, msg, iter.head-peekStart, parsing, context) -} - -// CurrentBuffer gets current buffer as string for debugging purpose -func (iter *Iterator) CurrentBuffer() string { - peekStart := iter.head - 10 - if peekStart < 0 { - peekStart = 0 - } - return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, - string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) -} - -func (iter *Iterator) readByte() (ret byte) { - if iter.head == iter.tail { - if iter.loadMore() { - ret = iter.buf[iter.head] - iter.head++ - return ret - } - return 0 - } - ret = iter.buf[iter.head] - iter.head++ - return ret -} - -func (iter *Iterator) loadMore() bool { - if iter.reader == nil { - if iter.Error == nil { - iter.head = iter.tail - iter.Error = io.EOF - } - return false - } - if iter.captured != nil { - iter.captured = append(iter.captured, - iter.buf[iter.captureStartedAt:iter.tail]...) - iter.captureStartedAt = 0 - } - for { - n, err := iter.reader.Read(iter.buf) - if n == 0 { - if err != nil { - if iter.Error == nil { - iter.Error = err - } - return false - } - } else { - iter.head = 0 - iter.tail = n - return true - } - } -} - -func (iter *Iterator) unreadByte() { - if iter.Error != nil { - return - } - iter.head-- - return -} - -// Read read the next JSON element as generic interface{}. -func (iter *Iterator) Read() interface{} { - valueType := iter.WhatIsNext() - switch valueType { - case StringValue: - return iter.ReadString() - case NumberValue: - if iter.cfg.configBeforeFrozen.UseNumber { - return json.Number(iter.readNumberAsString()) - } - return iter.ReadFloat64() - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - return nil - case BoolValue: - return iter.ReadBool() - case ArrayValue: - arr := []interface{}{} - iter.ReadArrayCB(func(iter *Iterator) bool { - var elem interface{} - iter.ReadVal(&elem) - arr = append(arr, elem) - return true - }) - return arr - case ObjectValue: - obj := map[string]interface{}{} - iter.ReadMapCB(func(Iter *Iterator, field string) bool { - var elem interface{} - iter.ReadVal(&elem) - obj[field] = elem - return true - }) - return obj - default: - iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", valueType)) - return nil - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_array.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_array.go deleted file mode 100644 index 6188cb4..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_array.go +++ /dev/null @@ -1,58 +0,0 @@ -package jsoniter - -// ReadArray read array element, tells if the array has more element to read. -func (iter *Iterator) ReadArray() (ret bool) { - c := iter.nextToken() - switch c { - case 'n': - iter.skipThreeBytes('u', 'l', 'l') - return false // null - case '[': - c = iter.nextToken() - if c != ']' { - iter.unreadByte() - return true - } - return false - case ']': - return false - case ',': - return true - default: - iter.ReportError("ReadArray", "expect [ or , or ] or n, but found "+string([]byte{c})) - return - } -} - -// ReadArrayCB read array with callback -func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { - c := iter.nextToken() - if c == '[' { - c = iter.nextToken() - if c != ']' { - iter.unreadByte() - if !callback(iter) { - return false - } - c = iter.nextToken() - for c == ',' { - if !callback(iter) { - return false - } - c = iter.nextToken() - } - if c != ']' { - iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) - return false - } - return true - } - return true - } - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return true // null - } - iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) - return false -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_float.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_float.go deleted file mode 100644 index 4f883c0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_float.go +++ /dev/null @@ -1,347 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "io" - "math/big" - "strconv" - "strings" - "unsafe" -) - -var floatDigits []int8 - -const invalidCharForNumber = int8(-1) -const endOfNumber = int8(-2) -const dotInNumber = int8(-3) - -func init() { - floatDigits = make([]int8, 256) - for i := 0; i < len(floatDigits); i++ { - floatDigits[i] = invalidCharForNumber - } - for i := int8('0'); i <= int8('9'); i++ { - floatDigits[i] = i - int8('0') - } - floatDigits[','] = endOfNumber - floatDigits[']'] = endOfNumber - floatDigits['}'] = endOfNumber - floatDigits[' '] = endOfNumber - floatDigits['\t'] = endOfNumber - floatDigits['\n'] = endOfNumber - floatDigits['.'] = dotInNumber -} - -// ReadBigFloat read big.Float -func (iter *Iterator) ReadBigFloat() (ret *big.Float) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return nil - } - prec := 64 - if len(str) > prec { - prec = len(str) - } - val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) - if err != nil { - iter.Error = err - return nil - } - return val -} - -// ReadBigInt read big.Int -func (iter *Iterator) ReadBigInt() (ret *big.Int) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return nil - } - ret = big.NewInt(0) - var success bool - ret, success = ret.SetString(str, 10) - if !success { - iter.ReportError("ReadBigInt", "invalid big int") - return nil - } - return ret -} - -//ReadFloat32 read float32 -func (iter *Iterator) ReadFloat32() (ret float32) { - c := iter.nextToken() - if c == '-' { - return -iter.readPositiveFloat32() - } - iter.unreadByte() - return iter.readPositiveFloat32() -} - -func (iter *Iterator) readPositiveFloat32() (ret float32) { - value := uint64(0) - c := byte(' ') - i := iter.head - // first char - if i == iter.tail { - return iter.readFloat32SlowPath() - } - c = iter.buf[i] - i++ - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat32SlowPath() - case endOfNumber: - iter.ReportError("readFloat32", "empty number") - return - case dotInNumber: - iter.ReportError("readFloat32", "leading dot is invalid") - return - case 0: - if i == iter.tail { - return iter.readFloat32SlowPath() - } - c = iter.buf[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - iter.ReportError("readFloat32", "leading zero is invalid") - return - } - } - value = uint64(ind) - // chars before dot -non_decimal_loop: - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat32SlowPath() - case endOfNumber: - iter.head = i - return float32(value) - case dotInNumber: - break non_decimal_loop - } - if value > uint64SafeToMultiple10 { - return iter.readFloat32SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; - } - // chars after dot - if c == '.' { - i++ - decimalPlaces := 0 - if i == iter.tail { - return iter.readFloat32SlowPath() - } - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case endOfNumber: - if decimalPlaces > 0 && decimalPlaces < len(pow10) { - iter.head = i - return float32(float64(value) / float64(pow10[decimalPlaces])) - } - // too many decimal places - return iter.readFloat32SlowPath() - case invalidCharForNumber: - fallthrough - case dotInNumber: - return iter.readFloat32SlowPath() - } - decimalPlaces++ - if value > uint64SafeToMultiple10 { - return iter.readFloat32SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) - } - } - return iter.readFloat32SlowPath() -} - -func (iter *Iterator) readNumberAsString() (ret string) { - strBuf := [16]byte{} - str := strBuf[0:0] -load_loop: - for { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - str = append(str, c) - continue - default: - iter.head = i - break load_loop - } - } - if !iter.loadMore() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - return - } - if len(str) == 0 { - iter.ReportError("readNumberAsString", "invalid number") - } - return *(*string)(unsafe.Pointer(&str)) -} - -func (iter *Iterator) readFloat32SlowPath() (ret float32) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return - } - errMsg := validateFloat(str) - if errMsg != "" { - iter.ReportError("readFloat32SlowPath", errMsg) - return - } - val, err := strconv.ParseFloat(str, 32) - if err != nil { - iter.Error = err - return - } - return float32(val) -} - -// ReadFloat64 read float64 -func (iter *Iterator) ReadFloat64() (ret float64) { - c := iter.nextToken() - if c == '-' { - return -iter.readPositiveFloat64() - } - iter.unreadByte() - return iter.readPositiveFloat64() -} - -func (iter *Iterator) readPositiveFloat64() (ret float64) { - value := uint64(0) - c := byte(' ') - i := iter.head - // first char - if i == iter.tail { - return iter.readFloat64SlowPath() - } - c = iter.buf[i] - i++ - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat64SlowPath() - case endOfNumber: - iter.ReportError("readFloat64", "empty number") - return - case dotInNumber: - iter.ReportError("readFloat64", "leading dot is invalid") - return - case 0: - if i == iter.tail { - return iter.readFloat64SlowPath() - } - c = iter.buf[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - iter.ReportError("readFloat64", "leading zero is invalid") - return - } - } - value = uint64(ind) - // chars before dot -non_decimal_loop: - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat64SlowPath() - case endOfNumber: - iter.head = i - return float64(value) - case dotInNumber: - break non_decimal_loop - } - if value > uint64SafeToMultiple10 { - return iter.readFloat64SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; - } - // chars after dot - if c == '.' { - i++ - decimalPlaces := 0 - if i == iter.tail { - return iter.readFloat64SlowPath() - } - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case endOfNumber: - if decimalPlaces > 0 && decimalPlaces < len(pow10) { - iter.head = i - return float64(value) / float64(pow10[decimalPlaces]) - } - // too many decimal places - return iter.readFloat64SlowPath() - case invalidCharForNumber: - fallthrough - case dotInNumber: - return iter.readFloat64SlowPath() - } - decimalPlaces++ - if value > uint64SafeToMultiple10 { - return iter.readFloat64SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) - } - } - return iter.readFloat64SlowPath() -} - -func (iter *Iterator) readFloat64SlowPath() (ret float64) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return - } - errMsg := validateFloat(str) - if errMsg != "" { - iter.ReportError("readFloat64SlowPath", errMsg) - return - } - val, err := strconv.ParseFloat(str, 64) - if err != nil { - iter.Error = err - return - } - return val -} - -func validateFloat(str string) string { - // strconv.ParseFloat is not validating `1.` or `1.e1` - if len(str) == 0 { - return "empty number" - } - if str[0] == '-' { - return "-- is not valid" - } - dotPos := strings.IndexByte(str, '.') - if dotPos != -1 { - if dotPos == len(str)-1 { - return "dot can not be last character" - } - switch str[dotPos+1] { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - default: - return "missing digit after dot" - } - } - return "" -} - -// ReadNumber read json.Number -func (iter *Iterator) ReadNumber() (ret json.Number) { - return json.Number(iter.readNumberAsString()) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_int.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_int.go deleted file mode 100644 index 2142320..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_int.go +++ /dev/null @@ -1,345 +0,0 @@ -package jsoniter - -import ( - "math" - "strconv" -) - -var intDigits []int8 - -const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 -const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 - -func init() { - intDigits = make([]int8, 256) - for i := 0; i < len(intDigits); i++ { - intDigits[i] = invalidCharForNumber - } - for i := int8('0'); i <= int8('9'); i++ { - intDigits[i] = i - int8('0') - } -} - -// ReadUint read uint -func (iter *Iterator) ReadUint() uint { - if strconv.IntSize == 32 { - return uint(iter.ReadUint32()) - } - return uint(iter.ReadUint64()) -} - -// ReadInt read int -func (iter *Iterator) ReadInt() int { - if strconv.IntSize == 32 { - return int(iter.ReadInt32()) - } - return int(iter.ReadInt64()) -} - -// ReadInt8 read int8 -func (iter *Iterator) ReadInt8() (ret int8) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint32(iter.readByte()) - if val > math.MaxInt8+1 { - iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return -int8(val) - } - val := iter.readUint32(c) - if val > math.MaxInt8 { - iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return int8(val) -} - -// ReadUint8 read uint8 -func (iter *Iterator) ReadUint8() (ret uint8) { - val := iter.readUint32(iter.nextToken()) - if val > math.MaxUint8 { - iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return uint8(val) -} - -// ReadInt16 read int16 -func (iter *Iterator) ReadInt16() (ret int16) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint32(iter.readByte()) - if val > math.MaxInt16+1 { - iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return -int16(val) - } - val := iter.readUint32(c) - if val > math.MaxInt16 { - iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return int16(val) -} - -// ReadUint16 read uint16 -func (iter *Iterator) ReadUint16() (ret uint16) { - val := iter.readUint32(iter.nextToken()) - if val > math.MaxUint16 { - iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return uint16(val) -} - -// ReadInt32 read int32 -func (iter *Iterator) ReadInt32() (ret int32) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint32(iter.readByte()) - if val > math.MaxInt32+1 { - iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return -int32(val) - } - val := iter.readUint32(c) - if val > math.MaxInt32 { - iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return int32(val) -} - -// ReadUint32 read uint32 -func (iter *Iterator) ReadUint32() (ret uint32) { - return iter.readUint32(iter.nextToken()) -} - -func (iter *Iterator) readUint32(c byte) (ret uint32) { - ind := intDigits[c] - if ind == 0 { - iter.assertInteger() - return 0 // single zero - } - if ind == invalidCharForNumber { - iter.ReportError("readUint32", "unexpected character: "+string([]byte{byte(ind)})) - return - } - value := uint32(ind) - if iter.tail-iter.head > 10 { - i := iter.head - ind2 := intDigits[iter.buf[i]] - if ind2 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - i++ - ind3 := intDigits[iter.buf[i]] - if ind3 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10 + uint32(ind2) - } - //iter.head = i + 1 - //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) - i++ - ind4 := intDigits[iter.buf[i]] - if ind4 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100 + uint32(ind2)*10 + uint32(ind3) - } - i++ - ind5 := intDigits[iter.buf[i]] - if ind5 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4) - } - i++ - ind6 := intDigits[iter.buf[i]] - if ind6 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5) - } - i++ - ind7 := intDigits[iter.buf[i]] - if ind7 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6) - } - i++ - ind8 := intDigits[iter.buf[i]] - if ind8 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7) - } - i++ - ind9 := intDigits[iter.buf[i]] - value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8) - iter.head = i - if ind9 == invalidCharForNumber { - iter.assertInteger() - return value - } - } - for { - for i := iter.head; i < iter.tail; i++ { - ind = intDigits[iter.buf[i]] - if ind == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - if value > uint32SafeToMultiply10 { - value2 := (value << 3) + (value << 1) + uint32(ind) - if value2 < value { - iter.ReportError("readUint32", "overflow") - return - } - value = value2 - continue - } - value = (value << 3) + (value << 1) + uint32(ind) - } - if !iter.loadMore() { - iter.assertInteger() - return value - } - } -} - -// ReadInt64 read int64 -func (iter *Iterator) ReadInt64() (ret int64) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint64(iter.readByte()) - if val > math.MaxInt64+1 { - iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) - return - } - return -int64(val) - } - val := iter.readUint64(c) - if val > math.MaxInt64 { - iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) - return - } - return int64(val) -} - -// ReadUint64 read uint64 -func (iter *Iterator) ReadUint64() uint64 { - return iter.readUint64(iter.nextToken()) -} - -func (iter *Iterator) readUint64(c byte) (ret uint64) { - ind := intDigits[c] - if ind == 0 { - iter.assertInteger() - return 0 // single zero - } - if ind == invalidCharForNumber { - iter.ReportError("readUint64", "unexpected character: "+string([]byte{byte(ind)})) - return - } - value := uint64(ind) - if iter.tail-iter.head > 10 { - i := iter.head - ind2 := intDigits[iter.buf[i]] - if ind2 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - i++ - ind3 := intDigits[iter.buf[i]] - if ind3 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10 + uint64(ind2) - } - //iter.head = i + 1 - //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) - i++ - ind4 := intDigits[iter.buf[i]] - if ind4 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100 + uint64(ind2)*10 + uint64(ind3) - } - i++ - ind5 := intDigits[iter.buf[i]] - if ind5 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4) - } - i++ - ind6 := intDigits[iter.buf[i]] - if ind6 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5) - } - i++ - ind7 := intDigits[iter.buf[i]] - if ind7 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6) - } - i++ - ind8 := intDigits[iter.buf[i]] - if ind8 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7) - } - i++ - ind9 := intDigits[iter.buf[i]] - value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8) - iter.head = i - if ind9 == invalidCharForNumber { - iter.assertInteger() - return value - } - } - for { - for i := iter.head; i < iter.tail; i++ { - ind = intDigits[iter.buf[i]] - if ind == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - if value > uint64SafeToMultiple10 { - value2 := (value << 3) + (value << 1) + uint64(ind) - if value2 < value { - iter.ReportError("readUint64", "overflow") - return - } - value = value2 - continue - } - value = (value << 3) + (value << 1) + uint64(ind) - } - if !iter.loadMore() { - iter.assertInteger() - return value - } - } -} - -func (iter *Iterator) assertInteger() { - if iter.head < len(iter.buf) && iter.buf[iter.head] == '.' { - iter.ReportError("assertInteger", "can not decode float as int") - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_object.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_object.go deleted file mode 100644 index 1c57576..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_object.go +++ /dev/null @@ -1,251 +0,0 @@ -package jsoniter - -import ( - "fmt" - "strings" -) - -// ReadObject read one field from object. -// If object ended, returns empty string. -// Otherwise, returns the field name. -func (iter *Iterator) ReadObject() (ret string) { - c := iter.nextToken() - switch c { - case 'n': - iter.skipThreeBytes('u', 'l', 'l') - return "" // null - case '{': - c = iter.nextToken() - if c == '"' { - iter.unreadByte() - field := iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - return field - } - if c == '}' { - return "" // end of object - } - iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) - return - case ',': - field := iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - return field - case '}': - return "" // end of object - default: - iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) - return - } -} - -// CaseInsensitive -func (iter *Iterator) readFieldHash() int64 { - hash := int64(0x811c9dc5) - c := iter.nextToken() - if c != '"' { - iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) - return 0 - } - for { - for i := iter.head; i < iter.tail; i++ { - // require ascii string and no escape - b := iter.buf[i] - if b == '\\' { - iter.head = i - for _, b := range iter.readStringSlowPath() { - if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { - b += 'a' - 'A' - } - hash ^= int64(b) - hash *= 0x1000193 - } - c = iter.nextToken() - if c != ':' { - iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) - return 0 - } - return hash - } - if b == '"' { - iter.head = i + 1 - c = iter.nextToken() - if c != ':' { - iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) - return 0 - } - return hash - } - if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { - b += 'a' - 'A' - } - hash ^= int64(b) - hash *= 0x1000193 - } - if !iter.loadMore() { - iter.ReportError("readFieldHash", `incomplete field name`) - return 0 - } - } -} - -func calcHash(str string, caseSensitive bool) int64 { - if !caseSensitive { - str = strings.ToLower(str) - } - hash := int64(0x811c9dc5) - for _, b := range []byte(str) { - hash ^= int64(b) - hash *= 0x1000193 - } - return int64(hash) -} - -// ReadObjectCB read object with callback, the key is ascii only and field name not copied -func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { - c := iter.nextToken() - var field string - if c == '{' { - c = iter.nextToken() - if c == '"' { - iter.unreadByte() - field = iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - if !callback(iter, field) { - return false - } - c = iter.nextToken() - for c == ',' { - field = iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - if !callback(iter, field) { - return false - } - c = iter.nextToken() - } - if c != '}' { - iter.ReportError("ReadObjectCB", `object not ended with }`) - return false - } - return true - } - if c == '}' { - return true - } - iter.ReportError("ReadObjectCB", `expect " after }, but found `+string([]byte{c})) - return false - } - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return true // null - } - iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) - return false -} - -// ReadMapCB read map with callback, the key can be any string -func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool { - c := iter.nextToken() - if c == '{' { - c = iter.nextToken() - if c == '"' { - iter.unreadByte() - field := iter.ReadString() - if iter.nextToken() != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - return false - } - if !callback(iter, field) { - return false - } - c = iter.nextToken() - for c == ',' { - field = iter.ReadString() - if iter.nextToken() != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - return false - } - if !callback(iter, field) { - return false - } - c = iter.nextToken() - } - if c != '}' { - iter.ReportError("ReadMapCB", `object not ended with }`) - return false - } - return true - } - if c == '}' { - return true - } - iter.ReportError("ReadMapCB", `expect " after }, but found `+string([]byte{c})) - return false - } - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return true // null - } - iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) - return false -} - -func (iter *Iterator) readObjectStart() bool { - c := iter.nextToken() - if c == '{' { - c = iter.nextToken() - if c == '}' { - return false - } - iter.unreadByte() - return true - } else if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return false - } - iter.ReportError("readObjectStart", "expect { or n, but found "+string([]byte{c})) - return false -} - -func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) { - str := iter.ReadStringAsSlice() - if iter.skipWhitespacesWithoutLoadMore() { - if ret == nil { - ret = make([]byte, len(str)) - copy(ret, str) - } - if !iter.loadMore() { - return - } - } - if iter.buf[iter.head] != ':' { - iter.ReportError("readObjectFieldAsBytes", "expect : after object field, but found "+string([]byte{iter.buf[iter.head]})) - return - } - iter.head++ - if iter.skipWhitespacesWithoutLoadMore() { - if ret == nil { - ret = make([]byte, len(str)) - copy(ret, str) - } - if !iter.loadMore() { - return - } - } - if ret == nil { - return str - } - return ret -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip.go deleted file mode 100644 index f58beb9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip.go +++ /dev/null @@ -1,129 +0,0 @@ -package jsoniter - -import "fmt" - -// ReadNil reads a json object as nil and -// returns whether it's a nil or not -func (iter *Iterator) ReadNil() (ret bool) { - c := iter.nextToken() - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') // null - return true - } - iter.unreadByte() - return false -} - -// ReadBool reads a json object as BoolValue -func (iter *Iterator) ReadBool() (ret bool) { - c := iter.nextToken() - if c == 't' { - iter.skipThreeBytes('r', 'u', 'e') - return true - } - if c == 'f' { - iter.skipFourBytes('a', 'l', 's', 'e') - return false - } - iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) - return -} - -// SkipAndReturnBytes skip next JSON element, and return its content as []byte. -// The []byte can be kept, it is a copy of data. -func (iter *Iterator) SkipAndReturnBytes() []byte { - iter.startCapture(iter.head) - iter.Skip() - return iter.stopCapture() -} - -type captureBuffer struct { - startedAt int - captured []byte -} - -func (iter *Iterator) startCapture(captureStartedAt int) { - if iter.captured != nil { - panic("already in capture mode") - } - iter.captureStartedAt = captureStartedAt - iter.captured = make([]byte, 0, 32) -} - -func (iter *Iterator) stopCapture() []byte { - if iter.captured == nil { - panic("not in capture mode") - } - captured := iter.captured - remaining := iter.buf[iter.captureStartedAt:iter.head] - iter.captureStartedAt = -1 - iter.captured = nil - if len(captured) == 0 { - copied := make([]byte, len(remaining)) - copy(copied, remaining) - return copied - } - captured = append(captured, remaining...) - return captured -} - -// Skip skips a json object and positions to relatively the next json object -func (iter *Iterator) Skip() { - c := iter.nextToken() - switch c { - case '"': - iter.skipString() - case 'n': - iter.skipThreeBytes('u', 'l', 'l') // null - case 't': - iter.skipThreeBytes('r', 'u', 'e') // true - case 'f': - iter.skipFourBytes('a', 'l', 's', 'e') // false - case '0': - iter.unreadByte() - iter.ReadFloat32() - case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': - iter.skipNumber() - case '[': - iter.skipArray() - case '{': - iter.skipObject() - default: - iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) - return - } -} - -func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) { - if iter.readByte() != b1 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } - if iter.readByte() != b2 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } - if iter.readByte() != b3 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } - if iter.readByte() != b4 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } -} - -func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) { - if iter.readByte() != b1 { - iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) - return - } - if iter.readByte() != b2 { - iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) - return - } - if iter.readByte() != b3 { - iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) - return - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip_sloppy.go deleted file mode 100644 index 8fcdc3b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip_sloppy.go +++ /dev/null @@ -1,144 +0,0 @@ -//+build jsoniter_sloppy - -package jsoniter - -// sloppy but faster implementation, do not validate the input json - -func (iter *Iterator) skipNumber() { - for { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case ' ', '\n', '\r', '\t', ',', '}', ']': - iter.head = i - return - } - } - if !iter.loadMore() { - return - } - } -} - -func (iter *Iterator) skipArray() { - level := 1 - for { - for i := iter.head; i < iter.tail; i++ { - switch iter.buf[i] { - case '"': // If inside string, skip it - iter.head = i + 1 - iter.skipString() - i = iter.head - 1 // it will be i++ soon - case '[': // If open symbol, increase level - level++ - case ']': // If close symbol, increase level - level-- - - // If we have returned to the original level, we're done - if level == 0 { - iter.head = i + 1 - return - } - } - } - if !iter.loadMore() { - iter.ReportError("skipObject", "incomplete array") - return - } - } -} - -func (iter *Iterator) skipObject() { - level := 1 - for { - for i := iter.head; i < iter.tail; i++ { - switch iter.buf[i] { - case '"': // If inside string, skip it - iter.head = i + 1 - iter.skipString() - i = iter.head - 1 // it will be i++ soon - case '{': // If open symbol, increase level - level++ - case '}': // If close symbol, increase level - level-- - - // If we have returned to the original level, we're done - if level == 0 { - iter.head = i + 1 - return - } - } - } - if !iter.loadMore() { - iter.ReportError("skipObject", "incomplete object") - return - } - } -} - -func (iter *Iterator) skipString() { - for { - end, escaped := iter.findStringEnd() - if end == -1 { - if !iter.loadMore() { - iter.ReportError("skipString", "incomplete string") - return - } - if escaped { - iter.head = 1 // skip the first char as last char read is \ - } - } else { - iter.head = end - return - } - } -} - -// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go -// Tries to find the end of string -// Support if string contains escaped quote symbols. -func (iter *Iterator) findStringEnd() (int, bool) { - escaped := false - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - if c == '"' { - if !escaped { - return i + 1, false - } - j := i - 1 - for { - if j < iter.head || iter.buf[j] != '\\' { - // even number of backslashes - // either end of buffer, or " found - return i + 1, true - } - j-- - if j < iter.head || iter.buf[j] != '\\' { - // odd number of backslashes - // it is \" or \\\" - break - } - j-- - } - } else if c == '\\' { - escaped = true - } - } - j := iter.tail - 1 - for { - if j < iter.head || iter.buf[j] != '\\' { - // even number of backslashes - // either end of buffer, or " found - return -1, false // do not end with \ - } - j-- - if j < iter.head || iter.buf[j] != '\\' { - // odd number of backslashes - // it is \" or \\\" - break - } - j-- - - } - return -1, true // end with \ -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip_strict.go deleted file mode 100644 index f67bc2e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_skip_strict.go +++ /dev/null @@ -1,89 +0,0 @@ -//+build !jsoniter_sloppy - -package jsoniter - -import "fmt" - -func (iter *Iterator) skipNumber() { - if !iter.trySkipNumber() { - iter.unreadByte() - iter.ReadFloat32() - } -} - -func (iter *Iterator) trySkipNumber() bool { - dotFound := false - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - case '.': - if dotFound { - iter.ReportError("validateNumber", `more than one dot found in number`) - return true // already failed - } - if i+1 == iter.tail { - return false - } - c = iter.buf[i+1] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - default: - iter.ReportError("validateNumber", `missing digit after dot`) - return true // already failed - } - dotFound = true - default: - switch c { - case ',', ']', '}', ' ', '\t', '\n', '\r': - if iter.head == i { - return false // if - without following digits - } - iter.head = i - return true // must be valid - } - return false // may be invalid - } - } - return false -} - -func (iter *Iterator) skipString() { - if !iter.trySkipString() { - iter.unreadByte() - iter.ReadString() - } -} - -func (iter *Iterator) trySkipString() bool { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - if c == '"' { - iter.head = i + 1 - return true // valid - } else if c == '\\' { - return false - } else if c < ' ' { - iter.ReportError("trySkipString", - fmt.Sprintf(`invalid control character found: %d`, c)) - return true // already failed - } - } - return false -} - -func (iter *Iterator) skipObject() { - iter.unreadByte() - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - iter.Skip() - return true - }) -} - -func (iter *Iterator) skipArray() { - iter.unreadByte() - iter.ReadArrayCB(func(iter *Iterator) bool { - iter.Skip() - return true - }) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_str.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_str.go deleted file mode 100644 index adc487e..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/iter_str.go +++ /dev/null @@ -1,215 +0,0 @@ -package jsoniter - -import ( - "fmt" - "unicode/utf16" -) - -// ReadString read string from iterator -func (iter *Iterator) ReadString() (ret string) { - c := iter.nextToken() - if c == '"' { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - if c == '"' { - ret = string(iter.buf[iter.head:i]) - iter.head = i + 1 - return ret - } else if c == '\\' { - break - } else if c < ' ' { - iter.ReportError("ReadString", - fmt.Sprintf(`invalid control character found: %d`, c)) - return - } - } - return iter.readStringSlowPath() - } else if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return "" - } - iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) - return -} - -func (iter *Iterator) readStringSlowPath() (ret string) { - var str []byte - var c byte - for iter.Error == nil { - c = iter.readByte() - if c == '"' { - return string(str) - } - if c == '\\' { - c = iter.readByte() - str = iter.readEscapedChar(c, str) - } else { - str = append(str, c) - } - } - iter.ReportError("readStringSlowPath", "unexpected end of input") - return -} - -func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte { - switch c { - case 'u': - r := iter.readU4() - if utf16.IsSurrogate(r) { - c = iter.readByte() - if iter.Error != nil { - return nil - } - if c != '\\' { - iter.unreadByte() - str = appendRune(str, r) - return str - } - c = iter.readByte() - if iter.Error != nil { - return nil - } - if c != 'u' { - str = appendRune(str, r) - return iter.readEscapedChar(c, str) - } - r2 := iter.readU4() - if iter.Error != nil { - return nil - } - combined := utf16.DecodeRune(r, r2) - if combined == '\uFFFD' { - str = appendRune(str, r) - str = appendRune(str, r2) - } else { - str = appendRune(str, combined) - } - } else { - str = appendRune(str, r) - } - case '"': - str = append(str, '"') - case '\\': - str = append(str, '\\') - case '/': - str = append(str, '/') - case 'b': - str = append(str, '\b') - case 'f': - str = append(str, '\f') - case 'n': - str = append(str, '\n') - case 'r': - str = append(str, '\r') - case 't': - str = append(str, '\t') - default: - iter.ReportError("readEscapedChar", - `invalid escape char after \`) - return nil - } - return str -} - -// ReadStringAsSlice read string from iterator without copying into string form. -// The []byte can not be kept, as it will change after next iterator call. -func (iter *Iterator) ReadStringAsSlice() (ret []byte) { - c := iter.nextToken() - if c == '"' { - for i := iter.head; i < iter.tail; i++ { - // require ascii string and no escape - // for: field name, base64, number - if iter.buf[i] == '"' { - // fast path: reuse the underlying buffer - ret = iter.buf[iter.head:i] - iter.head = i + 1 - return ret - } - } - readLen := iter.tail - iter.head - copied := make([]byte, readLen, readLen*2) - copy(copied, iter.buf[iter.head:iter.tail]) - iter.head = iter.tail - for iter.Error == nil { - c := iter.readByte() - if c == '"' { - return copied - } - copied = append(copied, c) - } - return copied - } - iter.ReportError("ReadStringAsSlice", `expects " or n, but found `+string([]byte{c})) - return -} - -func (iter *Iterator) readU4() (ret rune) { - for i := 0; i < 4; i++ { - c := iter.readByte() - if iter.Error != nil { - return - } - if c >= '0' && c <= '9' { - ret = ret*16 + rune(c-'0') - } else if c >= 'a' && c <= 'f' { - ret = ret*16 + rune(c-'a'+10) - } else if c >= 'A' && c <= 'F' { - ret = ret*16 + rune(c-'A'+10) - } else { - iter.ReportError("readU4", "expects 0~9 or a~f, but found "+string([]byte{c})) - return - } - } - return ret -} - -const ( - t1 = 0x00 // 0000 0000 - tx = 0x80 // 1000 0000 - t2 = 0xC0 // 1100 0000 - t3 = 0xE0 // 1110 0000 - t4 = 0xF0 // 1111 0000 - t5 = 0xF8 // 1111 1000 - - maskx = 0x3F // 0011 1111 - mask2 = 0x1F // 0001 1111 - mask3 = 0x0F // 0000 1111 - mask4 = 0x07 // 0000 0111 - - rune1Max = 1<<7 - 1 - rune2Max = 1<<11 - 1 - rune3Max = 1<<16 - 1 - - surrogateMin = 0xD800 - surrogateMax = 0xDFFF - - maxRune = '\U0010FFFF' // Maximum valid Unicode code point. - runeError = '\uFFFD' // the "error" Rune or "Unicode replacement character" -) - -func appendRune(p []byte, r rune) []byte { - // Negative values are erroneous. Making it unsigned addresses the problem. - switch i := uint32(r); { - case i <= rune1Max: - p = append(p, byte(r)) - return p - case i <= rune2Max: - p = append(p, t2|byte(r>>6)) - p = append(p, tx|byte(r)&maskx) - return p - case i > maxRune, surrogateMin <= i && i <= surrogateMax: - r = runeError - fallthrough - case i <= rune3Max: - p = append(p, t3|byte(r>>12)) - p = append(p, tx|byte(r>>6)&maskx) - p = append(p, tx|byte(r)&maskx) - return p - default: - p = append(p, t4|byte(r>>18)) - p = append(p, tx|byte(r>>12)&maskx) - p = append(p, tx|byte(r>>6)&maskx) - p = append(p, tx|byte(r)&maskx) - return p - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/jsoniter.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/jsoniter.go deleted file mode 100644 index c2934f9..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/jsoniter.go +++ /dev/null @@ -1,18 +0,0 @@ -// Package jsoniter implements encoding and decoding of JSON as defined in -// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json. -// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter -// and variable type declarations (if any). -// jsoniter interfaces gives 100% compatibility with code using standard lib. -// -// "JSON and Go" -// (https://golang.org/doc/articles/json_and_go.html) -// gives a description of how Marshal/Unmarshal operate -// between arbitrary or predefined json objects and bytes, -// and it applies to jsoniter.Marshal/Unmarshal as well. -// -// Besides, jsoniter.Iterator provides a different set of interfaces -// iterating given bytes/string/reader -// and yielding parsed elements one by one. -// This set of interfaces reads input as required and gives -// better performance. -package jsoniter diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/pool.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/pool.go deleted file mode 100644 index e2389b5..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/pool.go +++ /dev/null @@ -1,42 +0,0 @@ -package jsoniter - -import ( - "io" -) - -// IteratorPool a thread safe pool of iterators with same configuration -type IteratorPool interface { - BorrowIterator(data []byte) *Iterator - ReturnIterator(iter *Iterator) -} - -// StreamPool a thread safe pool of streams with same configuration -type StreamPool interface { - BorrowStream(writer io.Writer) *Stream - ReturnStream(stream *Stream) -} - -func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream { - stream := cfg.streamPool.Get().(*Stream) - stream.Reset(writer) - return stream -} - -func (cfg *frozenConfig) ReturnStream(stream *Stream) { - stream.out = nil - stream.Error = nil - stream.Attachment = nil - cfg.streamPool.Put(stream) -} - -func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator { - iter := cfg.iteratorPool.Get().(*Iterator) - iter.ResetBytes(data) - return iter -} - -func (cfg *frozenConfig) ReturnIterator(iter *Iterator) { - iter.Error = nil - iter.Attachment = nil - cfg.iteratorPool.Put(iter) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect.go deleted file mode 100644 index 4459e20..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect.go +++ /dev/null @@ -1,332 +0,0 @@ -package jsoniter - -import ( - "fmt" - "reflect" - "unsafe" - - "github.com/modern-go/reflect2" -) - -// ValDecoder is an internal type registered to cache as needed. -// Don't confuse jsoniter.ValDecoder with json.Decoder. -// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). -// -// Reflection on type to create decoders, which is then cached -// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions -// 1. create instance of new value, for example *int will need a int to be allocated -// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New -// 3. assignment to map, both key and value will be reflect.Value -// For a simple struct binding, it will be reflect.Value free and allocation free -type ValDecoder interface { - Decode(ptr unsafe.Pointer, iter *Iterator) -} - -// ValEncoder is an internal type registered to cache as needed. -// Don't confuse jsoniter.ValEncoder with json.Encoder. -// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). -type ValEncoder interface { - IsEmpty(ptr unsafe.Pointer) bool - Encode(ptr unsafe.Pointer, stream *Stream) -} - -type checkIsEmpty interface { - IsEmpty(ptr unsafe.Pointer) bool -} - -type ctx struct { - *frozenConfig - prefix string - encoders map[reflect2.Type]ValEncoder - decoders map[reflect2.Type]ValDecoder -} - -func (b *ctx) caseSensitive() bool { - if b.frozenConfig == nil { - // default is case-insensitive - return false - } - return b.frozenConfig.caseSensitive -} - -func (b *ctx) append(prefix string) *ctx { - return &ctx{ - frozenConfig: b.frozenConfig, - prefix: b.prefix + " " + prefix, - encoders: b.encoders, - decoders: b.decoders, - } -} - -// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal -func (iter *Iterator) ReadVal(obj interface{}) { - cacheKey := reflect2.RTypeOf(obj) - decoder := iter.cfg.getDecoderFromCache(cacheKey) - if decoder == nil { - typ := reflect2.TypeOf(obj) - if typ.Kind() != reflect.Ptr { - iter.ReportError("ReadVal", "can only unmarshal into pointer") - return - } - decoder = iter.cfg.DecoderOf(typ) - } - ptr := reflect2.PtrOf(obj) - if ptr == nil { - iter.ReportError("ReadVal", "can not read into nil pointer") - return - } - decoder.Decode(ptr, iter) -} - -// WriteVal copy the go interface into underlying JSON, same as json.Marshal -func (stream *Stream) WriteVal(val interface{}) { - if nil == val { - stream.WriteNil() - return - } - cacheKey := reflect2.RTypeOf(val) - encoder := stream.cfg.getEncoderFromCache(cacheKey) - if encoder == nil { - typ := reflect2.TypeOf(val) - encoder = stream.cfg.EncoderOf(typ) - } - encoder.Encode(reflect2.PtrOf(val), stream) -} - -func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder { - cacheKey := typ.RType() - decoder := cfg.getDecoderFromCache(cacheKey) - if decoder != nil { - return decoder - } - ctx := &ctx{ - frozenConfig: cfg, - prefix: "", - decoders: map[reflect2.Type]ValDecoder{}, - encoders: map[reflect2.Type]ValEncoder{}, - } - ptrType := typ.(*reflect2.UnsafePtrType) - decoder = decoderOfType(ctx, ptrType.Elem()) - cfg.addDecoderToCache(cacheKey, decoder) - return decoder -} - -func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := getTypeDecoderFromExtension(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfType(ctx, typ) - for _, extension := range extensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) - for _, extension := range ctx.extraExtensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - return decoder -} - -func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := ctx.decoders[typ] - if decoder != nil { - return decoder - } - placeholder := &placeholderDecoder{} - ctx.decoders[typ] = placeholder - decoder = _createDecoderOfType(ctx, typ) - placeholder.decoder = decoder - return decoder -} - -func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := createDecoderOfJsonRawMessage(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfJsonNumber(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfMarshaler(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfAny(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfNative(ctx, typ) - if decoder != nil { - return decoder - } - switch typ.Kind() { - case reflect.Interface: - ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType) - if isIFace { - return &ifaceDecoder{valType: ifaceType} - } - return &efaceDecoder{} - case reflect.Struct: - return decoderOfStruct(ctx, typ) - case reflect.Array: - return decoderOfArray(ctx, typ) - case reflect.Slice: - return decoderOfSlice(ctx, typ) - case reflect.Map: - return decoderOfMap(ctx, typ) - case reflect.Ptr: - return decoderOfOptional(ctx, typ) - default: - return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} - } -} - -func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder { - cacheKey := typ.RType() - encoder := cfg.getEncoderFromCache(cacheKey) - if encoder != nil { - return encoder - } - ctx := &ctx{ - frozenConfig: cfg, - prefix: "", - decoders: map[reflect2.Type]ValDecoder{}, - encoders: map[reflect2.Type]ValEncoder{}, - } - encoder = encoderOfType(ctx, typ) - if typ.LikePtr() { - encoder = &onePtrEncoder{encoder} - } - cfg.addEncoderToCache(cacheKey, encoder) - return encoder -} - -type onePtrEncoder struct { - encoder ValEncoder -} - -func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) -} - -func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) -} - -func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := getTypeEncoderFromExtension(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfType(ctx, typ) - for _, extension := range extensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) - for _, extension := range ctx.extraExtensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - return encoder -} - -func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := ctx.encoders[typ] - if encoder != nil { - return encoder - } - placeholder := &placeholderEncoder{} - ctx.encoders[typ] = placeholder - encoder = _createEncoderOfType(ctx, typ) - placeholder.encoder = encoder - return encoder -} -func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := createEncoderOfJsonRawMessage(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfJsonNumber(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfMarshaler(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfAny(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfNative(ctx, typ) - if encoder != nil { - return encoder - } - kind := typ.Kind() - switch kind { - case reflect.Interface: - return &dynamicEncoder{typ} - case reflect.Struct: - return encoderOfStruct(ctx, typ) - case reflect.Array: - return encoderOfArray(ctx, typ) - case reflect.Slice: - return encoderOfSlice(ctx, typ) - case reflect.Map: - return encoderOfMap(ctx, typ) - case reflect.Ptr: - return encoderOfOptional(ctx, typ) - default: - return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} - } -} - -type lazyErrorDecoder struct { - err error -} - -func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.WhatIsNext() != NilValue { - if iter.Error == nil { - iter.Error = decoder.err - } - } else { - iter.Skip() - } -} - -type lazyErrorEncoder struct { - err error -} - -func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if ptr == nil { - stream.WriteNil() - } else if stream.Error == nil { - stream.Error = encoder.err - } -} - -func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type placeholderDecoder struct { - decoder ValDecoder -} - -func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.decoder.Decode(ptr, iter) -} - -type placeholderEncoder struct { - encoder ValEncoder -} - -func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.encoder.Encode(ptr, stream) -} - -func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.encoder.IsEmpty(ptr) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_array.go deleted file mode 100644 index 13a0b7b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_array.go +++ /dev/null @@ -1,104 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "unsafe" -) - -func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { - arrayType := typ.(*reflect2.UnsafeArrayType) - decoder := decoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) - return &arrayDecoder{arrayType, decoder} -} - -func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder { - arrayType := typ.(*reflect2.UnsafeArrayType) - if arrayType.Len() == 0 { - return emptyArrayEncoder{} - } - encoder := encoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) - return &arrayEncoder{arrayType, encoder} -} - -type emptyArrayEncoder struct{} - -func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteEmptyArray() -} - -func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return true -} - -type arrayEncoder struct { - arrayType *reflect2.UnsafeArrayType - elemEncoder ValEncoder -} - -func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteArrayStart() - elemPtr := unsafe.Pointer(ptr) - encoder.elemEncoder.Encode(elemPtr, stream) - for i := 1; i < encoder.arrayType.Len(); i++ { - stream.WriteMore() - elemPtr = encoder.arrayType.UnsafeGetIndex(ptr, i) - encoder.elemEncoder.Encode(elemPtr, stream) - } - stream.WriteArrayEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) - } -} - -func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type arrayDecoder struct { - arrayType *reflect2.UnsafeArrayType - elemDecoder ValDecoder -} - -func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.doDecode(ptr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) - } -} - -func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - arrayType := decoder.arrayType - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return - } - if c != '[' { - iter.ReportError("decode array", "expect [ or n, but found "+string([]byte{c})) - return - } - c = iter.nextToken() - if c == ']' { - return - } - iter.unreadByte() - elemPtr := arrayType.UnsafeGetIndex(ptr, 0) - decoder.elemDecoder.Decode(elemPtr, iter) - length := 1 - for c = iter.nextToken(); c == ','; c = iter.nextToken() { - if length >= arrayType.Len() { - iter.Skip() - continue - } - idx := length - length += 1 - elemPtr = arrayType.UnsafeGetIndex(ptr, idx) - decoder.elemDecoder.Decode(elemPtr, iter) - } - if c != ']' { - iter.ReportError("decode array", "expect ], but found "+string([]byte{c})) - return - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_dynamic.go deleted file mode 100644 index 8b6bc8b..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_dynamic.go +++ /dev/null @@ -1,70 +0,0 @@ -package jsoniter - -import ( - "github.com/modern-go/reflect2" - "reflect" - "unsafe" -) - -type dynamicEncoder struct { - valType reflect2.Type -} - -func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - stream.WriteVal(obj) -} - -func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.valType.UnsafeIndirect(ptr) == nil -} - -type efaceDecoder struct { -} - -func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - pObj := (*interface{})(ptr) - obj := *pObj - if obj == nil { - *pObj = iter.Read() - return - } - typ := reflect2.TypeOf(obj) - if typ.Kind() != reflect.Ptr { - *pObj = iter.Read() - return - } - ptrType := typ.(*reflect2.UnsafePtrType) - ptrElemType := ptrType.Elem() - if iter.WhatIsNext() == NilValue { - if ptrElemType.Kind() != reflect.Ptr { - iter.skipFourBytes('n', 'u', 'l', 'l') - *pObj = nil - return - } - } - if reflect2.IsNil(obj) { - obj := ptrElemType.New() - iter.ReadVal(obj) - *pObj = obj - return - } - iter.ReadVal(obj) -} - -type ifaceDecoder struct { - valType *reflect2.UnsafeIFaceType -} - -func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew()) - return - } - obj := decoder.valType.UnsafeIndirect(ptr) - if reflect2.IsNil(obj) { - iter.ReportError("decode non empty interface", "can not unmarshal into nil") - return - } - iter.ReadVal(obj) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_extension.go deleted file mode 100644 index 04f6875..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_extension.go +++ /dev/null @@ -1,483 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "reflect" - "sort" - "strings" - "unicode" - "unsafe" -) - -var typeDecoders = map[string]ValDecoder{} -var fieldDecoders = map[string]ValDecoder{} -var typeEncoders = map[string]ValEncoder{} -var fieldEncoders = map[string]ValEncoder{} -var extensions = []Extension{} - -// StructDescriptor describe how should we encode/decode the struct -type StructDescriptor struct { - Type reflect2.Type - Fields []*Binding -} - -// GetField get one field from the descriptor by its name. -// Can not use map here to keep field orders. -func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { - for _, binding := range structDescriptor.Fields { - if binding.Field.Name() == fieldName { - return binding - } - } - return nil -} - -// Binding describe how should we encode/decode the struct field -type Binding struct { - levels []int - Field reflect2.StructField - FromNames []string - ToNames []string - Encoder ValEncoder - Decoder ValDecoder -} - -// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder. -// Can also rename fields by UpdateStructDescriptor. -type Extension interface { - UpdateStructDescriptor(structDescriptor *StructDescriptor) - CreateMapKeyDecoder(typ reflect2.Type) ValDecoder - CreateMapKeyEncoder(typ reflect2.Type) ValEncoder - CreateDecoder(typ reflect2.Type) ValDecoder - CreateEncoder(typ reflect2.Type) ValEncoder - DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder - DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder -} - -// DummyExtension embed this type get dummy implementation for all methods of Extension -type DummyExtension struct { -} - -// UpdateStructDescriptor No-op -func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { -} - -// CreateMapKeyDecoder No-op -func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateMapKeyEncoder No-op -func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// CreateDecoder No-op -func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateEncoder No-op -func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// DecorateDecoder No-op -func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { - return decoder -} - -// DecorateEncoder No-op -func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { - return encoder -} - -type EncoderExtension map[reflect2.Type]ValEncoder - -// UpdateStructDescriptor No-op -func (extension EncoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { -} - -// CreateDecoder No-op -func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateEncoder get encoder from map -func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { - return extension[typ] -} - -// CreateMapKeyDecoder No-op -func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateMapKeyEncoder No-op -func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// DecorateDecoder No-op -func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { - return decoder -} - -// DecorateEncoder No-op -func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { - return encoder -} - -type DecoderExtension map[reflect2.Type]ValDecoder - -// UpdateStructDescriptor No-op -func (extension DecoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { -} - -// CreateMapKeyDecoder No-op -func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateMapKeyEncoder No-op -func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// CreateDecoder get decoder from map -func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { - return extension[typ] -} - -// CreateEncoder No-op -func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// DecorateDecoder No-op -func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { - return decoder -} - -// DecorateEncoder No-op -func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { - return encoder -} - -type funcDecoder struct { - fun DecoderFunc -} - -func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.fun(ptr, iter) -} - -type funcEncoder struct { - fun EncoderFunc - isEmptyFunc func(ptr unsafe.Pointer) bool -} - -func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.fun(ptr, stream) -} - -func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { - if encoder.isEmptyFunc == nil { - return false - } - return encoder.isEmptyFunc(ptr) -} - -// DecoderFunc the function form of TypeDecoder -type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator) - -// EncoderFunc the function form of TypeEncoder -type EncoderFunc func(ptr unsafe.Pointer, stream *Stream) - -// RegisterTypeDecoderFunc register TypeDecoder for a type with function -func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) { - typeDecoders[typ] = &funcDecoder{fun} -} - -// RegisterTypeDecoder register TypeDecoder for a typ -func RegisterTypeDecoder(typ string, decoder ValDecoder) { - typeDecoders[typ] = decoder -} - -// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function -func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { - RegisterFieldDecoder(typ, field, &funcDecoder{fun}) -} - -// RegisterFieldDecoder register TypeDecoder for a struct field -func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { - fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder -} - -// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function -func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { - typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc} -} - -// RegisterTypeEncoder register TypeEncoder for a type -func RegisterTypeEncoder(typ string, encoder ValEncoder) { - typeEncoders[typ] = encoder -} - -// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function -func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { - RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc}) -} - -// RegisterFieldEncoder register TypeEncoder for a struct field -func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { - fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder -} - -// RegisterExtension register extension -func RegisterExtension(extension Extension) { - extensions = append(extensions, extension) -} - -func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := _getTypeDecoderFromExtension(ctx, typ) - if decoder != nil { - for _, extension := range extensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) - for _, extension := range ctx.extraExtensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - } - return decoder -} -func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { - for _, extension := range extensions { - decoder := extension.CreateDecoder(typ) - if decoder != nil { - return decoder - } - } - decoder := ctx.decoderExtension.CreateDecoder(typ) - if decoder != nil { - return decoder - } - for _, extension := range ctx.extraExtensions { - decoder := extension.CreateDecoder(typ) - if decoder != nil { - return decoder - } - } - typeName := typ.String() - decoder = typeDecoders[typeName] - if decoder != nil { - return decoder - } - if typ.Kind() == reflect.Ptr { - ptrType := typ.(*reflect2.UnsafePtrType) - decoder := typeDecoders[ptrType.Elem().String()] - if decoder != nil { - return &OptionalDecoder{ptrType.Elem(), decoder} - } - } - return nil -} - -func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := _getTypeEncoderFromExtension(ctx, typ) - if encoder != nil { - for _, extension := range extensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) - for _, extension := range ctx.extraExtensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - } - return encoder -} - -func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { - for _, extension := range extensions { - encoder := extension.CreateEncoder(typ) - if encoder != nil { - return encoder - } - } - encoder := ctx.encoderExtension.CreateEncoder(typ) - if encoder != nil { - return encoder - } - for _, extension := range ctx.extraExtensions { - encoder := extension.CreateEncoder(typ) - if encoder != nil { - return encoder - } - } - typeName := typ.String() - encoder = typeEncoders[typeName] - if encoder != nil { - return encoder - } - if typ.Kind() == reflect.Ptr { - typePtr := typ.(*reflect2.UnsafePtrType) - encoder := typeEncoders[typePtr.Elem().String()] - if encoder != nil { - return &OptionalEncoder{encoder} - } - } - return nil -} - -func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { - structType := typ.(*reflect2.UnsafeStructType) - embeddedBindings := []*Binding{} - bindings := []*Binding{} - for i := 0; i < structType.NumField(); i++ { - field := structType.Field(i) - tag, hastag := field.Tag().Lookup(ctx.getTagKey()) - if ctx.onlyTaggedField && !hastag { - continue - } - tagParts := strings.Split(tag, ",") - if tag == "-" { - continue - } - if field.Anonymous() && (tag == "" || tagParts[0] == "") { - if field.Type().Kind() == reflect.Struct { - structDescriptor := describeStruct(ctx, field.Type()) - for _, binding := range structDescriptor.Fields { - binding.levels = append([]int{i}, binding.levels...) - omitempty := binding.Encoder.(*structFieldEncoder).omitempty - binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} - binding.Decoder = &structFieldDecoder{field, binding.Decoder} - embeddedBindings = append(embeddedBindings, binding) - } - continue - } else if field.Type().Kind() == reflect.Ptr { - ptrType := field.Type().(*reflect2.UnsafePtrType) - if ptrType.Elem().Kind() == reflect.Struct { - structDescriptor := describeStruct(ctx, ptrType.Elem()) - for _, binding := range structDescriptor.Fields { - binding.levels = append([]int{i}, binding.levels...) - omitempty := binding.Encoder.(*structFieldEncoder).omitempty - binding.Encoder = &dereferenceEncoder{binding.Encoder} - binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} - binding.Decoder = &dereferenceDecoder{ptrType.Elem(), binding.Decoder} - binding.Decoder = &structFieldDecoder{field, binding.Decoder} - embeddedBindings = append(embeddedBindings, binding) - } - continue - } - } - } - fieldNames := calcFieldNames(field.Name(), tagParts[0], tag) - fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name()) - decoder := fieldDecoders[fieldCacheKey] - if decoder == nil { - decoder = decoderOfType(ctx.append(field.Name()), field.Type()) - } - encoder := fieldEncoders[fieldCacheKey] - if encoder == nil { - encoder = encoderOfType(ctx.append(field.Name()), field.Type()) - } - binding := &Binding{ - Field: field, - FromNames: fieldNames, - ToNames: fieldNames, - Decoder: decoder, - Encoder: encoder, - } - binding.levels = []int{i} - bindings = append(bindings, binding) - } - return createStructDescriptor(ctx, typ, bindings, embeddedBindings) -} -func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { - structDescriptor := &StructDescriptor{ - Type: typ, - Fields: bindings, - } - for _, extension := range extensions { - extension.UpdateStructDescriptor(structDescriptor) - } - ctx.encoderExtension.UpdateStructDescriptor(structDescriptor) - ctx.decoderExtension.UpdateStructDescriptor(structDescriptor) - for _, extension := range ctx.extraExtensions { - extension.UpdateStructDescriptor(structDescriptor) - } - processTags(structDescriptor, ctx.frozenConfig) - // merge normal & embedded bindings & sort with original order - allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...)) - sort.Sort(allBindings) - structDescriptor.Fields = allBindings - return structDescriptor -} - -type sortableBindings []*Binding - -func (bindings sortableBindings) Len() int { - return len(bindings) -} - -func (bindings sortableBindings) Less(i, j int) bool { - left := bindings[i].levels - right := bindings[j].levels - k := 0 - for { - if left[k] < right[k] { - return true - } else if left[k] > right[k] { - return false - } - k++ - } -} - -func (bindings sortableBindings) Swap(i, j int) { - bindings[i], bindings[j] = bindings[j], bindings[i] -} - -func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) { - for _, binding := range structDescriptor.Fields { - shouldOmitEmpty := false - tagParts := strings.Split(binding.Field.Tag().Get(cfg.getTagKey()), ",") - for _, tagPart := range tagParts[1:] { - if tagPart == "omitempty" { - shouldOmitEmpty = true - } else if tagPart == "string" { - if binding.Field.Type().Kind() == reflect.String { - binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg} - binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg} - } else { - binding.Decoder = &stringModeNumberDecoder{binding.Decoder} - binding.Encoder = &stringModeNumberEncoder{binding.Encoder} - } - } - } - binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder} - binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty} - } -} - -func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string { - // ignore? - if wholeTag == "-" { - return []string{} - } - // rename? - var fieldNames []string - if tagProvidedFieldName == "" { - fieldNames = []string{originalFieldName} - } else { - fieldNames = []string{tagProvidedFieldName} - } - // private? - isNotExported := unicode.IsLower(rune(originalFieldName[0])) - if isNotExported { - fieldNames = []string{} - } - return fieldNames -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_json_number.go deleted file mode 100644 index 98d45c1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_json_number.go +++ /dev/null @@ -1,112 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "github.com/modern-go/reflect2" - "strconv" - "unsafe" -) - -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) -} - -func CastJsonNumber(val interface{}) (string, bool) { - switch typedVal := val.(type) { - case json.Number: - return string(typedVal), true - case Number: - return string(typedVal), true - } - return "", false -} - -var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() -var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() - -func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ.AssignableTo(jsonNumberType) { - return &jsonNumberCodec{} - } - if typ.AssignableTo(jsoniterNumberType) { - return &jsoniterNumberCodec{} - } - return nil -} - -func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ.AssignableTo(jsonNumberType) { - return &jsonNumberCodec{} - } - if typ.AssignableTo(jsoniterNumberType) { - return &jsoniterNumberCodec{} - } - return nil -} - -type jsonNumberCodec struct { -} - -func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case StringValue: - *((*json.Number)(ptr)) = json.Number(iter.ReadString()) - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - *((*json.Number)(ptr)) = "" - default: - *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) - } -} - -func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - number := *((*json.Number)(ptr)) - if len(number) == 0 { - stream.writeByte('0') - } else { - stream.WriteRaw(string(number)) - } -} - -func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*json.Number)(ptr))) == 0 -} - -type jsoniterNumberCodec struct { -} - -func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case StringValue: - *((*Number)(ptr)) = Number(iter.ReadString()) - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - *((*Number)(ptr)) = "" - default: - *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) - } -} - -func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - number := *((*Number)(ptr)) - if len(number) == 0 { - stream.writeByte('0') - } else { - stream.WriteRaw(string(number)) - } -} - -func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*Number)(ptr))) == 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_json_raw_message.go deleted file mode 100644 index f261993..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_json_raw_message.go +++ /dev/null @@ -1,60 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "github.com/modern-go/reflect2" - "unsafe" -) - -var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() -var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() - -func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ == jsonRawMessageType { - return &jsonRawMessageCodec{} - } - if typ == jsoniterRawMessageType { - return &jsoniterRawMessageCodec{} - } - return nil -} - -func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ == jsonRawMessageType { - return &jsonRawMessageCodec{} - } - if typ == jsoniterRawMessageType { - return &jsoniterRawMessageCodec{} - } - return nil -} - -type jsonRawMessageCodec struct { -} - -func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*json.RawMessage)(ptr)) = json.RawMessage(iter.SkipAndReturnBytes()) -} - -func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) -} - -func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*json.RawMessage)(ptr))) == 0 -} - -type jsoniterRawMessageCodec struct { -} - -func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*RawMessage)(ptr)) = RawMessage(iter.SkipAndReturnBytes()) -} - -func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*RawMessage)(ptr)))) -} - -func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*RawMessage)(ptr))) == 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_map.go deleted file mode 100644 index 7f66a88..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_map.go +++ /dev/null @@ -1,326 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "reflect" - "sort" - "unsafe" -) - -func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { - mapType := typ.(*reflect2.UnsafeMapType) - keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()) - elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem()) - return &mapDecoder{ - mapType: mapType, - keyType: mapType.Key(), - elemType: mapType.Elem(), - keyDecoder: keyDecoder, - elemDecoder: elemDecoder, - } -} - -func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder { - mapType := typ.(*reflect2.UnsafeMapType) - if ctx.sortMapKeys { - return &sortKeysMapEncoder{ - mapType: mapType, - keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), - elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), - } - } - return &mapEncoder{ - mapType: mapType, - keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), - elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), - } -} - -func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := ctx.decoderExtension.CreateMapKeyDecoder(typ) - if decoder != nil { - return decoder - } - for _, extension := range ctx.extraExtensions { - decoder := extension.CreateMapKeyDecoder(typ) - if decoder != nil { - return decoder - } - } - switch typ.Kind() { - case reflect.String: - return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) - case reflect.Bool, - reflect.Uint8, reflect.Int8, - reflect.Uint16, reflect.Int16, - reflect.Uint32, reflect.Int32, - reflect.Uint64, reflect.Int64, - reflect.Uint, reflect.Int, - reflect.Float32, reflect.Float64, - reflect.Uintptr: - typ = reflect2.DefaultTypeOfKind(typ.Kind()) - return &numericMapKeyDecoder{decoderOfType(ctx, typ)} - default: - ptrType := reflect2.PtrTo(typ) - if ptrType.Implements(textMarshalerType) { - return &referenceDecoder{ - &textUnmarshalerDecoder{ - valType: ptrType, - }, - } - } - if typ.Implements(textMarshalerType) { - return &textUnmarshalerDecoder{ - valType: typ, - } - } - return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)} - } -} - -func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := ctx.encoderExtension.CreateMapKeyEncoder(typ) - if encoder != nil { - return encoder - } - for _, extension := range ctx.extraExtensions { - encoder := extension.CreateMapKeyEncoder(typ) - if encoder != nil { - return encoder - } - } - switch typ.Kind() { - case reflect.String: - return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) - case reflect.Bool, - reflect.Uint8, reflect.Int8, - reflect.Uint16, reflect.Int16, - reflect.Uint32, reflect.Int32, - reflect.Uint64, reflect.Int64, - reflect.Uint, reflect.Int, - reflect.Float32, reflect.Float64, - reflect.Uintptr: - typ = reflect2.DefaultTypeOfKind(typ.Kind()) - return &numericMapKeyEncoder{encoderOfType(ctx, typ)} - default: - if typ == textMarshalerType { - return &directTextMarshalerEncoder{ - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - } - } - if typ.Implements(textMarshalerType) { - return &textMarshalerEncoder{ - valType: typ, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - } - } - if typ.Kind() == reflect.Interface { - return &dynamicMapKeyEncoder{ctx, typ} - } - return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)} - } -} - -type mapDecoder struct { - mapType *reflect2.UnsafeMapType - keyType reflect2.Type - elemType reflect2.Type - keyDecoder ValDecoder - elemDecoder ValDecoder -} - -func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - mapType := decoder.mapType - c := iter.nextToken() - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - *(*unsafe.Pointer)(ptr) = nil - mapType.UnsafeSet(ptr, mapType.UnsafeNew()) - return - } - if mapType.UnsafeIsNil(ptr) { - mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0)) - } - if c != '{' { - iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) - return - } - c = iter.nextToken() - if c == '}' { - return - } - if c != '"' { - iter.ReportError("ReadMapCB", `expect " after }, but found `+string([]byte{c})) - return - } - iter.unreadByte() - key := decoder.keyType.UnsafeNew() - decoder.keyDecoder.Decode(key, iter) - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - return - } - elem := decoder.elemType.UnsafeNew() - decoder.elemDecoder.Decode(elem, iter) - decoder.mapType.UnsafeSetIndex(ptr, key, elem) - for c = iter.nextToken(); c == ','; c = iter.nextToken() { - key := decoder.keyType.UnsafeNew() - decoder.keyDecoder.Decode(key, iter) - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - return - } - elem := decoder.elemType.UnsafeNew() - decoder.elemDecoder.Decode(elem, iter) - decoder.mapType.UnsafeSetIndex(ptr, key, elem) - } - if c != '}' { - iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c})) - } -} - -type numericMapKeyDecoder struct { - decoder ValDecoder -} - -func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - if c != '"' { - iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) - return - } - decoder.decoder.Decode(ptr, iter) - c = iter.nextToken() - if c != '"' { - iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) - return - } -} - -type numericMapKeyEncoder struct { - encoder ValEncoder -} - -func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.writeByte('"') - encoder.encoder.Encode(ptr, stream) - stream.writeByte('"') -} - -func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type dynamicMapKeyEncoder struct { - ctx *ctx - valType reflect2.Type -} - -func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream) -} - -func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { - obj := encoder.valType.UnsafeIndirect(ptr) - return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj)) -} - -type mapEncoder struct { - mapType *reflect2.UnsafeMapType - keyEncoder ValEncoder - elemEncoder ValEncoder -} - -func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteObjectStart() - iter := encoder.mapType.UnsafeIterate(ptr) - for i := 0; iter.HasNext(); i++ { - if i != 0 { - stream.WriteMore() - } - key, elem := iter.UnsafeNext() - encoder.keyEncoder.Encode(key, stream) - if stream.indention > 0 { - stream.writeTwoBytes(byte(':'), byte(' ')) - } else { - stream.writeByte(':') - } - encoder.elemEncoder.Encode(elem, stream) - } - stream.WriteObjectEnd() -} - -func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { - iter := encoder.mapType.UnsafeIterate(ptr) - return !iter.HasNext() -} - -type sortKeysMapEncoder struct { - mapType *reflect2.UnsafeMapType - keyEncoder ValEncoder - elemEncoder ValEncoder -} - -func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *(*unsafe.Pointer)(ptr) == nil { - stream.WriteNil() - return - } - stream.WriteObjectStart() - mapIter := encoder.mapType.UnsafeIterate(ptr) - subStream := stream.cfg.BorrowStream(nil) - subIter := stream.cfg.BorrowIterator(nil) - keyValues := encodedKeyValues{} - for mapIter.HasNext() { - subStream.buf = make([]byte, 0, 64) - key, elem := mapIter.UnsafeNext() - encoder.keyEncoder.Encode(key, subStream) - if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil { - stream.Error = subStream.Error - } - encodedKey := subStream.Buffer() - subIter.ResetBytes(encodedKey) - decodedKey := subIter.ReadString() - if stream.indention > 0 { - subStream.writeTwoBytes(byte(':'), byte(' ')) - } else { - subStream.writeByte(':') - } - encoder.elemEncoder.Encode(elem, subStream) - keyValues = append(keyValues, encodedKV{ - key: decodedKey, - keyValue: subStream.Buffer(), - }) - } - sort.Sort(keyValues) - for i, keyValue := range keyValues { - if i != 0 { - stream.WriteMore() - } - stream.Write(keyValue.keyValue) - } - stream.WriteObjectEnd() - stream.cfg.ReturnStream(subStream) - stream.cfg.ReturnIterator(subIter) -} - -func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { - iter := encoder.mapType.UnsafeIterate(ptr) - return !iter.HasNext() -} - -type encodedKeyValues []encodedKV - -type encodedKV struct { - key string - keyValue []byte -} - -func (sv encodedKeyValues) Len() int { return len(sv) } -func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key } diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_marshaler.go deleted file mode 100644 index 58ac959..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_marshaler.go +++ /dev/null @@ -1,218 +0,0 @@ -package jsoniter - -import ( - "encoding" - "encoding/json" - "github.com/modern-go/reflect2" - "unsafe" -) - -var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() -var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() -var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() -var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() - -func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { - ptrType := reflect2.PtrTo(typ) - if ptrType.Implements(unmarshalerType) { - return &referenceDecoder{ - &unmarshalerDecoder{ptrType}, - } - } - if ptrType.Implements(textUnmarshalerType) { - return &referenceDecoder{ - &textUnmarshalerDecoder{ptrType}, - } - } - return nil -} - -func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ == marshalerType { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &directMarshalerEncoder{ - checkIsEmpty: checkIsEmpty, - } - return encoder - } - if typ.Implements(marshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &marshalerEncoder{ - valType: typ, - checkIsEmpty: checkIsEmpty, - } - return encoder - } - ptrType := reflect2.PtrTo(typ) - if ctx.prefix != "" && ptrType.Implements(marshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, ptrType) - var encoder ValEncoder = &marshalerEncoder{ - valType: ptrType, - checkIsEmpty: checkIsEmpty, - } - return &referenceEncoder{encoder} - } - if typ == textMarshalerType { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &directTextMarshalerEncoder{ - checkIsEmpty: checkIsEmpty, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - } - return encoder - } - if typ.Implements(textMarshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &textMarshalerEncoder{ - valType: typ, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - checkIsEmpty: checkIsEmpty, - } - return encoder - } - // if prefix is empty, the type is the root type - if ctx.prefix != "" && ptrType.Implements(textMarshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, ptrType) - var encoder ValEncoder = &textMarshalerEncoder{ - valType: ptrType, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - checkIsEmpty: checkIsEmpty, - } - return &referenceEncoder{encoder} - } - return nil -} - -type marshalerEncoder struct { - checkIsEmpty checkIsEmpty - valType reflect2.Type -} - -func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - if encoder.valType.IsNullable() && reflect2.IsNil(obj) { - stream.WriteNil() - return - } - marshaler := obj.(json.Marshaler) - bytes, err := marshaler.MarshalJSON() - if err != nil { - stream.Error = err - } else { - stream.Write(bytes) - } -} - -func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type directMarshalerEncoder struct { - checkIsEmpty checkIsEmpty -} - -func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - marshaler := *(*json.Marshaler)(ptr) - if marshaler == nil { - stream.WriteNil() - return - } - bytes, err := marshaler.MarshalJSON() - if err != nil { - stream.Error = err - } else { - stream.Write(bytes) - } -} - -func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type textMarshalerEncoder struct { - valType reflect2.Type - stringEncoder ValEncoder - checkIsEmpty checkIsEmpty -} - -func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - if encoder.valType.IsNullable() && reflect2.IsNil(obj) { - stream.WriteNil() - return - } - marshaler := (obj).(encoding.TextMarshaler) - bytes, err := marshaler.MarshalText() - if err != nil { - stream.Error = err - } else { - str := string(bytes) - encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) - } -} - -func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type directTextMarshalerEncoder struct { - stringEncoder ValEncoder - checkIsEmpty checkIsEmpty -} - -func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - marshaler := *(*encoding.TextMarshaler)(ptr) - if marshaler == nil { - stream.WriteNil() - return - } - bytes, err := marshaler.MarshalText() - if err != nil { - stream.Error = err - } else { - str := string(bytes) - encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) - } -} - -func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type unmarshalerDecoder struct { - valType reflect2.Type -} - -func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - valType := decoder.valType - obj := valType.UnsafeIndirect(ptr) - unmarshaler := obj.(json.Unmarshaler) - iter.nextToken() - iter.unreadByte() // skip spaces - bytes := iter.SkipAndReturnBytes() - err := unmarshaler.UnmarshalJSON(bytes) - if err != nil { - iter.ReportError("unmarshalerDecoder", err.Error()) - } -} - -type textUnmarshalerDecoder struct { - valType reflect2.Type -} - -func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - valType := decoder.valType - obj := valType.UnsafeIndirect(ptr) - if reflect2.IsNil(obj) { - ptrType := valType.(*reflect2.UnsafePtrType) - elemType := ptrType.Elem() - elem := elemType.UnsafeNew() - ptrType.UnsafeSet(ptr, unsafe.Pointer(&elem)) - obj = valType.UnsafeIndirect(ptr) - } - unmarshaler := (obj).(encoding.TextUnmarshaler) - str := iter.ReadString() - err := unmarshaler.UnmarshalText([]byte(str)) - if err != nil { - iter.ReportError("textUnmarshalerDecoder", err.Error()) - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_native.go deleted file mode 100644 index 9042eb0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_native.go +++ /dev/null @@ -1,451 +0,0 @@ -package jsoniter - -import ( - "encoding/base64" - "reflect" - "strconv" - "unsafe" - - "github.com/modern-go/reflect2" -) - -const ptrSize = 32 << uintptr(^uintptr(0)>>63) - -func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { - sliceDecoder := decoderOfSlice(ctx, typ) - return &base64Codec{sliceDecoder: sliceDecoder} - } - typeName := typ.String() - kind := typ.Kind() - switch kind { - case reflect.String: - if typeName != "string" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) - } - return &stringCodec{} - case reflect.Int: - if typeName != "int" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &int32Codec{} - } - return &int64Codec{} - case reflect.Int8: - if typeName != "int8" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) - } - return &int8Codec{} - case reflect.Int16: - if typeName != "int16" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) - } - return &int16Codec{} - case reflect.Int32: - if typeName != "int32" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) - } - return &int32Codec{} - case reflect.Int64: - if typeName != "int64" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) - } - return &int64Codec{} - case reflect.Uint: - if typeName != "uint" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint8: - if typeName != "uint8" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) - } - return &uint8Codec{} - case reflect.Uint16: - if typeName != "uint16" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) - } - return &uint16Codec{} - case reflect.Uint32: - if typeName != "uint32" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) - } - return &uint32Codec{} - case reflect.Uintptr: - if typeName != "uintptr" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) - } - if ptrSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint64: - if typeName != "uint64" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) - } - return &uint64Codec{} - case reflect.Float32: - if typeName != "float32" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) - } - return &float32Codec{} - case reflect.Float64: - if typeName != "float64" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) - } - return &float64Codec{} - case reflect.Bool: - if typeName != "bool" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) - } - return &boolCodec{} - } - return nil -} - -func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { - sliceDecoder := decoderOfSlice(ctx, typ) - return &base64Codec{sliceDecoder: sliceDecoder} - } - typeName := typ.String() - switch typ.Kind() { - case reflect.String: - if typeName != "string" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) - } - return &stringCodec{} - case reflect.Int: - if typeName != "int" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &int32Codec{} - } - return &int64Codec{} - case reflect.Int8: - if typeName != "int8" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) - } - return &int8Codec{} - case reflect.Int16: - if typeName != "int16" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) - } - return &int16Codec{} - case reflect.Int32: - if typeName != "int32" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) - } - return &int32Codec{} - case reflect.Int64: - if typeName != "int64" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) - } - return &int64Codec{} - case reflect.Uint: - if typeName != "uint" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint8: - if typeName != "uint8" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) - } - return &uint8Codec{} - case reflect.Uint16: - if typeName != "uint16" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) - } - return &uint16Codec{} - case reflect.Uint32: - if typeName != "uint32" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) - } - return &uint32Codec{} - case reflect.Uintptr: - if typeName != "uintptr" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) - } - if ptrSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint64: - if typeName != "uint64" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) - } - return &uint64Codec{} - case reflect.Float32: - if typeName != "float32" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) - } - return &float32Codec{} - case reflect.Float64: - if typeName != "float64" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) - } - return &float64Codec{} - case reflect.Bool: - if typeName != "bool" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) - } - return &boolCodec{} - } - return nil -} - -type stringCodec struct { -} - -func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*string)(ptr)) = iter.ReadString() -} - -func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - str := *((*string)(ptr)) - stream.WriteString(str) -} - -func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*string)(ptr)) == "" -} - -type int8Codec struct { -} - -func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int8)(ptr)) = iter.ReadInt8() - } -} - -func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt8(*((*int8)(ptr))) -} - -func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int8)(ptr)) == 0 -} - -type int16Codec struct { -} - -func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int16)(ptr)) = iter.ReadInt16() - } -} - -func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt16(*((*int16)(ptr))) -} - -func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int16)(ptr)) == 0 -} - -type int32Codec struct { -} - -func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int32)(ptr)) = iter.ReadInt32() - } -} - -func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt32(*((*int32)(ptr))) -} - -func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int32)(ptr)) == 0 -} - -type int64Codec struct { -} - -func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int64)(ptr)) = iter.ReadInt64() - } -} - -func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt64(*((*int64)(ptr))) -} - -func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int64)(ptr)) == 0 -} - -type uint8Codec struct { -} - -func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint8)(ptr)) = iter.ReadUint8() - } -} - -func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint8(*((*uint8)(ptr))) -} - -func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint8)(ptr)) == 0 -} - -type uint16Codec struct { -} - -func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint16)(ptr)) = iter.ReadUint16() - } -} - -func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint16(*((*uint16)(ptr))) -} - -func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint16)(ptr)) == 0 -} - -type uint32Codec struct { -} - -func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint32)(ptr)) = iter.ReadUint32() - } -} - -func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint32(*((*uint32)(ptr))) -} - -func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint32)(ptr)) == 0 -} - -type uint64Codec struct { -} - -func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint64)(ptr)) = iter.ReadUint64() - } -} - -func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint64(*((*uint64)(ptr))) -} - -func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint64)(ptr)) == 0 -} - -type float32Codec struct { -} - -func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*float32)(ptr)) = iter.ReadFloat32() - } -} - -func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat32(*((*float32)(ptr))) -} - -func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float32)(ptr)) == 0 -} - -type float64Codec struct { -} - -func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*float64)(ptr)) = iter.ReadFloat64() - } -} - -func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat64(*((*float64)(ptr))) -} - -func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float64)(ptr)) == 0 -} - -type boolCodec struct { -} - -func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*bool)(ptr)) = iter.ReadBool() - } -} - -func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteBool(*((*bool)(ptr))) -} - -func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { - return !(*((*bool)(ptr))) -} - -type base64Codec struct { - sliceType *reflect2.UnsafeSliceType - sliceDecoder ValDecoder -} - -func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - codec.sliceType.UnsafeSetNil(ptr) - return - } - switch iter.WhatIsNext() { - case StringValue: - src := iter.ReadString() - dst, err := base64.StdEncoding.DecodeString(src) - if err != nil { - iter.ReportError("decode base64", err.Error()) - } else { - codec.sliceType.UnsafeSet(ptr, unsafe.Pointer(&dst)) - } - case ArrayValue: - codec.sliceDecoder.Decode(ptr, iter) - default: - iter.ReportError("base64Codec", "invalid input") - } -} - -func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - src := *((*[]byte)(ptr)) - if len(src) == 0 { - stream.WriteNil() - return - } - encoding := base64.StdEncoding - stream.writeByte('"') - size := encoding.EncodedLen(len(src)) - buf := make([]byte, size) - encoding.Encode(buf, src) - stream.buf = append(stream.buf, buf...) - stream.writeByte('"') -} - -func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*[]byte)(ptr))) == 0 -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_optional.go deleted file mode 100644 index 43ec71d..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_optional.go +++ /dev/null @@ -1,133 +0,0 @@ -package jsoniter - -import ( - "github.com/modern-go/reflect2" - "reflect" - "unsafe" -) - -func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { - ptrType := typ.(*reflect2.UnsafePtrType) - elemType := ptrType.Elem() - decoder := decoderOfType(ctx, elemType) - if ctx.prefix == "" && elemType.Kind() == reflect.Ptr { - return &dereferenceDecoder{elemType, decoder} - } - return &OptionalDecoder{elemType, decoder} -} - -func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder { - ptrType := typ.(*reflect2.UnsafePtrType) - elemType := ptrType.Elem() - elemEncoder := encoderOfType(ctx, elemType) - encoder := &OptionalEncoder{elemEncoder} - return encoder -} - -type OptionalDecoder struct { - ValueType reflect2.Type - ValueDecoder ValDecoder -} - -func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - *((*unsafe.Pointer)(ptr)) = nil - } else { - if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value - newPtr := decoder.ValueType.UnsafeNew() - decoder.ValueDecoder.Decode(newPtr, iter) - *((*unsafe.Pointer)(ptr)) = newPtr - } else { - //reuse existing instance - decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) - } - } -} - -type dereferenceDecoder struct { - // only to deference a pointer - valueType reflect2.Type - valueDecoder ValDecoder -} - -func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value - newPtr := decoder.valueType.UnsafeNew() - decoder.valueDecoder.Decode(newPtr, iter) - *((*unsafe.Pointer)(ptr)) = newPtr - } else { - //reuse existing instance - decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) - } -} - -type OptionalEncoder struct { - ValueEncoder ValEncoder -} - -func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*unsafe.Pointer)(ptr)) == nil { - stream.WriteNil() - } else { - encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) - } -} - -func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*unsafe.Pointer)(ptr)) == nil -} - -type dereferenceEncoder struct { - ValueEncoder ValEncoder -} - -func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*unsafe.Pointer)(ptr)) == nil { - stream.WriteNil() - } else { - encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) - } -} - -func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - dePtr := *((*unsafe.Pointer)(ptr)) - if dePtr == nil { - return true - } - return encoder.ValueEncoder.IsEmpty(dePtr) -} - -func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { - deReferenced := *((*unsafe.Pointer)(ptr)) - if deReferenced == nil { - return true - } - isEmbeddedPtrNil, converted := encoder.ValueEncoder.(IsEmbeddedPtrNil) - if !converted { - return false - } - fieldPtr := unsafe.Pointer(deReferenced) - return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) -} - -type referenceEncoder struct { - encoder ValEncoder -} - -func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) -} - -func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) -} - -type referenceDecoder struct { - decoder ValDecoder -} - -func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.decoder.Decode(unsafe.Pointer(&ptr), iter) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_slice.go deleted file mode 100644 index 9441d79..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_slice.go +++ /dev/null @@ -1,99 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "unsafe" -) - -func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { - sliceType := typ.(*reflect2.UnsafeSliceType) - decoder := decoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) - return &sliceDecoder{sliceType, decoder} -} - -func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder { - sliceType := typ.(*reflect2.UnsafeSliceType) - encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) - return &sliceEncoder{sliceType, encoder} -} - -type sliceEncoder struct { - sliceType *reflect2.UnsafeSliceType - elemEncoder ValEncoder -} - -func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if encoder.sliceType.UnsafeIsNil(ptr) { - stream.WriteNil() - return - } - length := encoder.sliceType.UnsafeLengthOf(ptr) - if length == 0 { - stream.WriteEmptyArray() - return - } - stream.WriteArrayStart() - encoder.elemEncoder.Encode(encoder.sliceType.UnsafeGetIndex(ptr, 0), stream) - for i := 1; i < length; i++ { - stream.WriteMore() - elemPtr := encoder.sliceType.UnsafeGetIndex(ptr, i) - encoder.elemEncoder.Encode(elemPtr, stream) - } - stream.WriteArrayEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) - } -} - -func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.sliceType.UnsafeLengthOf(ptr) == 0 -} - -type sliceDecoder struct { - sliceType *reflect2.UnsafeSliceType - elemDecoder ValDecoder -} - -func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.doDecode(ptr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) - } -} - -func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - sliceType := decoder.sliceType - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - sliceType.UnsafeSetNil(ptr) - return - } - if c != '[' { - iter.ReportError("decode slice", "expect [ or n, but found "+string([]byte{c})) - return - } - c = iter.nextToken() - if c == ']' { - sliceType.UnsafeSet(ptr, sliceType.UnsafeMakeSlice(0, 0)) - return - } - iter.unreadByte() - sliceType.UnsafeGrow(ptr, 1) - elemPtr := sliceType.UnsafeGetIndex(ptr, 0) - decoder.elemDecoder.Decode(elemPtr, iter) - length := 1 - for c = iter.nextToken(); c == ','; c = iter.nextToken() { - idx := length - length += 1 - sliceType.UnsafeGrow(ptr, length) - elemPtr = sliceType.UnsafeGetIndex(ptr, idx) - decoder.elemDecoder.Decode(elemPtr, iter) - } - if c != ']' { - iter.ReportError("decode slice", "expect ], but found "+string([]byte{c})) - return - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_struct_decoder.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_struct_decoder.go deleted file mode 100644 index 355d2d1..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_struct_decoder.go +++ /dev/null @@ -1,1048 +0,0 @@ -package jsoniter - -import ( - "fmt" - "io" - "strings" - "unsafe" - - "github.com/modern-go/reflect2" -) - -func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder { - bindings := map[string]*Binding{} - structDescriptor := describeStruct(ctx, typ) - for _, binding := range structDescriptor.Fields { - for _, fromName := range binding.FromNames { - old := bindings[fromName] - if old == nil { - bindings[fromName] = binding - continue - } - ignoreOld, ignoreNew := resolveConflictBinding(ctx.frozenConfig, old, binding) - if ignoreOld { - delete(bindings, fromName) - } - if !ignoreNew { - bindings[fromName] = binding - } - } - } - fields := map[string]*structFieldDecoder{} - for k, binding := range bindings { - fields[k] = binding.Decoder.(*structFieldDecoder) - } - - if !ctx.caseSensitive() { - for k, binding := range bindings { - if _, found := fields[strings.ToLower(k)]; !found { - fields[strings.ToLower(k)] = binding.Decoder.(*structFieldDecoder) - } - } - } - - return createStructDecoder(ctx, typ, fields) -} - -func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structFieldDecoder) ValDecoder { - if ctx.disallowUnknownFields { - return &generalStructDecoder{typ: typ, fields: fields, disallowUnknownFields: true} - } - knownHash := map[int64]struct{}{ - 0: {}, - } - - switch len(fields) { - case 0: - return &skipObjectDecoder{typ} - case 1: - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder} - } - case 2: - var fieldHash1 int64 - var fieldHash2 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldHash1 == 0 { - fieldHash1 = fieldHash - fieldDecoder1 = fieldDecoder - } else { - fieldHash2 = fieldHash - fieldDecoder2 = fieldDecoder - } - } - return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2} - case 3: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } - } - return &threeFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3} - case 4: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } - } - return &fourFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4} - case 5: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } - } - return &fiveFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5} - case 6: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } - } - return &sixFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6} - case 7: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } - } - return &sevenFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7} - case 8: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldName8 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - var fieldDecoder8 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else if fieldName7 == 0 { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } else { - fieldName8 = fieldHash - fieldDecoder8 = fieldDecoder - } - } - return &eightFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8} - case 9: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldName8 int64 - var fieldName9 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - var fieldDecoder8 *structFieldDecoder - var fieldDecoder9 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else if fieldName7 == 0 { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } else if fieldName8 == 0 { - fieldName8 = fieldHash - fieldDecoder8 = fieldDecoder - } else { - fieldName9 = fieldHash - fieldDecoder9 = fieldDecoder - } - } - return &nineFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8, - fieldName9, fieldDecoder9} - case 10: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldName8 int64 - var fieldName9 int64 - var fieldName10 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - var fieldDecoder8 *structFieldDecoder - var fieldDecoder9 *structFieldDecoder - var fieldDecoder10 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else if fieldName7 == 0 { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } else if fieldName8 == 0 { - fieldName8 = fieldHash - fieldDecoder8 = fieldDecoder - } else if fieldName9 == 0 { - fieldName9 = fieldHash - fieldDecoder9 = fieldDecoder - } else { - fieldName10 = fieldHash - fieldDecoder10 = fieldDecoder - } - } - return &tenFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8, - fieldName9, fieldDecoder9, - fieldName10, fieldDecoder10} - } - return &generalStructDecoder{typ, fields, false} -} - -type generalStructDecoder struct { - typ reflect2.Type - fields map[string]*structFieldDecoder - disallowUnknownFields bool -} - -func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - var c byte - for c = ','; c == ','; c = iter.nextToken() { - decoder.decodeOneField(ptr, iter) - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - if c != '}' { - iter.ReportError("struct Decode", `expect }, but found `+string([]byte{c})) - } -} - -func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer, iter *Iterator) { - var field string - var fieldDecoder *structFieldDecoder - if iter.cfg.objectFieldMustBeSimpleString { - fieldBytes := iter.ReadStringAsSlice() - field = *(*string)(unsafe.Pointer(&fieldBytes)) - fieldDecoder = decoder.fields[field] - if fieldDecoder == nil && !iter.cfg.caseSensitive { - fieldDecoder = decoder.fields[strings.ToLower(field)] - } - } else { - field = iter.ReadString() - fieldDecoder = decoder.fields[field] - if fieldDecoder == nil && !iter.cfg.caseSensitive { - fieldDecoder = decoder.fields[strings.ToLower(field)] - } - } - if fieldDecoder == nil { - msg := "found unknown field: " + field - if decoder.disallowUnknownFields { - iter.ReportError("ReadObject", msg) - } - c := iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - iter.Skip() - return - } - c := iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - fieldDecoder.Decode(ptr, iter) -} - -type skipObjectDecoder struct { - typ reflect2.Type -} - -func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - valueType := iter.WhatIsNext() - if valueType != ObjectValue && valueType != NilValue { - iter.ReportError("skipObjectDecoder", "expect object or null") - return - } - iter.Skip() -} - -type oneFieldStructDecoder struct { - typ reflect2.Type - fieldHash int64 - fieldDecoder *structFieldDecoder -} - -func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - if iter.readFieldHash() == decoder.fieldHash { - decoder.fieldDecoder.Decode(ptr, iter) - } else { - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type twoFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder -} - -func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type threeFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder -} - -func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type fourFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder -} - -func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type fiveFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder -} - -func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type sixFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder -} - -func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type sevenFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder -} - -func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type eightFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder - fieldHash8 int64 - fieldDecoder8 *structFieldDecoder -} - -func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - case decoder.fieldHash8: - decoder.fieldDecoder8.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type nineFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder - fieldHash8 int64 - fieldDecoder8 *structFieldDecoder - fieldHash9 int64 - fieldDecoder9 *structFieldDecoder -} - -func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - case decoder.fieldHash8: - decoder.fieldDecoder8.Decode(ptr, iter) - case decoder.fieldHash9: - decoder.fieldDecoder9.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type tenFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder - fieldHash8 int64 - fieldDecoder8 *structFieldDecoder - fieldHash9 int64 - fieldDecoder9 *structFieldDecoder - fieldHash10 int64 - fieldDecoder10 *structFieldDecoder -} - -func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - case decoder.fieldHash8: - decoder.fieldDecoder8.Decode(ptr, iter) - case decoder.fieldHash9: - decoder.fieldDecoder9.Decode(ptr, iter) - case decoder.fieldHash10: - decoder.fieldDecoder10.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } -} - -type structFieldDecoder struct { - field reflect2.StructField - fieldDecoder ValDecoder -} - -func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - fieldPtr := decoder.field.UnsafeGet(ptr) - decoder.fieldDecoder.Decode(fieldPtr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%s: %s", decoder.field.Name(), iter.Error.Error()) - } -} - -type stringModeStringDecoder struct { - elemDecoder ValDecoder - cfg *frozenConfig -} - -func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.elemDecoder.Decode(ptr, iter) - str := *((*string)(ptr)) - tempIter := decoder.cfg.BorrowIterator([]byte(str)) - defer decoder.cfg.ReturnIterator(tempIter) - *((*string)(ptr)) = tempIter.ReadString() -} - -type stringModeNumberDecoder struct { - elemDecoder ValDecoder -} - -func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - if c != '"' { - iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) - return - } - decoder.elemDecoder.Decode(ptr, iter) - if iter.Error != nil { - return - } - c = iter.readByte() - if c != '"' { - iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) - return - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_struct_encoder.go deleted file mode 100644 index d0759cf..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/reflect_struct_encoder.go +++ /dev/null @@ -1,210 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "reflect" - "unsafe" -) - -func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { - type bindingTo struct { - binding *Binding - toName string - ignored bool - } - orderedBindings := []*bindingTo{} - structDescriptor := describeStruct(ctx, typ) - for _, binding := range structDescriptor.Fields { - for _, toName := range binding.ToNames { - new := &bindingTo{ - binding: binding, - toName: toName, - } - for _, old := range orderedBindings { - if old.toName != toName { - continue - } - old.ignored, new.ignored = resolveConflictBinding(ctx.frozenConfig, old.binding, new.binding) - } - orderedBindings = append(orderedBindings, new) - } - } - if len(orderedBindings) == 0 { - return &emptyStructEncoder{} - } - finalOrderedFields := []structFieldTo{} - for _, bindingTo := range orderedBindings { - if !bindingTo.ignored { - finalOrderedFields = append(finalOrderedFields, structFieldTo{ - encoder: bindingTo.binding.Encoder.(*structFieldEncoder), - toName: bindingTo.toName, - }) - } - } - return &structEncoder{typ, finalOrderedFields} -} - -func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty { - encoder := createEncoderOfNative(ctx, typ) - if encoder != nil { - return encoder - } - kind := typ.Kind() - switch kind { - case reflect.Interface: - return &dynamicEncoder{typ} - case reflect.Struct: - return &structEncoder{typ: typ} - case reflect.Array: - return &arrayEncoder{} - case reflect.Slice: - return &sliceEncoder{} - case reflect.Map: - return encoderOfMap(ctx, typ) - case reflect.Ptr: - return &OptionalEncoder{} - default: - return &lazyErrorEncoder{err: fmt.Errorf("unsupported type: %v", typ)} - } -} - -func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { - newTagged := new.Field.Tag().Get(cfg.getTagKey()) != "" - oldTagged := old.Field.Tag().Get(cfg.getTagKey()) != "" - if newTagged { - if oldTagged { - if len(old.levels) > len(new.levels) { - return true, false - } else if len(new.levels) > len(old.levels) { - return false, true - } else { - return true, true - } - } else { - return true, false - } - } else { - if oldTagged { - return true, false - } - if len(old.levels) > len(new.levels) { - return true, false - } else if len(new.levels) > len(old.levels) { - return false, true - } else { - return true, true - } - } -} - -type structFieldEncoder struct { - field reflect2.StructField - fieldEncoder ValEncoder - omitempty bool -} - -func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - fieldPtr := encoder.field.UnsafeGet(ptr) - encoder.fieldEncoder.Encode(fieldPtr, stream) - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%s: %s", encoder.field.Name(), stream.Error.Error()) - } -} - -func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool { - fieldPtr := encoder.field.UnsafeGet(ptr) - return encoder.fieldEncoder.IsEmpty(fieldPtr) -} - -func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { - isEmbeddedPtrNil, converted := encoder.fieldEncoder.(IsEmbeddedPtrNil) - if !converted { - return false - } - fieldPtr := encoder.field.UnsafeGet(ptr) - return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) -} - -type IsEmbeddedPtrNil interface { - IsEmbeddedPtrNil(ptr unsafe.Pointer) bool -} - -type structEncoder struct { - typ reflect2.Type - fields []structFieldTo -} - -type structFieldTo struct { - encoder *structFieldEncoder - toName string -} - -func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteObjectStart() - isNotFirst := false - for _, field := range encoder.fields { - if field.encoder.omitempty && field.encoder.IsEmpty(ptr) { - continue - } - if field.encoder.IsEmbeddedPtrNil(ptr) { - continue - } - if isNotFirst { - stream.WriteMore() - } - stream.WriteObjectField(field.toName) - field.encoder.Encode(ptr, stream) - isNotFirst = true - } - stream.WriteObjectEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v.%s", encoder.typ, stream.Error.Error()) - } -} - -func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type emptyStructEncoder struct { -} - -func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteEmptyObject() -} - -func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type stringModeNumberEncoder struct { - elemEncoder ValEncoder -} - -func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.writeByte('"') - encoder.elemEncoder.Encode(ptr, stream) - stream.writeByte('"') -} - -func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.elemEncoder.IsEmpty(ptr) -} - -type stringModeStringEncoder struct { - elemEncoder ValEncoder - cfg *frozenConfig -} - -func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - tempStream := encoder.cfg.BorrowStream(nil) - defer encoder.cfg.ReturnStream(tempStream) - encoder.elemEncoder.Encode(ptr, tempStream) - stream.WriteString(string(tempStream.Buffer())) -} - -func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.elemEncoder.IsEmpty(ptr) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream.go deleted file mode 100644 index 17662fd..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream.go +++ /dev/null @@ -1,211 +0,0 @@ -package jsoniter - -import ( - "io" -) - -// stream is a io.Writer like object, with JSON specific write functions. -// Error is not returned as return value, but stored as Error member on this stream instance. -type Stream struct { - cfg *frozenConfig - out io.Writer - buf []byte - Error error - indention int - Attachment interface{} // open for customized encoder -} - -// NewStream create new stream instance. -// cfg can be jsoniter.ConfigDefault. -// out can be nil if write to internal buffer. -// bufSize is the initial size for the internal buffer in bytes. -func NewStream(cfg API, out io.Writer, bufSize int) *Stream { - return &Stream{ - cfg: cfg.(*frozenConfig), - out: out, - buf: make([]byte, 0, bufSize), - Error: nil, - indention: 0, - } -} - -// Pool returns a pool can provide more stream with same configuration -func (stream *Stream) Pool() StreamPool { - return stream.cfg -} - -// Reset reuse this stream instance by assign a new writer -func (stream *Stream) Reset(out io.Writer) { - stream.out = out - stream.buf = stream.buf[:0] -} - -// Available returns how many bytes are unused in the buffer. -func (stream *Stream) Available() int { - return cap(stream.buf) - len(stream.buf) -} - -// Buffered returns the number of bytes that have been written into the current buffer. -func (stream *Stream) Buffered() int { - return len(stream.buf) -} - -// Buffer if writer is nil, use this method to take the result -func (stream *Stream) Buffer() []byte { - return stream.buf -} - -// SetBuffer allows to append to the internal buffer directly -func (stream *Stream) SetBuffer(buf []byte) { - stream.buf = buf -} - -// Write writes the contents of p into the buffer. -// It returns the number of bytes written. -// If nn < len(p), it also returns an error explaining -// why the write is short. -func (stream *Stream) Write(p []byte) (nn int, err error) { - stream.buf = append(stream.buf, p...) - if stream.out != nil { - nn, err = stream.out.Write(stream.buf) - stream.buf = stream.buf[nn:] - return - } - return len(p), nil -} - -// WriteByte writes a single byte. -func (stream *Stream) writeByte(c byte) { - stream.buf = append(stream.buf, c) -} - -func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { - stream.buf = append(stream.buf, c1, c2) -} - -func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { - stream.buf = append(stream.buf, c1, c2, c3) -} - -func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { - stream.buf = append(stream.buf, c1, c2, c3, c4) -} - -func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { - stream.buf = append(stream.buf, c1, c2, c3, c4, c5) -} - -// Flush writes any buffered data to the underlying io.Writer. -func (stream *Stream) Flush() error { - if stream.out == nil { - return nil - } - if stream.Error != nil { - return stream.Error - } - n, err := stream.out.Write(stream.buf) - if err != nil { - if stream.Error == nil { - stream.Error = err - } - return err - } - stream.buf = stream.buf[n:] - return nil -} - -// WriteRaw write string out without quotes, just like []byte -func (stream *Stream) WriteRaw(s string) { - stream.buf = append(stream.buf, s...) -} - -// WriteNil write null to stream -func (stream *Stream) WriteNil() { - stream.writeFourBytes('n', 'u', 'l', 'l') -} - -// WriteTrue write true to stream -func (stream *Stream) WriteTrue() { - stream.writeFourBytes('t', 'r', 'u', 'e') -} - -// WriteFalse write false to stream -func (stream *Stream) WriteFalse() { - stream.writeFiveBytes('f', 'a', 'l', 's', 'e') -} - -// WriteBool write true or false into stream -func (stream *Stream) WriteBool(val bool) { - if val { - stream.WriteTrue() - } else { - stream.WriteFalse() - } -} - -// WriteObjectStart write { with possible indention -func (stream *Stream) WriteObjectStart() { - stream.indention += stream.cfg.indentionStep - stream.writeByte('{') - stream.writeIndention(0) -} - -// WriteObjectField write "field": with possible indention -func (stream *Stream) WriteObjectField(field string) { - stream.WriteString(field) - if stream.indention > 0 { - stream.writeTwoBytes(':', ' ') - } else { - stream.writeByte(':') - } -} - -// WriteObjectEnd write } with possible indention -func (stream *Stream) WriteObjectEnd() { - stream.writeIndention(stream.cfg.indentionStep) - stream.indention -= stream.cfg.indentionStep - stream.writeByte('}') -} - -// WriteEmptyObject write {} -func (stream *Stream) WriteEmptyObject() { - stream.writeByte('{') - stream.writeByte('}') -} - -// WriteMore write , with possible indention -func (stream *Stream) WriteMore() { - stream.writeByte(',') - stream.writeIndention(0) - stream.Flush() -} - -// WriteArrayStart write [ with possible indention -func (stream *Stream) WriteArrayStart() { - stream.indention += stream.cfg.indentionStep - stream.writeByte('[') - stream.writeIndention(0) -} - -// WriteEmptyArray write [] -func (stream *Stream) WriteEmptyArray() { - stream.writeTwoBytes('[', ']') -} - -// WriteArrayEnd write ] with possible indention -func (stream *Stream) WriteArrayEnd() { - stream.writeIndention(stream.cfg.indentionStep) - stream.indention -= stream.cfg.indentionStep - stream.writeByte(']') -} - -func (stream *Stream) writeIndention(delta int) { - if stream.indention == 0 { - return - } - stream.writeByte('\n') - toWrite := stream.indention - delta - for i := 0; i < toWrite; i++ { - stream.buf = append(stream.buf, ' ') - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_float.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_float.go deleted file mode 100644 index f318d2c..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_float.go +++ /dev/null @@ -1,94 +0,0 @@ -package jsoniter - -import ( - "math" - "strconv" -) - -var pow10 []uint64 - -func init() { - pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000} -} - -// WriteFloat32 write float32 to stream -func (stream *Stream) WriteFloat32(val float32) { - abs := math.Abs(float64(val)) - fmt := byte('f') - // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs != 0 { - if float32(abs) < 1e-6 || float32(abs) >= 1e21 { - fmt = 'e' - } - } - stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32) -} - -// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster -func (stream *Stream) WriteFloat32Lossy(val float32) { - if val < 0 { - stream.writeByte('-') - val = -val - } - if val > 0x4ffffff { - stream.WriteFloat32(val) - return - } - precision := 6 - exp := uint64(1000000) // 6 - lval := uint64(float64(val)*float64(exp) + 0.5) - stream.WriteUint64(lval / exp) - fval := lval % exp - if fval == 0 { - return - } - stream.writeByte('.') - for p := precision - 1; p > 0 && fval < pow10[p]; p-- { - stream.writeByte('0') - } - stream.WriteUint64(fval) - for stream.buf[len(stream.buf)-1] == '0' { - stream.buf = stream.buf[:len(stream.buf)-1] - } -} - -// WriteFloat64 write float64 to stream -func (stream *Stream) WriteFloat64(val float64) { - abs := math.Abs(val) - fmt := byte('f') - // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs != 0 { - if abs < 1e-6 || abs >= 1e21 { - fmt = 'e' - } - } - stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64) -} - -// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster -func (stream *Stream) WriteFloat64Lossy(val float64) { - if val < 0 { - stream.writeByte('-') - val = -val - } - if val > 0x4ffffff { - stream.WriteFloat64(val) - return - } - precision := 6 - exp := uint64(1000000) // 6 - lval := uint64(val*float64(exp) + 0.5) - stream.WriteUint64(lval / exp) - fval := lval % exp - if fval == 0 { - return - } - stream.writeByte('.') - for p := precision - 1; p > 0 && fval < pow10[p]; p-- { - stream.writeByte('0') - } - stream.WriteUint64(fval) - for stream.buf[len(stream.buf)-1] == '0' { - stream.buf = stream.buf[:len(stream.buf)-1] - } -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_int.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_int.go deleted file mode 100644 index d1059ee..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_int.go +++ /dev/null @@ -1,190 +0,0 @@ -package jsoniter - -var digits []uint32 - -func init() { - digits = make([]uint32, 1000) - for i := uint32(0); i < 1000; i++ { - digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' - if i < 10 { - digits[i] += 2 << 24 - } else if i < 100 { - digits[i] += 1 << 24 - } - } -} - -func writeFirstBuf(space []byte, v uint32) []byte { - start := v >> 24 - if start == 0 { - space = append(space, byte(v>>16), byte(v>>8)) - } else if start == 1 { - space = append(space, byte(v>>8)) - } - space = append(space, byte(v)) - return space -} - -func writeBuf(buf []byte, v uint32) []byte { - return append(buf, byte(v>>16), byte(v>>8), byte(v)) -} - -// WriteUint8 write uint8 to stream -func (stream *Stream) WriteUint8(val uint8) { - stream.buf = writeFirstBuf(stream.buf, digits[val]) -} - -// WriteInt8 write int8 to stream -func (stream *Stream) WriteInt8(nval int8) { - var val uint8 - if nval < 0 { - val = uint8(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint8(nval) - } - stream.buf = writeFirstBuf(stream.buf, digits[val]) -} - -// WriteUint16 write uint16 to stream -func (stream *Stream) WriteUint16(val uint16) { - q1 := val / 1000 - if q1 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[val]) - return - } - r1 := val - q1*1000 - stream.buf = writeFirstBuf(stream.buf, digits[q1]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return -} - -// WriteInt16 write int16 to stream -func (stream *Stream) WriteInt16(nval int16) { - var val uint16 - if nval < 0 { - val = uint16(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint16(nval) - } - stream.WriteUint16(val) -} - -// WriteUint32 write uint32 to stream -func (stream *Stream) WriteUint32(val uint32) { - q1 := val / 1000 - if q1 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[val]) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q1]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q2]) - } else { - r3 := q2 - q3*1000 - stream.buf = append(stream.buf, byte(q3+'0')) - stream.buf = writeBuf(stream.buf, digits[r3]) - } - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) -} - -// WriteInt32 write int32 to stream -func (stream *Stream) WriteInt32(nval int32) { - var val uint32 - if nval < 0 { - val = uint32(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint32(nval) - } - stream.WriteUint32(val) -} - -// WriteUint64 write uint64 to stream -func (stream *Stream) WriteUint64(val uint64) { - q1 := val / 1000 - if q1 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[val]) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q1]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q2]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r3 := q2 - q3*1000 - q4 := q3 / 1000 - if q4 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q3]) - stream.buf = writeBuf(stream.buf, digits[r3]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r4 := q3 - q4*1000 - q5 := q4 / 1000 - if q5 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q4]) - stream.buf = writeBuf(stream.buf, digits[r4]) - stream.buf = writeBuf(stream.buf, digits[r3]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r5 := q4 - q5*1000 - q6 := q5 / 1000 - if q6 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q5]) - } else { - stream.buf = writeFirstBuf(stream.buf, digits[q6]) - r6 := q5 - q6*1000 - stream.buf = writeBuf(stream.buf, digits[r6]) - } - stream.buf = writeBuf(stream.buf, digits[r5]) - stream.buf = writeBuf(stream.buf, digits[r4]) - stream.buf = writeBuf(stream.buf, digits[r3]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) -} - -// WriteInt64 write int64 to stream -func (stream *Stream) WriteInt64(nval int64) { - var val uint64 - if nval < 0 { - val = uint64(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint64(nval) - } - stream.WriteUint64(val) -} - -// WriteInt write int to stream -func (stream *Stream) WriteInt(val int) { - stream.WriteInt64(int64(val)) -} - -// WriteUint write uint to stream -func (stream *Stream) WriteUint(val uint) { - stream.WriteUint64(uint64(val)) -} diff --git a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_str.go b/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_str.go deleted file mode 100644 index 54c2ba0..0000000 --- a/vendor/github.com/go-acme/lego/vendor/github.com/json-iterator/go/stream_str.go +++ /dev/null @@ -1,372 +0,0 @@ -package jsoniter - -import ( - "unicode/utf8" -) - -// htmlSafeSet holds the value true if the ASCII character with the given -// array position can be safely represented inside a JSON string, embedded -// inside of HTML