build: upgrade to go 1.17 and dependencies
This commit is contained in:
parent
de6f39bddc
commit
8b5888ee1b
@ -1,4 +1,4 @@
|
|||||||
FROM --platform=$BUILDPLATFORM golang:alpine AS builder
|
FROM --platform=$BUILDPLATFORM golang:1.17-alpine AS builder
|
||||||
|
|
||||||
ARG TARGETPLATFORM
|
ARG TARGETPLATFORM
|
||||||
ARG BUILDPLATFORM
|
ARG BUILDPLATFORM
|
||||||
|
23
go.mod
23
go.mod
@ -1,13 +1,20 @@
|
|||||||
module github.com/cyrilix/robocar-led
|
module github.com/cyrilix/robocar-led
|
||||||
|
|
||||||
go 1.15
|
go 1.17
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/cyrilix/robocar-base v0.1.1
|
github.com/cyrilix/robocar-base v0.1.4
|
||||||
github.com/cyrilix/robocar-protobuf/go v1.0.0
|
github.com/cyrilix/robocar-protobuf/go v1.0.3
|
||||||
github.com/eclipse/paho.mqtt.golang v1.2.0
|
github.com/eclipse/paho.mqtt.golang v1.3.5
|
||||||
github.com/golang/protobuf v1.4.2
|
github.com/golang/protobuf v1.5.2
|
||||||
github.com/sirupsen/logrus v1.6.0
|
github.com/sirupsen/logrus v1.8.1
|
||||||
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f // indirect
|
periph.io/x/periph v3.6.8+incompatible
|
||||||
periph.io/x/periph v3.6.4+incompatible
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/gorilla/websocket v1.4.2 // indirect
|
||||||
|
github.com/stretchr/testify v1.6.1 // indirect
|
||||||
|
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0 // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd // indirect
|
||||||
|
google.golang.org/protobuf v1.26.0 // indirect
|
||||||
)
|
)
|
||||||
|
74
go.sum
74
go.sum
@ -4,20 +4,21 @@ github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcy
|
|||||||
github.com/Microsoft/hcsshim v0.8.6/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg=
|
github.com/Microsoft/hcsshim v0.8.6/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg=
|
||||||
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
||||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||||
|
github.com/containerd/containerd v1.4.1/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=
|
||||||
github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
|
github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
|
||||||
github.com/cyrilix/robocar-base v0.1.1 h1:zpD9oeqv4g6bUgOP/+KTuEcCinuEJ25yPzLkQJBuZPU=
|
github.com/cyrilix/robocar-base v0.1.4 h1:nfnjRwAcCfS7xGu6tW9rZhmc/HZIsuDJX5NFhgX5dWE=
|
||||||
github.com/cyrilix/robocar-base v0.1.1/go.mod h1:8z3uJpUJoQPDLUl66UD7aadYkNOsy2GipPN+OXPl4nk=
|
github.com/cyrilix/robocar-base v0.1.4/go.mod h1:Tt04UmbGBiQtU0Cn3wFD0q7XoyokTwIlWYQxThKI+04=
|
||||||
github.com/cyrilix/robocar-protobuf/go v1.0.0 h1:kPsmmYakcIWd/Y73YDufbdILJUna0tJcteKKWlNfVFY=
|
github.com/cyrilix/robocar-protobuf/go v1.0.3 h1:iPHw2+7FVXG2C4+Th1m11hQ+2RpAQzlxKhc5M7XOa6Q=
|
||||||
github.com/cyrilix/robocar-protobuf/go v1.0.0/go.mod h1:I+i6Ujns+4DmRmmUej56MItlmT4K2zlMZ35vZrHEfQ4=
|
github.com/cyrilix/robocar-protobuf/go v1.0.3/go.mod h1:xb95cK07lYXnKcHZKnGafmAgYRrqZWZgV9LMiJAp+gE=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
||||||
github.com/docker/docker v0.7.3-0.20190506211059-b20a14b54661/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
github.com/docker/docker v17.12.0-ce-rc1.0.20200916142827-bd33bbf0497b+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||||
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
|
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
|
||||||
github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||||
github.com/eclipse/paho.mqtt.golang v1.2.0 h1:1F8mhG9+aO5/xpdtFkW4SxOJB67ukuDC3t2y2qayIX0=
|
github.com/eclipse/paho.mqtt.golang v1.3.5 h1:sWtmgNxYM9P2sP+xEItMozsR3w0cqZFlqnNN1bdl41Y=
|
||||||
github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts=
|
github.com/eclipse/paho.mqtt.golang v1.3.5/go.mod h1:eTzb4gxwwyWpqBUHGQZ4ABAV7+Jgm1PklsYT/eo8Hcc=
|
||||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||||
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||||
@ -25,40 +26,31 @@ github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvSc
|
|||||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||||
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||||
github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
|
github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
|
||||||
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||||
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||||
github.com/golang/protobuf v1.2.0/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.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.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
|
||||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
|
||||||
github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
|
|
||||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
|
||||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
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.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
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/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||||
github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
|
github.com/gorilla/mux v1.6.2/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/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
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.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
|
||||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
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/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/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
@ -76,8 +68,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
|||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||||
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
||||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
@ -86,31 +78,26 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
|||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
|
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/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/testcontainers/testcontainers-go v0.7.0/go.mod h1:4dloDPrC94+8ebXA+Iei3Jy+gxF6uHQssJkB3mlP9Rg=
|
github.com/testcontainers/testcontainers-go v0.9.0/go.mod h1:b22BFXhRbg4PJmeMVWh6ftqjyZHgiIl3w274e9r3C2E=
|
||||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/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-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
|
||||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/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-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0 h1:Jcxah/M+oLZ/R4/z5RzfPzGbPXnVDPkEDtf2JnuxN+U=
|
||||||
golang.org/x/net v0.0.0-20200904194848-62affa334b73 h1:MXfv8rhZWmFeqX3GNZRsd6vOLoaCHjYEX3qkRo3YBUA=
|
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||||
golang.org/x/net v0.0.0-20200904194848-62affa334b73/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-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/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-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-20180909124046-d0be0721c37e/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-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
|
||||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f h1:Fqb3ao1hUmOR3GkUOg/Y+BadLwykBIzs5q8Ez2SbHyc=
|
|
||||||
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/text v0.3.0/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.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
@ -122,15 +109,10 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T
|
|||||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||||
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
|
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
|
||||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
|
||||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
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/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
|
||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||||
@ -142,5 +124,5 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie
|
|||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gotest.tools v0.0.0-20181223230014-1083505acf35/go.mod h1:R//lfYlUuTOTfblYI3lGoAAAebUdzjvbmQsuB7Ykd90=
|
gotest.tools v0.0.0-20181223230014-1083505acf35/go.mod h1:R//lfYlUuTOTfblYI3lGoAAAebUdzjvbmQsuB7Ykd90=
|
||||||
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
periph.io/x/periph v3.6.4+incompatible h1:8FyXTbu9lcMVofz8mf+cj1pzTLN4V6EuPY2EF+DoJF4=
|
periph.io/x/periph v3.6.8+incompatible h1:lki0ie6wHtvlilXhIkabdCUQMpb5QN4Fx33yNQdqnaA=
|
||||||
periph.io/x/periph v3.6.4+incompatible/go.mod h1:EWr+FCIU2dBWz5/wSWeiIUJTriYv9v2j2ENBmgYyy7Y=
|
periph.io/x/periph v3.6.8+incompatible/go.mod h1:EWr+FCIU2dBWz5/wSWeiIUJTriYv9v2j2ENBmgYyy7Y=
|
||||||
|
1
vendor/github.com/cyrilix/robocar-base/service/part.go
generated
vendored
1
vendor/github.com/cyrilix/robocar-base/service/part.go
generated
vendored
@ -30,4 +30,3 @@ type Part interface {
|
|||||||
Start() error
|
Start() error
|
||||||
Stop()
|
Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
1363
vendor/github.com/cyrilix/robocar-protobuf/go/events/events.pb.go
generated
vendored
1363
vendor/github.com/cyrilix/robocar-protobuf/go/events/events.pb.go
generated
vendored
File diff suppressed because it is too large
Load Diff
91
vendor/github.com/eclipse/paho.mqtt.golang/LICENSE
generated
vendored
91
vendor/github.com/eclipse/paho.mqtt.golang/LICENSE
generated
vendored
@ -1,87 +1,20 @@
|
|||||||
Eclipse Public License - v 1.0
|
This project is dual licensed under the Eclipse Public License 1.0 and the
|
||||||
|
Eclipse Distribution License 1.0 as described in the epl-v10 and edl-v10 files.
|
||||||
|
|
||||||
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
|
The EDL is copied below in order to pass the pkg.go.dev license check (https://pkg.go.dev/license-policy).
|
||||||
|
|
||||||
1. DEFINITIONS
|
****
|
||||||
|
Eclipse Distribution License - v 1.0
|
||||||
|
|
||||||
"Contribution" means:
|
Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors.
|
||||||
|
|
||||||
a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
|
All rights reserved.
|
||||||
|
|
||||||
b) in the case of each subsequent Contributor:
|
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
i) changes to the Program, and
|
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||||
|
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||||
|
Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||||
|
|
||||||
ii) additions to the Program;
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 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.
|
||||||
|
|
||||||
where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
|
|
||||||
|
|
||||||
"Contributor" means any person or entity that distributes the Program.
|
|
||||||
|
|
||||||
"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
|
|
||||||
|
|
||||||
"Program" means the Contributions distributed in accordance with this Agreement.
|
|
||||||
|
|
||||||
"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
|
|
||||||
|
|
||||||
2. GRANT OF RIGHTS
|
|
||||||
|
|
||||||
a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
|
|
||||||
|
|
||||||
b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
|
|
||||||
|
|
||||||
c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
|
|
||||||
|
|
||||||
d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
|
|
||||||
|
|
||||||
3. REQUIREMENTS
|
|
||||||
|
|
||||||
A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
|
|
||||||
|
|
||||||
a) it complies with the terms and conditions of this Agreement; and
|
|
||||||
|
|
||||||
b) its license agreement:
|
|
||||||
|
|
||||||
i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
|
|
||||||
|
|
||||||
ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
|
|
||||||
|
|
||||||
iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
|
|
||||||
|
|
||||||
iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
|
|
||||||
|
|
||||||
When the Program is made available in source code form:
|
|
||||||
|
|
||||||
a) it must be made available under this Agreement; and
|
|
||||||
|
|
||||||
b) a copy of this Agreement must be included with each copy of the Program.
|
|
||||||
|
|
||||||
Contributors may not remove or alter any copyright notices contained within the Program.
|
|
||||||
|
|
||||||
Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
|
|
||||||
|
|
||||||
4. COMMERCIAL DISTRIBUTION
|
|
||||||
|
|
||||||
Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
|
|
||||||
|
|
||||||
For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
|
|
||||||
|
|
||||||
5. NO WARRANTY
|
|
||||||
|
|
||||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
|
|
||||||
|
|
||||||
6. DISCLAIMER OF LIABILITY
|
|
||||||
|
|
||||||
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
|
||||||
7. GENERAL
|
|
||||||
|
|
||||||
If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
|
|
||||||
|
|
||||||
If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
|
|
||||||
|
|
||||||
All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
|
|
||||||
|
|
||||||
Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
|
|
||||||
|
|
||||||
This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
|
|
140
vendor/github.com/eclipse/paho.mqtt.golang/README.md
generated
vendored
140
vendor/github.com/eclipse/paho.mqtt.golang/README.md
generated
vendored
@ -1,32 +1,47 @@
|
|||||||
|
|
||||||
[](https://godoc.org/github.com/eclipse/paho.mqtt.golang)
|
[](https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang)
|
||||||
[](https://goreportcard.com/report/github.com/eclipse/paho.mqtt.golang)
|
[](https://goreportcard.com/report/github.com/eclipse/paho.mqtt.golang)
|
||||||
|
|
||||||
Eclipse Paho MQTT Go client
|
Eclipse Paho MQTT Go client
|
||||||
===========================
|
===========================
|
||||||
|
|
||||||
|
|
||||||
This repository contains the source code for the [Eclipse Paho](http://eclipse.org/paho) MQTT Go client library.
|
This repository contains the source code for the [Eclipse Paho](https://eclipse.org/paho) MQTT 3.1/3.11 Go client library.
|
||||||
|
|
||||||
This code builds a library which enable applications to connect to an [MQTT](http://mqtt.org) broker to publish messages, and to subscribe to topics and receive published messages.
|
This code builds a library which enable applications to connect to an [MQTT](https://mqtt.org) broker to publish
|
||||||
|
messages, and to subscribe to topics and receive published messages.
|
||||||
|
|
||||||
This library supports a fully asynchronous mode of operation.
|
This library supports a fully asynchronous mode of operation.
|
||||||
|
|
||||||
|
A client supporting MQTT V5 is [also available](https://github.com/eclipse/paho.golang).
|
||||||
|
|
||||||
Installation and Build
|
Installation and Build
|
||||||
----------------------
|
----------------------
|
||||||
|
|
||||||
This client is designed to work with the standard Go tools, so installation is as easy as:
|
The process depends upon whether you are using [modules](https://golang.org/ref/mod) (recommended) or `GOPATH`.
|
||||||
|
|
||||||
|
#### Modules
|
||||||
|
|
||||||
|
If you are using [modules](https://blog.golang.org/using-go-modules) then `import "github.com/eclipse/paho.mqtt.golang"`
|
||||||
|
and start using it. The necessary packages will be download automatically when you run `go build`.
|
||||||
|
|
||||||
|
Note that the latest release will be downloaded and changes may have been made since the release. If you have
|
||||||
|
encountered an issue, or wish to try the latest code for another reason, then run
|
||||||
|
`go get github.com/eclipse/paho.mqtt.golang@master` to get the latest commit.
|
||||||
|
|
||||||
|
#### GOPATH
|
||||||
|
|
||||||
|
Installation is as easy as:
|
||||||
|
|
||||||
```
|
```
|
||||||
go get github.com/eclipse/paho.mqtt.golang
|
go get github.com/eclipse/paho.mqtt.golang
|
||||||
```
|
```
|
||||||
|
|
||||||
The client depends on Google's [websockets](https://godoc.org/golang.org/x/net/websocket) and [proxy](https://godoc.org/golang.org/x/net/proxy) package,
|
The client depends on Google's [proxy](https://godoc.org/golang.org/x/net/proxy) package and the
|
||||||
also easily installed with the commands:
|
[websockets](https://godoc.org/github.com/gorilla/websocket) package, also easily installed with the commands:
|
||||||
|
|
||||||
```
|
```
|
||||||
go get golang.org/x/net/websocket
|
go get github.com/gorilla/websocket
|
||||||
go get golang.org/x/net/proxy
|
go get golang.org/x/net/proxy
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -35,27 +50,119 @@ Usage and API
|
|||||||
-------------
|
-------------
|
||||||
|
|
||||||
Detailed API documentation is available by using to godoc tool, or can be browsed online
|
Detailed API documentation is available by using to godoc tool, or can be browsed online
|
||||||
using the [godoc.org](http://godoc.org/github.com/eclipse/paho.mqtt.golang) service.
|
using the [pkg.go.dev](https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang) service.
|
||||||
|
|
||||||
Make use of the library by importing it in your Go client source code. For example,
|
|
||||||
```
|
|
||||||
import "github.com/eclipse/paho.mqtt.golang"
|
|
||||||
```
|
|
||||||
|
|
||||||
Samples are available in the `cmd` directory for reference.
|
Samples are available in the `cmd` directory for reference.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
|
||||||
Runtime tracing
|
The library also supports using MQTT over websockets by using the `ws://` (unsecure) or `wss://` (secure) prefix in the
|
||||||
|
URI. If the client is running behind a corporate http/https proxy then the following environment variables `HTTP_PROXY`,
|
||||||
|
`HTTPS_PROXY` and `NO_PROXY` are taken into account when establishing the connection.
|
||||||
|
|
||||||
|
Troubleshooting
|
||||||
---------------
|
---------------
|
||||||
|
|
||||||
Tracing is enabled by assigning logs (from the Go log package) to the logging endpoints, ERROR, CRITICAL, WARN and DEBUG
|
If you are new to MQTT and your application is not working as expected reviewing the
|
||||||
|
[MQTT specification](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html), which this library implements,
|
||||||
|
is a good first step. [MQTT.org](https://mqtt.org) has some [good resources](https://mqtt.org/getting-started/) that answer many
|
||||||
|
common questions.
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
|
||||||
|
The asynchronous nature of this library makes it easy to forget to check for errors. Consider using a go routine to
|
||||||
|
log these:
|
||||||
|
|
||||||
|
```go
|
||||||
|
t := client.Publish("topic", qos, retained, msg)
|
||||||
|
go func() {
|
||||||
|
_ = t.Wait() // Can also use '<-t.Done()' in releases > 1.2.0
|
||||||
|
if t.Error() != nil {
|
||||||
|
log.Error(t.Error()) // Use your preferred logging technique (or just fmt.Printf)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Logging
|
||||||
|
|
||||||
|
If you are encountering issues then enabling logging, both within this library and on your broker, is a good way to
|
||||||
|
begin troubleshooting. This library can produce various levels of log by assigning the logging endpoints, ERROR,
|
||||||
|
CRITICAL, WARN and DEBUG. For example:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func main() {
|
||||||
|
mqtt.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
|
||||||
|
mqtt.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
|
||||||
|
mqtt.WARN = log.New(os.Stdout, "[WARN] ", 0)
|
||||||
|
mqtt.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
|
||||||
|
|
||||||
|
// Connect, Subscribe, Publish etc..
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common Problems
|
||||||
|
|
||||||
|
* Seemingly random disconnections may be caused by another client connecting to the broker with the same client
|
||||||
|
identifier; this is as per the [spec](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800405).
|
||||||
|
* Unless ordered delivery of messages is essential (and you have configured your broker to support this e.g.
|
||||||
|
`max_inflight_messages=1` in mosquitto) then set `ClientOptions.SetOrderMatters(false)`. Doing so will avoid the
|
||||||
|
below issue (deadlocks due to blocking message handlers).
|
||||||
|
* A `MessageHandler` (called when a new message is received) must not block (unless
|
||||||
|
`ClientOptions.SetOrderMatters(false)` set). If you wish to perform a long-running task, or publish a message, then
|
||||||
|
please use a go routine (blocking in the handler is a common cause of unexpected `pingresp
|
||||||
|
not received, disconnecting` errors).
|
||||||
|
* When QOS1+ subscriptions have been created previously and you connect with `CleanSession` set to false it is possible that the broker will deliver retained
|
||||||
|
messages before `Subscribe` can be called. To process these messages either configure a handler with `AddRoute` or
|
||||||
|
set a `DefaultPublishHandler`.
|
||||||
|
* Loss of network connectivity may not be detected immediately. If this is an issue then consider setting
|
||||||
|
`ClientOptions.KeepAlive` (sends regular messages to check the link is active).
|
||||||
|
* Brokers offer many configuration options; some settings may lead to unexpected results. If using Mosquitto check
|
||||||
|
`max_inflight_messages`, `max_queued_messages`, `persistence` (the defaults may not be what you expect).
|
||||||
|
|
||||||
Reporting bugs
|
Reporting bugs
|
||||||
--------------
|
--------------
|
||||||
|
|
||||||
Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues
|
Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues
|
||||||
|
|
||||||
|
*A limited number of contributors monitor the issues section so if you have a general question please consider the
|
||||||
|
resources in the [more information](#more-information) section (your question will be seen by more people, and you are
|
||||||
|
likely to receive an answer more quickly).*
|
||||||
|
|
||||||
|
We welcome bug reports, but it is important they are actionable. A significant percentage of issues reported are not
|
||||||
|
resolved due to a lack of information. If we cannot replicate the problem then it is unlikely we will be able to fix it.
|
||||||
|
The information required will vary from issue to issue but consider including:
|
||||||
|
|
||||||
|
* Which version of the package you are using (tag or commit - this should be in your go.mod file)
|
||||||
|
* A [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Providing an example
|
||||||
|
is the best way to demonstrate the issue you are facing; it is important this includes all relevant information
|
||||||
|
(including broker configuration). Docker (see `cmd/docker`) makes it relatively simple to provide a working end-to-end
|
||||||
|
example.
|
||||||
|
* A full, clear, description of the problem (detail what you are expecting vs what actually happens).
|
||||||
|
* Details of your attempts to resolve the issue (what have you tried, what worked, what did not).
|
||||||
|
* [Application Logs](#logging) covering the period the issue occurred. Unless you have isolated the root cause of the issue please include a link to a full log (including data from well before the problem arose).
|
||||||
|
* Broker Logs covering the period the issue occurred.
|
||||||
|
|
||||||
|
It is important to remember that this library does not stand alone; it communicates with a broker and any issues you are
|
||||||
|
seeing may be due to:
|
||||||
|
|
||||||
|
* Bugs in your code.
|
||||||
|
* Bugs in this library.
|
||||||
|
* The broker configuration.
|
||||||
|
* Bugs in the broker.
|
||||||
|
* Issues with whatever you are communicating with.
|
||||||
|
|
||||||
|
When submitting an issue, please ensure that you provide sufficient details to enable us to eliminate causes outside of
|
||||||
|
this library.
|
||||||
|
|
||||||
|
Contributing
|
||||||
|
------------
|
||||||
|
|
||||||
|
We welcome pull requests but before your contribution can be accepted by the project, you need to create and
|
||||||
|
electronically sign the Eclipse Contributor Agreement (ECA) and sign off on the Eclipse Foundation Certificate of Origin.
|
||||||
|
|
||||||
|
More information is available in the
|
||||||
|
[Eclipse Development Resources](http://wiki.eclipse.org/Development_Resources/Contributing_via_Git); please take special
|
||||||
|
note of the requirement that the commit record contain a "Signed-off-by" entry.
|
||||||
|
|
||||||
More information
|
More information
|
||||||
----------------
|
----------------
|
||||||
@ -65,3 +172,6 @@ Discussion of the Paho clients takes place on the [Eclipse paho-dev mailing list
|
|||||||
General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt).
|
General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt).
|
||||||
|
|
||||||
There is much more information available via the [MQTT community site](http://mqtt.org).
|
There is much more information available via the [MQTT community site](http://mqtt.org).
|
||||||
|
|
||||||
|
[Stack Overflow](https://stackoverflow.com/questions/tagged/mqtt+go) has a range questions covering a range of common
|
||||||
|
issues (both relating to use of this library and MQTT in general).
|
||||||
|
948
vendor/github.com/eclipse/paho.mqtt.golang/client.go
generated
vendored
948
vendor/github.com/eclipse/paho.mqtt.golang/client.go
generated
vendored
File diff suppressed because it is too large
Load Diff
1
vendor/github.com/eclipse/paho.mqtt.golang/components.go
generated
vendored
1
vendor/github.com/eclipse/paho.mqtt.golang/components.go
generated
vendored
@ -28,4 +28,5 @@ const (
|
|||||||
TST component = "[test] "
|
TST component = "[test] "
|
||||||
STA component = "[state] "
|
STA component = "[state] "
|
||||||
ERR component = "[error] "
|
ERR component = "[error] "
|
||||||
|
ROU component = "[router] "
|
||||||
)
|
)
|
||||||
|
14
vendor/github.com/eclipse/paho.mqtt.golang/filestore.go
generated
vendored
14
vendor/github.com/eclipse/paho.mqtt.golang/filestore.go
generated
vendored
@ -101,7 +101,7 @@ func (store *FileStore) Get(key string) packets.ControlPacket {
|
|||||||
store.RLock()
|
store.RLock()
|
||||||
defer store.RUnlock()
|
defer store.RUnlock()
|
||||||
if !store.opened {
|
if !store.opened {
|
||||||
ERROR.Println(STR, "Trying to use file store, but not open")
|
ERROR.Println(STR, "trying to use file store, but not open")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
filepath := fullpath(store.directory, key)
|
filepath := fullpath(store.directory, key)
|
||||||
@ -117,14 +117,16 @@ func (store *FileStore) Get(key string) packets.ControlPacket {
|
|||||||
if rerr != nil {
|
if rerr != nil {
|
||||||
newpath := corruptpath(store.directory, key)
|
newpath := corruptpath(store.directory, key)
|
||||||
WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath)
|
WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath)
|
||||||
os.Rename(filepath, newpath)
|
if err := os.Rename(filepath, newpath); err != nil {
|
||||||
|
ERROR.Println(STR, err)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return msg
|
return msg
|
||||||
}
|
}
|
||||||
|
|
||||||
// All will provide a list of all of the keys associated with messages
|
// All will provide a list of all of the keys associated with messages
|
||||||
// currenly residing in the FileStore.
|
// currently residing in the FileStore.
|
||||||
func (store *FileStore) All() []string {
|
func (store *FileStore) All() []string {
|
||||||
store.RLock()
|
store.RLock()
|
||||||
defer store.RUnlock()
|
defer store.RUnlock()
|
||||||
@ -156,7 +158,7 @@ func (store *FileStore) all() []string {
|
|||||||
var files fileInfos
|
var files fileInfos
|
||||||
|
|
||||||
if !store.opened {
|
if !store.opened {
|
||||||
ERROR.Println(STR, "Trying to use file store, but not open")
|
ERROR.Println(STR, "trying to use file store, but not open")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -166,7 +168,7 @@ func (store *FileStore) all() []string {
|
|||||||
for _, f := range files {
|
for _, f := range files {
|
||||||
DEBUG.Println(STR, "file in All():", f.Name())
|
DEBUG.Println(STR, "file in All():", f.Name())
|
||||||
name := f.Name()
|
name := f.Name()
|
||||||
if name[len(name)-4:len(name)] != msgExt {
|
if name[len(name)-4:] != msgExt {
|
||||||
DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name)
|
DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -179,7 +181,7 @@ func (store *FileStore) all() []string {
|
|||||||
// lockless
|
// lockless
|
||||||
func (store *FileStore) del(key string) {
|
func (store *FileStore) del(key string) {
|
||||||
if !store.opened {
|
if !store.opened {
|
||||||
ERROR.Println(STR, "Trying to use file store, but not open")
|
ERROR.Println(STR, "trying to use file store, but not open")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
DEBUG.Println(STR, "store del filepath:", store.directory)
|
DEBUG.Println(STR, "store del filepath:", store.directory)
|
||||||
|
2
vendor/github.com/eclipse/paho.mqtt.golang/memstore.go
generated
vendored
2
vendor/github.com/eclipse/paho.mqtt.golang/memstore.go
generated
vendored
@ -88,7 +88,7 @@ func (store *MemoryStore) All() []string {
|
|||||||
ERROR.Println(STR, "Trying to use memory store, but not open")
|
ERROR.Println(STR, "Trying to use memory store, but not open")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
keys := []string{}
|
var keys []string
|
||||||
for k := range store.messages {
|
for k := range store.messages {
|
||||||
keys = append(keys, k)
|
keys = append(keys, k)
|
||||||
}
|
}
|
||||||
|
2
vendor/github.com/eclipse/paho.mqtt.golang/message.go
generated
vendored
2
vendor/github.com/eclipse/paho.mqtt.golang/message.go
generated
vendored
@ -16,9 +16,9 @@ package mqtt
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
"sync"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Message defines the externals that a message implementation must support
|
// Message defines the externals that a message implementation must support
|
||||||
|
69
vendor/github.com/eclipse/paho.mqtt.golang/messageids.go
generated
vendored
69
vendor/github.com/eclipse/paho.mqtt.golang/messageids.go
generated
vendored
@ -28,6 +28,8 @@ type MId uint16
|
|||||||
type messageIds struct {
|
type messageIds struct {
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
index map[uint16]tokenCompletor
|
index map[uint16]tokenCompletor
|
||||||
|
|
||||||
|
lastIssuedID uint16 // The most recently issued ID. Used so we cycle through ids rather than immediately reusing them (can make debugging easier)
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -40,11 +42,11 @@ func (mids *messageIds) cleanUp() {
|
|||||||
for _, token := range mids.index {
|
for _, token := range mids.index {
|
||||||
switch token.(type) {
|
switch token.(type) {
|
||||||
case *PublishToken:
|
case *PublishToken:
|
||||||
token.setError(fmt.Errorf("Connection lost before Publish completed"))
|
token.setError(fmt.Errorf("connection lost before Publish completed"))
|
||||||
case *SubscribeToken:
|
case *SubscribeToken:
|
||||||
token.setError(fmt.Errorf("Connection lost before Subscribe completed"))
|
token.setError(fmt.Errorf("connection lost before Subscribe completed"))
|
||||||
case *UnsubscribeToken:
|
case *UnsubscribeToken:
|
||||||
token.setError(fmt.Errorf("Connection lost before Unsubscribe completed"))
|
token.setError(fmt.Errorf("connection lost before Unsubscribe completed"))
|
||||||
case nil:
|
case nil:
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -71,18 +73,33 @@ func (mids *messageIds) claimID(token tokenCompletor, id uint16) {
|
|||||||
old.flowComplete()
|
old.flowComplete()
|
||||||
mids.index[id] = token
|
mids.index[id] = token
|
||||||
}
|
}
|
||||||
|
if id > mids.lastIssuedID {
|
||||||
|
mids.lastIssuedID = id
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getID will return an available id or 0 if none available
|
||||||
|
// The id will generally be the previous id + 1 (because this makes tracing messages a bit simpler)
|
||||||
func (mids *messageIds) getID(t tokenCompletor) uint16 {
|
func (mids *messageIds) getID(t tokenCompletor) uint16 {
|
||||||
mids.Lock()
|
mids.Lock()
|
||||||
defer mids.Unlock()
|
defer mids.Unlock()
|
||||||
for i := midMin; i < midMax; i++ {
|
i := mids.lastIssuedID // note: the only situation where lastIssuedID is 0 the map will be empty
|
||||||
|
looped := false // uint16 will loop from 65535->0
|
||||||
|
for {
|
||||||
|
i++
|
||||||
|
if i == 0 { // skip 0 because its not a valid id (Control Packets MUST contain a non-zero 16-bit Packet Identifier [MQTT-2.3.1-1])
|
||||||
|
i++
|
||||||
|
looped = true
|
||||||
|
}
|
||||||
if _, ok := mids.index[i]; !ok {
|
if _, ok := mids.index[i]; !ok {
|
||||||
mids.index[i] = t
|
mids.index[i] = t
|
||||||
|
mids.lastIssuedID = i
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
|
if (looped && i == mids.lastIssuedID) || (mids.lastIssuedID == 0 && i == midMax) { // lastIssuedID will be 0 at startup
|
||||||
|
return 0 // no free ids
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mids *messageIds) getToken(id uint16) tokenCompletor {
|
func (mids *messageIds) getToken(id uint16) tokenCompletor {
|
||||||
@ -98,14 +115,23 @@ type DummyToken struct {
|
|||||||
id uint16
|
id uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Wait implements the Token Wait method.
|
||||||
func (d *DummyToken) Wait() bool {
|
func (d *DummyToken) Wait() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WaitTimeout implements the Token WaitTimeout method.
|
||||||
func (d *DummyToken) WaitTimeout(t time.Duration) bool {
|
func (d *DummyToken) WaitTimeout(t time.Duration) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Done implements the Token Done method.
|
||||||
|
func (d *DummyToken) Done() <-chan struct{} {
|
||||||
|
ch := make(chan struct{})
|
||||||
|
close(ch)
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
func (d *DummyToken) flowComplete() {
|
func (d *DummyToken) flowComplete() {
|
||||||
ERROR.Printf("A lookup for token %d returned nil\n", d.id)
|
ERROR.Printf("A lookup for token %d returned nil\n", d.id)
|
||||||
}
|
}
|
||||||
@ -115,3 +141,36 @@ func (d *DummyToken) Error() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *DummyToken) setError(e error) {}
|
func (d *DummyToken) setError(e error) {}
|
||||||
|
|
||||||
|
// PlaceHolderToken does nothing and was implemented to allow a messageid to be reserved
|
||||||
|
// it differs from DummyToken in that calling flowComplete does not generate an error (it
|
||||||
|
// is expected that flowComplete will be called when the token is overwritten with a real token)
|
||||||
|
type PlaceHolderToken struct {
|
||||||
|
id uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait implements the Token Wait method.
|
||||||
|
func (p *PlaceHolderToken) Wait() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// WaitTimeout implements the Token WaitTimeout method.
|
||||||
|
func (p *PlaceHolderToken) WaitTimeout(t time.Duration) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Done implements the Token Done method.
|
||||||
|
func (p *PlaceHolderToken) Done() <-chan struct{} {
|
||||||
|
ch := make(chan struct{})
|
||||||
|
close(ch)
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PlaceHolderToken) flowComplete() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PlaceHolderToken) Error() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PlaceHolderToken) setError(e error) {}
|
||||||
|
623
vendor/github.com/eclipse/paho.mqtt.golang/net.go
generated
vendored
623
vendor/github.com/eclipse/paho.mqtt.golang/net.go
generated
vendored
@ -15,341 +15,450 @@
|
|||||||
package mqtt
|
package mqtt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"sync/atomic"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
"golang.org/x/net/proxy"
|
|
||||||
"golang.org/x/net/websocket"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func signalError(c chan<- error, err error) {
|
const closedNetConnErrorText = "use of closed network connection" // error string for closed conn (https://golang.org/src/net/error_test.go)
|
||||||
select {
|
|
||||||
case c <- err:
|
// ConnectMQTT takes a connected net.Conn and performs the initial MQTT handshake. Parameters are:
|
||||||
|
// conn - Connected net.Conn
|
||||||
|
// cm - Connect Packet with everything other than the protocol name/version populated (historical reasons)
|
||||||
|
// protocolVersion - The protocol version to attempt to connect with
|
||||||
|
//
|
||||||
|
// Note that, for backward compatibility, ConnectMQTT() suppresses the actual connection error (compare to connectMQTT()).
|
||||||
|
func ConnectMQTT(conn net.Conn, cm *packets.ConnectPacket, protocolVersion uint) (byte, bool) {
|
||||||
|
rc, sessionPresent, _ := connectMQTT(conn, cm, protocolVersion)
|
||||||
|
return rc, sessionPresent
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectMQTT(conn io.ReadWriter, cm *packets.ConnectPacket, protocolVersion uint) (byte, bool, error) {
|
||||||
|
switch protocolVersion {
|
||||||
|
case 3:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1 protocol")
|
||||||
|
cm.ProtocolName = "MQIsdp"
|
||||||
|
cm.ProtocolVersion = 3
|
||||||
|
case 0x83:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1b protocol")
|
||||||
|
cm.ProtocolName = "MQIsdp"
|
||||||
|
cm.ProtocolVersion = 0x83
|
||||||
|
case 0x84:
|
||||||
|
DEBUG.Println(CLI, "Using MQTT 3.1.1b protocol")
|
||||||
|
cm.ProtocolName = "MQTT"
|
||||||
|
cm.ProtocolVersion = 0x84
|
||||||
default:
|
default:
|
||||||
}
|
DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol")
|
||||||
|
cm.ProtocolName = "MQTT"
|
||||||
|
cm.ProtocolVersion = 4
|
||||||
}
|
}
|
||||||
|
|
||||||
func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration, headers http.Header) (net.Conn, error) {
|
if err := cm.Write(conn); err != nil {
|
||||||
switch uri.Scheme {
|
ERROR.Println(CLI, err)
|
||||||
case "ws":
|
return packets.ErrNetworkError, false, err
|
||||||
config, _ := websocket.NewConfig(uri.String(), fmt.Sprintf("http://%s", uri.Host))
|
|
||||||
config.Protocol = []string{"mqtt"}
|
|
||||||
config.Header = headers
|
|
||||||
config.Dialer = &net.Dialer{Timeout: timeout}
|
|
||||||
conn, err := websocket.DialConfig(config)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn.PayloadType = websocket.BinaryFrame
|
|
||||||
return conn, err
|
|
||||||
case "wss":
|
|
||||||
config, _ := websocket.NewConfig(uri.String(), fmt.Sprintf("https://%s", uri.Host))
|
|
||||||
config.Protocol = []string{"mqtt"}
|
|
||||||
config.TlsConfig = tlsc
|
|
||||||
config.Header = headers
|
|
||||||
config.Dialer = &net.Dialer{Timeout: timeout}
|
|
||||||
conn, err := websocket.DialConfig(config)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn.PayloadType = websocket.BinaryFrame
|
|
||||||
return conn, err
|
|
||||||
case "tcp":
|
|
||||||
allProxy := os.Getenv("all_proxy")
|
|
||||||
if len(allProxy) == 0 {
|
|
||||||
conn, err := net.DialTimeout("tcp", uri.Host, timeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
proxyDialer := proxy.FromEnvironment()
|
|
||||||
|
|
||||||
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
case "unix":
|
|
||||||
conn, err := net.DialTimeout("unix", uri.Host, timeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
case "ssl":
|
|
||||||
fallthrough
|
|
||||||
case "tls":
|
|
||||||
fallthrough
|
|
||||||
case "tcps":
|
|
||||||
allProxy := os.Getenv("all_proxy")
|
|
||||||
if len(allProxy) == 0 {
|
|
||||||
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
proxyDialer := proxy.FromEnvironment()
|
|
||||||
|
|
||||||
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConn := tls.Client(conn, tlsc)
|
rc, sessionPresent, err := verifyCONNACK(conn)
|
||||||
|
return rc, sessionPresent, err
|
||||||
|
}
|
||||||
|
|
||||||
err = tlsConn.Handshake()
|
// This function is only used for receiving a connack
|
||||||
|
// when the connection is first started.
|
||||||
|
// This prevents receiving incoming data while resume
|
||||||
|
// is in progress if clean session is false.
|
||||||
|
func verifyCONNACK(conn io.Reader) (byte, bool, error) {
|
||||||
|
DEBUG.Println(NET, "connect started")
|
||||||
|
|
||||||
|
ca, err := packets.ReadPacket(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
conn.Close()
|
ERROR.Println(NET, "connect got error", err)
|
||||||
return nil, err
|
return packets.ErrNetworkError, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return tlsConn, nil
|
if ca == nil {
|
||||||
}
|
ERROR.Println(NET, "received nil packet")
|
||||||
return nil, errors.New("Unknown protocol")
|
return packets.ErrNetworkError, false, errors.New("nil CONNACK packet")
|
||||||
}
|
}
|
||||||
|
|
||||||
// actually read incoming messages off the wire
|
msg, ok := ca.(*packets.ConnackPacket)
|
||||||
// send Message object into ibound channel
|
if !ok {
|
||||||
func incoming(c *client) {
|
ERROR.Println(NET, "received msg that was not CONNACK")
|
||||||
|
return packets.ErrNetworkError, false, errors.New("non-CONNACK first packet received")
|
||||||
|
}
|
||||||
|
|
||||||
|
DEBUG.Println(NET, "received connack")
|
||||||
|
return msg.ReturnCode, msg.SessionPresent, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// inbound encapsulates the output from startIncoming.
|
||||||
|
// err - If != nil then an error has occurred
|
||||||
|
// cp - A control packet received over the network link
|
||||||
|
type inbound struct {
|
||||||
|
err error
|
||||||
|
cp packets.ControlPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
// startIncoming initiates a goroutine that reads incoming messages off the wire and sends them to the channel (returned).
|
||||||
|
// If there are any issues with the network connection then the returned channel will be closed and the goroutine will exit
|
||||||
|
// (so closing the connection will terminate the goroutine)
|
||||||
|
func startIncoming(conn io.Reader) <-chan inbound {
|
||||||
var err error
|
var err error
|
||||||
var cp packets.ControlPacket
|
var cp packets.ControlPacket
|
||||||
|
ibound := make(chan inbound)
|
||||||
defer c.workers.Done()
|
|
||||||
|
|
||||||
DEBUG.Println(NET, "incoming started")
|
DEBUG.Println(NET, "incoming started")
|
||||||
|
|
||||||
|
go func() {
|
||||||
for {
|
for {
|
||||||
if cp, err = packets.ReadPacket(c.conn); err != nil {
|
if cp, err = packets.ReadPacket(conn); err != nil {
|
||||||
break
|
// We do not want to log the error if it is due to the network connection having been closed
|
||||||
|
// elsewhere (i.e. after sending DisconnectPacket). Detecting this situation is the subject of
|
||||||
|
// https://github.com/golang/go/issues/4373
|
||||||
|
if !strings.Contains(err.Error(), closedNetConnErrorText) {
|
||||||
|
ibound <- inbound{err: err}
|
||||||
}
|
}
|
||||||
DEBUG.Println(NET, "Received Message")
|
close(ibound)
|
||||||
select {
|
DEBUG.Println(NET, "incoming complete")
|
||||||
case c.ibound <- cp:
|
|
||||||
// Notify keepalive logic that we recently received a packet
|
|
||||||
if c.options.KeepAlive != 0 {
|
|
||||||
c.lastReceived.Store(time.Now())
|
|
||||||
}
|
|
||||||
case <-c.stop:
|
|
||||||
// This avoids a deadlock should a message arrive while shutting down.
|
|
||||||
// In that case the "reader" of c.ibound might already be gone
|
|
||||||
WARN.Println(NET, "incoming dropped a received message during shutdown")
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// We received an error on read.
|
|
||||||
// If disconnect is in progress, swallow error and return
|
|
||||||
select {
|
|
||||||
case <-c.stop:
|
|
||||||
DEBUG.Println(NET, "incoming stopped")
|
|
||||||
return
|
|
||||||
// Not trying to disconnect, send the error to the errors channel
|
|
||||||
default:
|
|
||||||
ERROR.Println(NET, "incoming stopped with error", err)
|
|
||||||
signalError(c.errors, err)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
DEBUG.Println(NET, "startIncoming Received Message")
|
||||||
|
ibound <- inbound{cp: cp}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return ibound
|
||||||
|
}
|
||||||
|
|
||||||
|
// incomingComms encapsulates the possible output of the incomingComms routine. If err != nil then an error has occurred and
|
||||||
|
// the routine will have terminated; otherwise one of the other members should be non-nil
|
||||||
|
type incomingComms struct {
|
||||||
|
err error // If non-nil then there has been an error (ignore everything else)
|
||||||
|
outbound *PacketAndToken // Packet (with token) than needs to be sent out (e.g. an acknowledgement)
|
||||||
|
incomingPub *packets.PublishPacket // A new publish has been received; this will need to be passed on to our user
|
||||||
|
}
|
||||||
|
|
||||||
|
// startIncomingComms initiates incoming communications; this includes starting a goroutine to process incoming
|
||||||
|
// messages.
|
||||||
|
// Accepts a channel of inbound messages from the store (persisted messages); note this must be closed as soon as the
|
||||||
|
// everything in the store has been sent.
|
||||||
|
// Returns a channel that will be passed any received packets; this will be closed on a network error (and inboundFromStore closed)
|
||||||
|
func startIncomingComms(conn io.Reader,
|
||||||
|
c commsFns,
|
||||||
|
inboundFromStore <-chan packets.ControlPacket,
|
||||||
|
) <-chan incomingComms {
|
||||||
|
ibound := startIncoming(conn) // Start goroutine that reads from network connection
|
||||||
|
output := make(chan incomingComms)
|
||||||
|
|
||||||
|
DEBUG.Println(NET, "startIncomingComms started")
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
if inboundFromStore == nil && ibound == nil {
|
||||||
|
close(output)
|
||||||
|
DEBUG.Println(NET, "startIncomingComms goroutine complete")
|
||||||
|
return // As soon as ibound is closed we can exit (should have already processed an error)
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "logic waiting for msg on ibound")
|
||||||
|
|
||||||
|
var msg packets.ControlPacket
|
||||||
|
var ok bool
|
||||||
|
select {
|
||||||
|
case msg, ok = <-inboundFromStore:
|
||||||
|
if !ok {
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: inboundFromStore complete")
|
||||||
|
inboundFromStore = nil // should happen quickly as this is only for persisted messages
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: got msg from store")
|
||||||
|
case ibMsg, ok := <-ibound:
|
||||||
|
if !ok {
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: ibound complete")
|
||||||
|
ibound = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: got msg on ibound")
|
||||||
|
// If the inbound comms routine encounters any issues it will send us an error.
|
||||||
|
if ibMsg.err != nil {
|
||||||
|
output <- incomingComms{err: ibMsg.err}
|
||||||
|
continue // Usually the channel will be closed immediately after sending an error but safer that we do not assume this
|
||||||
|
}
|
||||||
|
msg = ibMsg.cp
|
||||||
|
|
||||||
|
c.persistInbound(msg)
|
||||||
|
c.UpdateLastReceived() // Notify keepalive logic that we recently received a packet
|
||||||
|
}
|
||||||
|
|
||||||
|
switch m := msg.(type) {
|
||||||
|
case *packets.PingrespPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received pingresp")
|
||||||
|
c.pingRespReceived()
|
||||||
|
case *packets.SubackPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received suback, id:", m.MessageID)
|
||||||
|
token := c.getToken(m.MessageID)
|
||||||
|
|
||||||
|
if t, ok := token.(*SubscribeToken); ok {
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: granted qoss", m.ReturnCodes)
|
||||||
|
for i, qos := range m.ReturnCodes {
|
||||||
|
t.subResult[t.subs[i]] = qos
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// receive a Message object on obound, and then
|
token.flowComplete()
|
||||||
// actually send outgoing message to the wire
|
c.freeID(m.MessageID)
|
||||||
func outgoing(c *client) {
|
case *packets.UnsubackPacket:
|
||||||
defer c.workers.Done()
|
DEBUG.Println(NET, "startIncomingComms: received unsuback, id:", m.MessageID)
|
||||||
|
c.getToken(m.MessageID).flowComplete()
|
||||||
|
c.freeID(m.MessageID)
|
||||||
|
case *packets.PublishPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received publish, msgId:", m.MessageID)
|
||||||
|
output <- incomingComms{incomingPub: m}
|
||||||
|
case *packets.PubackPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received puback, id:", m.MessageID)
|
||||||
|
c.getToken(m.MessageID).flowComplete()
|
||||||
|
c.freeID(m.MessageID)
|
||||||
|
case *packets.PubrecPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received pubrec, id:", m.MessageID)
|
||||||
|
prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
|
||||||
|
prel.MessageID = m.MessageID
|
||||||
|
output <- incomingComms{outbound: &PacketAndToken{p: prel, t: nil}}
|
||||||
|
case *packets.PubrelPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received pubrel, id:", m.MessageID)
|
||||||
|
pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket)
|
||||||
|
pc.MessageID = m.MessageID
|
||||||
|
c.persistOutbound(pc)
|
||||||
|
output <- incomingComms{outbound: &PacketAndToken{p: pc, t: nil}}
|
||||||
|
case *packets.PubcompPacket:
|
||||||
|
DEBUG.Println(NET, "startIncomingComms: received pubcomp, id:", m.MessageID)
|
||||||
|
c.getToken(m.MessageID).flowComplete()
|
||||||
|
c.freeID(m.MessageID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
// startOutgoingComms initiates a go routine to transmit outgoing packets.
|
||||||
|
// Pass in an open network connection and channels for outbound messages (including those triggered
|
||||||
|
// directly from incoming comms).
|
||||||
|
// Returns a channel that will receive details of any errors (closed when the goroutine exits)
|
||||||
|
// This function wil only terminate when all input channels are closed
|
||||||
|
func startOutgoingComms(conn net.Conn,
|
||||||
|
c commsFns,
|
||||||
|
oboundp <-chan *PacketAndToken,
|
||||||
|
obound <-chan *PacketAndToken,
|
||||||
|
oboundFromIncoming <-chan *PacketAndToken,
|
||||||
|
) <-chan error {
|
||||||
|
errChan := make(chan error)
|
||||||
DEBUG.Println(NET, "outgoing started")
|
DEBUG.Println(NET, "outgoing started")
|
||||||
|
|
||||||
|
go func() {
|
||||||
for {
|
for {
|
||||||
DEBUG.Println(NET, "outgoing waiting for an outbound message")
|
DEBUG.Println(NET, "outgoing waiting for an outbound message")
|
||||||
|
|
||||||
|
// This goroutine will only exits when all of the input channels we receive on have been closed. This approach is taken to avoid any
|
||||||
|
// deadlocks (if the connection goes down there are limited options as to what we can do with anything waiting on us and
|
||||||
|
// throwing away the packets seems the best option)
|
||||||
|
if oboundp == nil && obound == nil && oboundFromIncoming == nil {
|
||||||
|
DEBUG.Println(NET, "outgoing comms stopping")
|
||||||
|
close(errChan)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-c.stop:
|
case pub, ok := <-obound:
|
||||||
DEBUG.Println(NET, "outgoing stopped")
|
if !ok {
|
||||||
return
|
obound = nil
|
||||||
case pub := <-c.obound:
|
continue
|
||||||
|
}
|
||||||
msg := pub.p.(*packets.PublishPacket)
|
msg := pub.p.(*packets.PublishPacket)
|
||||||
|
DEBUG.Println(NET, "obound msg to write", msg.MessageID)
|
||||||
|
|
||||||
if c.options.WriteTimeout > 0 {
|
writeTimeout := c.getWriteTimeOut()
|
||||||
c.conn.SetWriteDeadline(time.Now().Add(c.options.WriteTimeout))
|
if writeTimeout > 0 {
|
||||||
|
if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
|
||||||
|
ERROR.Println(NET, "SetWriteDeadline ", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := msg.Write(c.conn); err != nil {
|
if err := msg.Write(conn); err != nil {
|
||||||
ERROR.Println(NET, "outgoing stopped with error", err)
|
ERROR.Println(NET, "outgoing obound reporting error ", err)
|
||||||
pub.t.setError(err)
|
pub.t.setError(err)
|
||||||
signalError(c.errors, err)
|
// report error if it's not due to the connection being closed elsewhere
|
||||||
return
|
if !strings.Contains(err.Error(), closedNetConnErrorText) {
|
||||||
|
errChan <- err
|
||||||
|
}
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.options.WriteTimeout > 0 {
|
if writeTimeout > 0 {
|
||||||
// If we successfully wrote, we don't want the timeout to happen during an idle period
|
// If we successfully wrote, we don't want the timeout to happen during an idle period
|
||||||
// so we reset it to infinite.
|
// so we reset it to infinite.
|
||||||
c.conn.SetWriteDeadline(time.Time{})
|
if err := conn.SetWriteDeadline(time.Time{}); err != nil {
|
||||||
|
ERROR.Println(NET, "SetWriteDeadline to 0 ", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if msg.Qos == 0 {
|
if msg.Qos == 0 {
|
||||||
pub.t.flowComplete()
|
pub.t.flowComplete()
|
||||||
}
|
}
|
||||||
DEBUG.Println(NET, "obound wrote msg, id:", msg.MessageID)
|
DEBUG.Println(NET, "obound wrote msg, id:", msg.MessageID)
|
||||||
case msg := <-c.oboundP:
|
case msg, ok := <-oboundp:
|
||||||
switch msg.p.(type) {
|
if !ok {
|
||||||
case *packets.SubscribePacket:
|
oboundp = nil
|
||||||
msg.p.(*packets.SubscribePacket).MessageID = c.getID(msg.t)
|
continue
|
||||||
case *packets.UnsubscribePacket:
|
|
||||||
msg.p.(*packets.UnsubscribePacket).MessageID = c.getID(msg.t)
|
|
||||||
}
|
}
|
||||||
DEBUG.Println(NET, "obound priority msg to write, type", reflect.TypeOf(msg.p))
|
DEBUG.Println(NET, "obound priority msg to write, type", reflect.TypeOf(msg.p))
|
||||||
if err := msg.p.Write(c.conn); err != nil {
|
if err := msg.p.Write(conn); err != nil {
|
||||||
ERROR.Println(NET, "outgoing stopped with error", err)
|
ERROR.Println(NET, "outgoing oboundp reporting error ", err)
|
||||||
if msg.t != nil {
|
if msg.t != nil {
|
||||||
msg.t.setError(err)
|
msg.t.setError(err)
|
||||||
}
|
}
|
||||||
signalError(c.errors, err)
|
errChan <- err
|
||||||
return
|
continue
|
||||||
}
|
}
|
||||||
switch msg.p.(type) {
|
|
||||||
case *packets.DisconnectPacket:
|
if _, ok := msg.p.(*packets.DisconnectPacket); ok {
|
||||||
msg.t.(*DisconnectToken).flowComplete()
|
msg.t.(*DisconnectToken).flowComplete()
|
||||||
DEBUG.Println(NET, "outbound wrote disconnect, stopping")
|
DEBUG.Println(NET, "outbound wrote disconnect, closing connection")
|
||||||
return
|
// As per the MQTT spec "After sending a DISCONNECT Packet the Client MUST close the Network Connection"
|
||||||
|
// Closing the connection will cause the goroutines to end in sequence (starting with incoming comms)
|
||||||
|
conn.Close()
|
||||||
|
}
|
||||||
|
case msg, ok := <-oboundFromIncoming: // message triggered by an inbound message (PubrecPacket or PubrelPacket)
|
||||||
|
if !ok {
|
||||||
|
oboundFromIncoming = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
DEBUG.Println(NET, "obound from incoming msg to write, type", reflect.TypeOf(msg.p), " ID ", msg.p.Details().MessageID)
|
||||||
|
if err := msg.p.Write(conn); err != nil {
|
||||||
|
ERROR.Println(NET, "outgoing oboundFromIncoming reporting error", err)
|
||||||
|
if msg.t != nil {
|
||||||
|
msg.t.setError(err)
|
||||||
|
}
|
||||||
|
errChan <- err
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Reset ping timer after sending control packet.
|
c.UpdateLastSent() // Record that a packet has been received (for keepalive routine)
|
||||||
if c.options.KeepAlive != 0 {
|
|
||||||
c.lastSent.Store(time.Now())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}()
|
||||||
|
return errChan
|
||||||
}
|
}
|
||||||
|
|
||||||
// receive Message objects on ibound
|
// commsFns provide access to the client state (messageids, requesting disconnection and updating timing)
|
||||||
// store messages if necessary
|
type commsFns interface {
|
||||||
// send replies on obound
|
getToken(id uint16) tokenCompletor // Retrieve the token for the specified messageid (if none then a dummy token must be returned)
|
||||||
// delete messages from store if necessary
|
freeID(id uint16) // Release the specified messageid (clearing out of any persistent store)
|
||||||
func alllogic(c *client) {
|
UpdateLastReceived() // Must be called whenever a packet is received
|
||||||
defer c.workers.Done()
|
UpdateLastSent() // Must be called whenever a packet is successfully sent
|
||||||
DEBUG.Println(NET, "logic started")
|
getWriteTimeOut() time.Duration // Return the writetimeout (or 0 if none)
|
||||||
|
persistOutbound(m packets.ControlPacket) // add the packet to the outbound store
|
||||||
for {
|
persistInbound(m packets.ControlPacket) // add the packet to the inbound store
|
||||||
DEBUG.Println(NET, "logic waiting for msg on ibound")
|
pingRespReceived() // Called when a ping response is received
|
||||||
|
|
||||||
select {
|
|
||||||
case msg := <-c.ibound:
|
|
||||||
DEBUG.Println(NET, "logic got msg on ibound")
|
|
||||||
persistInbound(c.persist, msg)
|
|
||||||
switch m := msg.(type) {
|
|
||||||
case *packets.PingrespPacket:
|
|
||||||
DEBUG.Println(NET, "received pingresp")
|
|
||||||
atomic.StoreInt32(&c.pingOutstanding, 0)
|
|
||||||
case *packets.SubackPacket:
|
|
||||||
DEBUG.Println(NET, "received suback, id:", m.MessageID)
|
|
||||||
token := c.getToken(m.MessageID)
|
|
||||||
switch t := token.(type) {
|
|
||||||
case *SubscribeToken:
|
|
||||||
DEBUG.Println(NET, "granted qoss", m.ReturnCodes)
|
|
||||||
for i, qos := range m.ReturnCodes {
|
|
||||||
t.subResult[t.subs[i]] = qos
|
|
||||||
}
|
|
||||||
}
|
|
||||||
token.flowComplete()
|
|
||||||
c.freeID(m.MessageID)
|
|
||||||
case *packets.UnsubackPacket:
|
|
||||||
DEBUG.Println(NET, "received unsuback, id:", m.MessageID)
|
|
||||||
c.getToken(m.MessageID).flowComplete()
|
|
||||||
c.freeID(m.MessageID)
|
|
||||||
case *packets.PublishPacket:
|
|
||||||
DEBUG.Println(NET, "received publish, msgId:", m.MessageID)
|
|
||||||
DEBUG.Println(NET, "putting msg on onPubChan")
|
|
||||||
switch m.Qos {
|
|
||||||
case 2:
|
|
||||||
c.incomingPubChan <- m
|
|
||||||
DEBUG.Println(NET, "done putting msg on incomingPubChan")
|
|
||||||
case 1:
|
|
||||||
c.incomingPubChan <- m
|
|
||||||
DEBUG.Println(NET, "done putting msg on incomingPubChan")
|
|
||||||
case 0:
|
|
||||||
select {
|
|
||||||
case c.incomingPubChan <- m:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "done putting msg on incomingPubChan")
|
|
||||||
}
|
|
||||||
case *packets.PubackPacket:
|
|
||||||
DEBUG.Println(NET, "received puback, id:", m.MessageID)
|
|
||||||
// c.receipts.get(msg.MsgId()) <- Receipt{}
|
|
||||||
// c.receipts.end(msg.MsgId())
|
|
||||||
c.getToken(m.MessageID).flowComplete()
|
|
||||||
c.freeID(m.MessageID)
|
|
||||||
case *packets.PubrecPacket:
|
|
||||||
DEBUG.Println(NET, "received pubrec, id:", m.MessageID)
|
|
||||||
prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
|
|
||||||
prel.MessageID = m.MessageID
|
|
||||||
select {
|
|
||||||
case c.oboundP <- &PacketAndToken{p: prel, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
case *packets.PubrelPacket:
|
|
||||||
DEBUG.Println(NET, "received pubrel, id:", m.MessageID)
|
|
||||||
pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket)
|
|
||||||
pc.MessageID = m.MessageID
|
|
||||||
persistOutbound(c.persist, pc)
|
|
||||||
select {
|
|
||||||
case c.oboundP <- &PacketAndToken{p: pc, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
case *packets.PubcompPacket:
|
|
||||||
DEBUG.Println(NET, "received pubcomp, id:", m.MessageID)
|
|
||||||
c.getToken(m.MessageID).flowComplete()
|
|
||||||
c.freeID(m.MessageID)
|
|
||||||
}
|
|
||||||
case <-c.stop:
|
|
||||||
WARN.Println(NET, "logic stopped")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ackFunc(packet *packets.PublishPacket) func() {
|
// startComms initiates goroutines that handles communications over the network connection
|
||||||
|
// Messages will be stored (via commsFns) and deleted from the store as necessary
|
||||||
|
// It returns two channels:
|
||||||
|
// packets.PublishPacket - Will receive publish packets received over the network.
|
||||||
|
// Closed when incoming comms routines exit (on shutdown or if network link closed)
|
||||||
|
// error - Any errors will be sent on this channel. The channel is closed when all comms routines have shut down
|
||||||
|
//
|
||||||
|
// Note: The comms routines monitoring oboundp and obound will not shutdown until those channels are both closed. Any messages received between the
|
||||||
|
// connection being closed and those channels being closed will generate errors (and nothing will be sent). That way the chance of a deadlock is
|
||||||
|
// minimised.
|
||||||
|
func startComms(conn net.Conn, // Network connection (must be active)
|
||||||
|
c commsFns, // getters and setters to enable us to cleanly interact with client
|
||||||
|
inboundFromStore <-chan packets.ControlPacket, // Inbound packets from the persistence store (should be closed relatively soon after startup)
|
||||||
|
oboundp <-chan *PacketAndToken,
|
||||||
|
obound <-chan *PacketAndToken) (
|
||||||
|
<-chan *packets.PublishPacket, // Publishpackages received over the network
|
||||||
|
<-chan error, // Any errors (should generally trigger a disconnect)
|
||||||
|
) {
|
||||||
|
// Start inbound comms handler; this needs to be able to transmit messages so we start a go routine to add these to the priority outbound channel
|
||||||
|
ibound := startIncomingComms(conn, c, inboundFromStore)
|
||||||
|
outboundFromIncoming := make(chan *PacketAndToken) // Will accept outgoing messages triggered by startIncomingComms (e.g. acknowledgements)
|
||||||
|
|
||||||
|
// Start the outgoing handler. It is important to note that output from startIncomingComms is fed into startOutgoingComms (for ACK's)
|
||||||
|
oboundErr := startOutgoingComms(conn, c, oboundp, obound, outboundFromIncoming)
|
||||||
|
DEBUG.Println(NET, "startComms started")
|
||||||
|
|
||||||
|
// Run up go routines to handle the output from the above comms functions - these are handled in separate
|
||||||
|
// go routines because they can interact (e.g. ibound triggers an ACK to obound which triggers an error)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(2)
|
||||||
|
|
||||||
|
outPublish := make(chan *packets.PublishPacket)
|
||||||
|
outError := make(chan error)
|
||||||
|
|
||||||
|
// Any messages received get passed to the appropriate channel
|
||||||
|
go func() {
|
||||||
|
for ic := range ibound {
|
||||||
|
if ic.err != nil {
|
||||||
|
outError <- ic.err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ic.outbound != nil {
|
||||||
|
outboundFromIncoming <- ic.outbound
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ic.incomingPub != nil {
|
||||||
|
outPublish <- ic.incomingPub
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ERROR.Println(STR, "startComms received empty incomingComms msg")
|
||||||
|
}
|
||||||
|
// Close channels that will not be written to again (allowing other routines to exit)
|
||||||
|
close(outboundFromIncoming)
|
||||||
|
close(outPublish)
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Any errors will be passed out to our caller
|
||||||
|
go func() {
|
||||||
|
for err := range oboundErr {
|
||||||
|
outError <- err
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// outError is used by both routines so can only be closed when they are both complete
|
||||||
|
go func() {
|
||||||
|
wg.Wait()
|
||||||
|
close(outError)
|
||||||
|
DEBUG.Println(NET, "startComms closing outError")
|
||||||
|
}()
|
||||||
|
|
||||||
|
return outPublish, outError
|
||||||
|
}
|
||||||
|
|
||||||
|
// ackFunc acknowledges a packet
|
||||||
|
// WARNING the function returned must not be called if the comms routine is shutting down or not running
|
||||||
|
// (it needs outgoing comms in order to send the acknowledgement). Currently this is only called from
|
||||||
|
// matchAndDispatch which will be shutdown before the comms are
|
||||||
|
func ackFunc(oboundP chan *PacketAndToken, persist Store, packet *packets.PublishPacket) func() {
|
||||||
return func() {
|
return func() {
|
||||||
switch packet.Qos {
|
switch packet.Qos {
|
||||||
case 2:
|
case 2:
|
||||||
pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket)
|
pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket)
|
||||||
pr.MessageID = packet.MessageID
|
pr.MessageID = packet.MessageID
|
||||||
DEBUG.Println(NET, "putting pubrec msg on obound")
|
DEBUG.Println(NET, "putting pubrec msg on obound")
|
||||||
select {
|
oboundP <- &PacketAndToken{p: pr, t: nil}
|
||||||
case c.oboundP <- &PacketAndToken{p: pr, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "done putting pubrec msg on obound")
|
DEBUG.Println(NET, "done putting pubrec msg on obound")
|
||||||
case 1:
|
case 1:
|
||||||
pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
|
pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
|
||||||
pa.MessageID = packet.MessageID
|
pa.MessageID = packet.MessageID
|
||||||
DEBUG.Println(NET, "putting puback msg on obound")
|
DEBUG.Println(NET, "putting puback msg on obound")
|
||||||
persistOutbound(c.persist, pa)
|
persistOutbound(persist, pa)
|
||||||
select {
|
oboundP <- &PacketAndToken{p: pa, t: nil}
|
||||||
case c.oboundP <- &PacketAndToken{p: pa, t: nil}:
|
|
||||||
case <-c.stop:
|
|
||||||
}
|
|
||||||
DEBUG.Println(NET, "done putting puback msg on obound")
|
DEBUG.Println(NET, "done putting puback msg on obound")
|
||||||
case 0:
|
case 0:
|
||||||
// do nothing, since there is no need to send an ack packet back
|
// do nothing, since there is no need to send an ack packet back
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func errorWatch(c *client) {
|
|
||||||
defer c.workers.Done()
|
|
||||||
select {
|
|
||||||
case <-c.stop:
|
|
||||||
WARN.Println(NET, "errorWatch stopped")
|
|
||||||
return
|
|
||||||
case err := <-c.errors:
|
|
||||||
ERROR.Println(NET, "error triggered, stopping")
|
|
||||||
go c.internalConnLost(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
92
vendor/github.com/eclipse/paho.mqtt.golang/netconn.go
generated
vendored
Normal file
92
vendor/github.com/eclipse/paho.mqtt.golang/netconn.go
generated
vendored
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2013 IBM Corp.
|
||||||
|
*
|
||||||
|
* All rights reserved. This program and the accompanying materials
|
||||||
|
* are made available under the terms of the Eclipse Public License v1.0
|
||||||
|
* which accompanies this distribution, and is available at
|
||||||
|
* http://www.eclipse.org/legal/epl-v10.html
|
||||||
|
*
|
||||||
|
* Contributors:
|
||||||
|
* Seth Hoenig
|
||||||
|
* Allan Stockdill-Mander
|
||||||
|
* Mike Robertson
|
||||||
|
*/
|
||||||
|
|
||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/net/proxy"
|
||||||
|
)
|
||||||
|
|
||||||
|
//
|
||||||
|
// This just establishes the network connection; once established the type of connection should be irrelevant
|
||||||
|
//
|
||||||
|
|
||||||
|
// openConnection opens a network connection using the protocol indicated in the URL.
|
||||||
|
// Does not carry out any MQTT specific handshakes.
|
||||||
|
func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration, headers http.Header, websocketOptions *WebsocketOptions) (net.Conn, error) {
|
||||||
|
switch uri.Scheme {
|
||||||
|
case "ws":
|
||||||
|
conn, err := NewWebsocket(uri.String(), nil, timeout, headers, websocketOptions)
|
||||||
|
return conn, err
|
||||||
|
case "wss":
|
||||||
|
conn, err := NewWebsocket(uri.String(), tlsc, timeout, headers, websocketOptions)
|
||||||
|
return conn, err
|
||||||
|
case "mqtt", "tcp":
|
||||||
|
allProxy := os.Getenv("all_proxy")
|
||||||
|
if len(allProxy) == 0 {
|
||||||
|
conn, err := net.DialTimeout("tcp", uri.Host, timeout)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
proxyDialer := proxy.FromEnvironment()
|
||||||
|
|
||||||
|
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
case "unix":
|
||||||
|
conn, err := net.DialTimeout("unix", uri.Host, timeout)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
case "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
|
||||||
|
allProxy := os.Getenv("all_proxy")
|
||||||
|
if len(allProxy) == 0 {
|
||||||
|
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
proxyDialer := proxy.FromEnvironment()
|
||||||
|
|
||||||
|
conn, err := proxyDialer.Dial("tcp", uri.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConn := tls.Client(conn, tlsc)
|
||||||
|
|
||||||
|
err = tlsConn.Handshake()
|
||||||
|
if err != nil {
|
||||||
|
_ = conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tlsConn, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("unknown protocol")
|
||||||
|
}
|
93
vendor/github.com/eclipse/paho.mqtt.golang/options.go
generated
vendored
93
vendor/github.com/eclipse/paho.mqtt.golang/options.go
generated
vendored
@ -10,6 +10,7 @@
|
|||||||
* Seth Hoenig
|
* Seth Hoenig
|
||||||
* Allan Stockdill-Mander
|
* Allan Stockdill-Mander
|
||||||
* Mike Robertson
|
* Mike Robertson
|
||||||
|
* Måns Ansgariusson
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Portions copyright © 2018 TIBCO Software Inc.
|
// Portions copyright © 2018 TIBCO Software Inc.
|
||||||
@ -44,7 +45,15 @@ type ConnectionLostHandler func(Client, error)
|
|||||||
// at initial connection and on reconnection
|
// at initial connection and on reconnection
|
||||||
type OnConnectHandler func(Client)
|
type OnConnectHandler func(Client)
|
||||||
|
|
||||||
// ClientOptions contains configurable options for an Client.
|
// ReconnectHandler is invoked prior to reconnecting after
|
||||||
|
// the initial connection is lost
|
||||||
|
type ReconnectHandler func(Client, *ClientOptions)
|
||||||
|
|
||||||
|
// ConnectionAttemptHandler is invoked prior to making the initial connection.
|
||||||
|
type ConnectionAttemptHandler func(broker *url.URL, tlsCfg *tls.Config) *tls.Config
|
||||||
|
|
||||||
|
// ClientOptions contains configurable options for an Client. Note that these should be set using the
|
||||||
|
// relevant methods (e.g. AddBroker) rather than directly. See those functions for information on usage.
|
||||||
type ClientOptions struct {
|
type ClientOptions struct {
|
||||||
Servers []*url.URL
|
Servers []*url.URL
|
||||||
ClientID string
|
ClientID string
|
||||||
@ -66,21 +75,26 @@ type ClientOptions struct {
|
|||||||
ConnectTimeout time.Duration
|
ConnectTimeout time.Duration
|
||||||
MaxReconnectInterval time.Duration
|
MaxReconnectInterval time.Duration
|
||||||
AutoReconnect bool
|
AutoReconnect bool
|
||||||
|
ConnectRetryInterval time.Duration
|
||||||
|
ConnectRetry bool
|
||||||
Store Store
|
Store Store
|
||||||
DefaultPublishHandler MessageHandler
|
DefaultPublishHandler MessageHandler
|
||||||
OnConnect OnConnectHandler
|
OnConnect OnConnectHandler
|
||||||
OnConnectionLost ConnectionLostHandler
|
OnConnectionLost ConnectionLostHandler
|
||||||
|
OnReconnecting ReconnectHandler
|
||||||
|
OnConnectAttempt ConnectionAttemptHandler
|
||||||
WriteTimeout time.Duration
|
WriteTimeout time.Duration
|
||||||
MessageChannelDepth uint
|
MessageChannelDepth uint
|
||||||
ResumeSubs bool
|
ResumeSubs bool
|
||||||
HTTPHeaders http.Header
|
HTTPHeaders http.Header
|
||||||
|
WebsocketOptions *WebsocketOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClientOptions will create a new ClientClientOptions type with some
|
// NewClientOptions will create a new ClientClientOptions type with some
|
||||||
// default values.
|
// default values.
|
||||||
// Port: 1883
|
// Port: 1883
|
||||||
// CleanSession: True
|
// CleanSession: True
|
||||||
// Order: True
|
// Order: True (note: it is recommended that this be set to FALSE unless order is important)
|
||||||
// KeepAlive: 30 (seconds)
|
// KeepAlive: 30 (seconds)
|
||||||
// ConnectTimeout: 30 (seconds)
|
// ConnectTimeout: 30 (seconds)
|
||||||
// MaxReconnectInterval 10 (minutes)
|
// MaxReconnectInterval 10 (minutes)
|
||||||
@ -105,13 +119,16 @@ func NewClientOptions() *ClientOptions {
|
|||||||
ConnectTimeout: 30 * time.Second,
|
ConnectTimeout: 30 * time.Second,
|
||||||
MaxReconnectInterval: 10 * time.Minute,
|
MaxReconnectInterval: 10 * time.Minute,
|
||||||
AutoReconnect: true,
|
AutoReconnect: true,
|
||||||
|
ConnectRetryInterval: 30 * time.Second,
|
||||||
|
ConnectRetry: false,
|
||||||
Store: nil,
|
Store: nil,
|
||||||
OnConnect: nil,
|
OnConnect: nil,
|
||||||
OnConnectionLost: DefaultConnectionLostHandler,
|
OnConnectionLost: DefaultConnectionLostHandler,
|
||||||
|
OnConnectAttempt: nil,
|
||||||
WriteTimeout: 0, // 0 represents timeout disabled
|
WriteTimeout: 0, // 0 represents timeout disabled
|
||||||
MessageChannelDepth: 100,
|
|
||||||
ResumeSubs: false,
|
ResumeSubs: false,
|
||||||
HTTPHeaders: make(map[string][]string),
|
HTTPHeaders: make(map[string][]string),
|
||||||
|
WebsocketOptions: &WebsocketOptions{},
|
||||||
}
|
}
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
@ -149,7 +166,7 @@ func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions {
|
|||||||
|
|
||||||
// SetClientID will set the client id to be used by this client when
|
// SetClientID will set the client id to be used by this client when
|
||||||
// connecting to the MQTT broker. According to the MQTT v3.1 specification,
|
// connecting to the MQTT broker. According to the MQTT v3.1 specification,
|
||||||
// a client id mus be no longer than 23 characters.
|
// a client id must be no longer than 23 characters.
|
||||||
func (o *ClientOptions) SetClientID(id string) *ClientOptions {
|
func (o *ClientOptions) SetClientID(id string) *ClientOptions {
|
||||||
o.ClientID = id
|
o.ClientID = id
|
||||||
return o
|
return o
|
||||||
@ -157,7 +174,7 @@ func (o *ClientOptions) SetClientID(id string) *ClientOptions {
|
|||||||
|
|
||||||
// SetUsername will set the username to be used by this client when connecting
|
// SetUsername will set the username to be used by this client when connecting
|
||||||
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
||||||
// be sent in plaintext accross the wire.
|
// be sent in plaintext across the wire.
|
||||||
func (o *ClientOptions) SetUsername(u string) *ClientOptions {
|
func (o *ClientOptions) SetUsername(u string) *ClientOptions {
|
||||||
o.Username = u
|
o.Username = u
|
||||||
return o
|
return o
|
||||||
@ -165,7 +182,7 @@ func (o *ClientOptions) SetUsername(u string) *ClientOptions {
|
|||||||
|
|
||||||
// SetPassword will set the password to be used by this client when connecting
|
// SetPassword will set the password to be used by this client when connecting
|
||||||
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
// to the MQTT broker. Note: without the use of SSL/TLS, this information will
|
||||||
// be sent in plaintext accross the wire.
|
// be sent in plaintext across the wire.
|
||||||
func (o *ClientOptions) SetPassword(p string) *ClientOptions {
|
func (o *ClientOptions) SetPassword(p string) *ClientOptions {
|
||||||
o.Password = p
|
o.Password = p
|
||||||
return o
|
return o
|
||||||
@ -174,7 +191,7 @@ func (o *ClientOptions) SetPassword(p string) *ClientOptions {
|
|||||||
// SetCredentialsProvider will set a method to be called by this client when
|
// SetCredentialsProvider will set a method to be called by this client when
|
||||||
// connecting to the MQTT broker that provide the current username and password.
|
// connecting to the MQTT broker that provide the current username and password.
|
||||||
// Note: without the use of SSL/TLS, this information will be sent
|
// Note: without the use of SSL/TLS, this information will be sent
|
||||||
// in plaintext accross the wire.
|
// in plaintext across the wire.
|
||||||
func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions {
|
func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions {
|
||||||
o.CredentialsProvider = p
|
o.CredentialsProvider = p
|
||||||
return o
|
return o
|
||||||
@ -184,7 +201,7 @@ func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOpt
|
|||||||
// when this client connects to an MQTT broker. By setting this flag, you are
|
// when this client connects to an MQTT broker. By setting this flag, you are
|
||||||
// indicating that no messages saved by the broker for this client should be
|
// indicating that no messages saved by the broker for this client should be
|
||||||
// delivered. Any messages that were going to be sent by this client before
|
// delivered. Any messages that were going to be sent by this client before
|
||||||
// diconnecting previously but didn't will not be sent upon connecting to the
|
// disconnecting previously but didn't will not be sent upon connecting to the
|
||||||
// broker.
|
// broker.
|
||||||
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
|
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
|
||||||
o.CleanSession = clean
|
o.CleanSession = clean
|
||||||
@ -192,9 +209,13 @@ func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetOrderMatters will set the message routing to guarantee order within
|
// SetOrderMatters will set the message routing to guarantee order within
|
||||||
// each QoS level. By default, this value is true. If set to false,
|
// each QoS level. By default, this value is true. If set to false (recommended),
|
||||||
// this flag indicates that messages can be delivered asynchronously
|
// this flag indicates that messages can be delivered asynchronously
|
||||||
// from the client to the application and possibly arrive out of order.
|
// from the client to the application and possibly arrive out of order.
|
||||||
|
// Specifically, the message handler is called in its own go routine.
|
||||||
|
// Note that setting this to true does not guarantee in-order delivery
|
||||||
|
// (this is subject to broker settings like "max_inflight_messages=1" in mosquitto)
|
||||||
|
// and if true then handlers must not block.
|
||||||
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions {
|
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions {
|
||||||
o.Order = order
|
o.Order = order
|
||||||
return o
|
return o
|
||||||
@ -274,6 +295,11 @@ func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, re
|
|||||||
|
|
||||||
// SetDefaultPublishHandler sets the MessageHandler that will be called when a message
|
// SetDefaultPublishHandler sets the MessageHandler that will be called when a message
|
||||||
// is received that does not match any known subscriptions.
|
// is received that does not match any known subscriptions.
|
||||||
|
//
|
||||||
|
// If OrderMatters is true (the defaultHandler) then callback must not block or
|
||||||
|
// call functions within this package that may block (e.g. Publish) other than in
|
||||||
|
// a new go routine.
|
||||||
|
// defaultHandler must be safe for concurrent use by multiple goroutines.
|
||||||
func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions {
|
func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions {
|
||||||
o.DefaultPublishHandler = defaultHandler
|
o.DefaultPublishHandler = defaultHandler
|
||||||
return o
|
return o
|
||||||
@ -293,15 +319,31 @@ func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *
|
|||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetReconnectingHandler sets the OnReconnecting callback to be executed prior
|
||||||
|
// to the client attempting a reconnect to the MQTT broker.
|
||||||
|
func (o *ClientOptions) SetReconnectingHandler(cb ReconnectHandler) *ClientOptions {
|
||||||
|
o.OnReconnecting = cb
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConnectionAttemptHandler sets the ConnectionAttemptHandler callback to be executed prior
|
||||||
|
// to each attempt to connect to an MQTT broker. Returns the *tls.Config that will be used when establishing
|
||||||
|
// the connection (a copy of the tls.Config from ClientOptions will be passed in along with the broker URL).
|
||||||
|
// This allows connection specific changes to be made to the *tls.Config.
|
||||||
|
func (o *ClientOptions) SetConnectionAttemptHandler(onConnectAttempt ConnectionAttemptHandler) *ClientOptions {
|
||||||
|
o.OnConnectAttempt = onConnectAttempt
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a
|
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a
|
||||||
// timeout error. A duration of 0 never times out. Default 30 seconds
|
// timeout error. A duration of 0 never times out. Default never times out
|
||||||
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions {
|
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions {
|
||||||
o.WriteTimeout = t
|
o.WriteTimeout = t
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetConnectTimeout limits how long the client will wait when trying to open a connection
|
// SetConnectTimeout limits how long the client will wait when trying to open a connection
|
||||||
// to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out.
|
// to an MQTT server before timing out. A duration of 0 never times out.
|
||||||
// Default 30 seconds. Currently only operational on TCP/TLS connections.
|
// Default 30 seconds. Currently only operational on TCP/TLS connections.
|
||||||
func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions {
|
func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions {
|
||||||
o.ConnectTimeout = t
|
o.ConnectTimeout = t
|
||||||
@ -323,10 +365,25 @@ func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions {
|
|||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetMessageChannelDepth sets the size of the internal queue that holds messages while the
|
// SetConnectRetryInterval sets the time that will be waited between connection attempts
|
||||||
// client is temporairily offline, allowing the application to publish when the client is
|
// when initially connecting if ConnectRetry is TRUE
|
||||||
// reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise
|
func (o *ClientOptions) SetConnectRetryInterval(t time.Duration) *ClientOptions {
|
||||||
// ignored.
|
o.ConnectRetryInterval = t
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConnectRetry sets whether the connect function will automatically retry the connection
|
||||||
|
// in the event of a failure (when true the token returned by the Connect function will
|
||||||
|
// not complete until the connection is up or it is cancelled)
|
||||||
|
// If ConnectRetry is true then subscriptions should be requested in OnConnect handler
|
||||||
|
// Setting this to TRUE permits messages to be published before the connection is established
|
||||||
|
func (o *ClientOptions) SetConnectRetry(a bool) *ClientOptions {
|
||||||
|
o.ConnectRetry = a
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetMessageChannelDepth DEPRECATED The value set here no longer has any effect, this function
|
||||||
|
// remains so the API is not altered.
|
||||||
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions {
|
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions {
|
||||||
o.MessageChannelDepth = s
|
o.MessageChannelDepth = s
|
||||||
return o
|
return o
|
||||||
@ -338,3 +395,9 @@ func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions {
|
|||||||
o.HTTPHeaders = h
|
o.HTTPHeaders = h
|
||||||
return o
|
return o
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetWebsocketOptions sets the additional websocket options used in a WebSocket connection
|
||||||
|
func (o *ClientOptions) SetWebsocketOptions(w *WebsocketOptions) *ClientOptions {
|
||||||
|
o.WebsocketOptions = w
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
18
vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go
generated
vendored
18
vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go
generated
vendored
@ -133,6 +133,18 @@ func (r *ClientOptionsReader) AutoReconnect() bool {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ConnectRetryInterval returns the delay between retries on the initial connection (if ConnectRetry true)
|
||||||
|
func (r *ClientOptionsReader) ConnectRetryInterval() time.Duration {
|
||||||
|
s := r.options.ConnectRetryInterval
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectRetry returns whether the initial connection request will be retried until connection established
|
||||||
|
func (r *ClientOptionsReader) ConnectRetry() bool {
|
||||||
|
s := r.options.ConnectRetry
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
func (r *ClientOptionsReader) WriteTimeout() time.Duration {
|
func (r *ClientOptionsReader) WriteTimeout() time.Duration {
|
||||||
s := r.options.WriteTimeout
|
s := r.options.WriteTimeout
|
||||||
return s
|
return s
|
||||||
@ -147,3 +159,9 @@ func (r *ClientOptionsReader) HTTPHeaders() http.Header {
|
|||||||
h := r.options.HTTPHeaders
|
h := r.options.HTTPHeaders
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WebsocketOptions returns the currently configured WebSocket options
|
||||||
|
func (r *ClientOptionsReader) WebsocketOptions() *WebsocketOptions {
|
||||||
|
s := r.options.WebsocketOptions
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go
generated
vendored
@ -15,10 +15,7 @@ type ConnackPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ca *ConnackPacket) String() string {
|
func (ca *ConnackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", ca.FixedHeader)
|
return fmt.Sprintf("%s sessionpresent: %t returncode: %d", ca.FixedHeader, ca.SessionPresent, ca.ReturnCode)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("sessionpresent: %t returncode: %d", ca.SessionPresent, ca.ReturnCode)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ca *ConnackPacket) Write(w io.Writer) error {
|
func (ca *ConnackPacket) Write(w io.Writer) error {
|
||||||
|
9
vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go
generated
vendored
9
vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go
generated
vendored
@ -29,10 +29,11 @@ type ConnectPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConnectPacket) String() string {
|
func (c *ConnectPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", c.FixedHeader)
|
var password string
|
||||||
str += " "
|
if len(c.Password) > 0 {
|
||||||
str += fmt.Sprintf("protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, c.Password)
|
password = "<redacted>"
|
||||||
return str
|
}
|
||||||
|
return fmt.Sprintf("%s protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.FixedHeader, c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, password)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConnectPacket) Write(w io.Writer) error {
|
func (c *ConnectPacket) Write(w io.Writer) error {
|
||||||
|
4
vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go
generated
vendored
4
vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go
generated
vendored
@ -1,7 +1,6 @@
|
|||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -12,8 +11,7 @@ type DisconnectPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *DisconnectPacket) String() string {
|
func (d *DisconnectPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", d.FixedHeader)
|
return d.FixedHeader.String()
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DisconnectPacket) Write(w io.Writer) error {
|
func (d *DisconnectPacket) Write(w io.Writer) error {
|
||||||
|
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go
generated
vendored
32
vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go
generated
vendored
@ -81,17 +81,27 @@ var ConnackReturnCodes = map[uint8]string{
|
|||||||
255: "Connection Refused: Protocol Violation",
|
255: "Connection Refused: Protocol Violation",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrorRefusedBadProtocolVersion = errors.New("unacceptable protocol version")
|
||||||
|
ErrorRefusedIDRejected = errors.New("identifier rejected")
|
||||||
|
ErrorRefusedServerUnavailable = errors.New("server Unavailable")
|
||||||
|
ErrorRefusedBadUsernameOrPassword = errors.New("bad user name or password")
|
||||||
|
ErrorRefusedNotAuthorised = errors.New("not Authorized")
|
||||||
|
ErrorNetworkError = errors.New("network Error")
|
||||||
|
ErrorProtocolViolation = errors.New("protocol Violation")
|
||||||
|
)
|
||||||
|
|
||||||
// ConnErrors is a map of the errors codes constants for Connect()
|
// ConnErrors is a map of the errors codes constants for Connect()
|
||||||
// to a Go error
|
// to a Go error
|
||||||
var ConnErrors = map[byte]error{
|
var ConnErrors = map[byte]error{
|
||||||
Accepted: nil,
|
Accepted: nil,
|
||||||
ErrRefusedBadProtocolVersion: errors.New("Unnacceptable protocol version"),
|
ErrRefusedBadProtocolVersion: ErrorRefusedBadProtocolVersion,
|
||||||
ErrRefusedIDRejected: errors.New("Identifier rejected"),
|
ErrRefusedIDRejected: ErrorRefusedIDRejected,
|
||||||
ErrRefusedServerUnavailable: errors.New("Server Unavailable"),
|
ErrRefusedServerUnavailable: ErrorRefusedServerUnavailable,
|
||||||
ErrRefusedBadUsernameOrPassword: errors.New("Bad user name or password"),
|
ErrRefusedBadUsernameOrPassword: ErrorRefusedBadUsernameOrPassword,
|
||||||
ErrRefusedNotAuthorised: errors.New("Not Authorized"),
|
ErrRefusedNotAuthorised: ErrorRefusedNotAuthorised,
|
||||||
ErrNetworkError: errors.New("Network Error"),
|
ErrNetworkError: ErrorNetworkError,
|
||||||
ErrProtocolViolation: errors.New("Protocol Violation"),
|
ErrProtocolViolation: ErrorProtocolViolation,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts
|
// ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts
|
||||||
@ -123,7 +133,7 @@ func ReadPacket(r io.Reader) (ControlPacket, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if n != fh.RemainingLength {
|
if n != fh.RemainingLength {
|
||||||
return nil, errors.New("Failed to read expected data")
|
return nil, errors.New("failed to read expected data")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cp.Unpack(bytes.NewBuffer(packetBytes))
|
err = cp.Unpack(bytes.NewBuffer(packetBytes))
|
||||||
@ -274,9 +284,9 @@ func decodeUint16(b io.Reader) (uint16, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func encodeUint16(num uint16) []byte {
|
func encodeUint16(num uint16) []byte {
|
||||||
bytes := make([]byte, 2)
|
bytesResult := make([]byte, 2)
|
||||||
binary.BigEndian.PutUint16(bytes, num)
|
binary.BigEndian.PutUint16(bytesResult, num)
|
||||||
return bytes
|
return bytesResult
|
||||||
}
|
}
|
||||||
|
|
||||||
func encodeString(field string) []byte {
|
func encodeString(field string) []byte {
|
||||||
|
4
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go
generated
vendored
4
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go
generated
vendored
@ -1,7 +1,6 @@
|
|||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -12,8 +11,7 @@ type PingreqPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingreqPacket) String() string {
|
func (pr *PingreqPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return pr.FixedHeader.String()
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingreqPacket) Write(w io.Writer) error {
|
func (pr *PingreqPacket) Write(w io.Writer) error {
|
||||||
|
4
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go
generated
vendored
4
vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go
generated
vendored
@ -1,7 +1,6 @@
|
|||||||
package packets
|
package packets
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -12,8 +11,7 @@ type PingrespPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingrespPacket) String() string {
|
func (pr *PingrespPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return pr.FixedHeader.String()
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PingrespPacket) Write(w io.Writer) error {
|
func (pr *PingrespPacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go
generated
vendored
@ -13,10 +13,7 @@ type PubackPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pa *PubackPacket) String() string {
|
func (pa *PubackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pa.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pa.FixedHeader, pa.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pa.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pa *PubackPacket) Write(w io.Writer) error {
|
func (pa *PubackPacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go
generated
vendored
@ -13,10 +13,7 @@ type PubcompPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pc *PubcompPacket) String() string {
|
func (pc *PubcompPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pc.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pc.FixedHeader, pc.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pc.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pc *PubcompPacket) Write(w io.Writer) error {
|
func (pc *PubcompPacket) Write(w io.Writer) error {
|
||||||
|
9
vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go
generated
vendored
9
vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go
generated
vendored
@ -16,12 +16,7 @@ type PublishPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *PublishPacket) String() string {
|
func (p *PublishPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", p.FixedHeader)
|
return fmt.Sprintf("%s topicName: %s MessageID: %d payload: %s", p.FixedHeader, p.TopicName, p.MessageID, string(p.Payload))
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("topicName: %s MessageID: %d", p.TopicName, p.MessageID)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("payload: %s", string(p.Payload))
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *PublishPacket) Write(w io.Writer) error {
|
func (p *PublishPacket) Write(w io.Writer) error {
|
||||||
@ -61,7 +56,7 @@ func (p *PublishPacket) Unpack(b io.Reader) error {
|
|||||||
payloadLength -= len(p.TopicName) + 2
|
payloadLength -= len(p.TopicName) + 2
|
||||||
}
|
}
|
||||||
if payloadLength < 0 {
|
if payloadLength < 0 {
|
||||||
return fmt.Errorf("Error unpacking publish, payload length < 0")
|
return fmt.Errorf("error unpacking publish, payload length < 0")
|
||||||
}
|
}
|
||||||
p.Payload = make([]byte, payloadLength)
|
p.Payload = make([]byte, payloadLength)
|
||||||
_, err = b.Read(p.Payload)
|
_, err = b.Read(p.Payload)
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go
generated
vendored
@ -13,10 +13,7 @@ type PubrecPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrecPacket) String() string {
|
func (pr *PubrecPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pr.FixedHeader, pr.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pr.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrecPacket) Write(w io.Writer) error {
|
func (pr *PubrecPacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go
generated
vendored
@ -13,10 +13,7 @@ type PubrelPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrelPacket) String() string {
|
func (pr *PubrelPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", pr.FixedHeader, pr.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pr.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr *PubrelPacket) Write(w io.Writer) error {
|
func (pr *PubrelPacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go
generated
vendored
@ -15,10 +15,7 @@ type SubackPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (sa *SubackPacket) String() string {
|
func (sa *SubackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", sa.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", sa.FixedHeader, sa.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", sa.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sa *SubackPacket) Write(w io.Writer) error {
|
func (sa *SubackPacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go
generated
vendored
@ -16,10 +16,7 @@ type SubscribePacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *SubscribePacket) String() string {
|
func (s *SubscribePacket) String() string {
|
||||||
str := fmt.Sprintf("%s", s.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d topics: %s", s.FixedHeader, s.MessageID, s.Topics)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d topics: %s", s.MessageID, s.Topics)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SubscribePacket) Write(w io.Writer) error {
|
func (s *SubscribePacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go
generated
vendored
@ -13,10 +13,7 @@ type UnsubackPacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ua *UnsubackPacket) String() string {
|
func (ua *UnsubackPacket) String() string {
|
||||||
str := fmt.Sprintf("%s", ua.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", ua.FixedHeader, ua.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", ua.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ua *UnsubackPacket) Write(w io.Writer) error {
|
func (ua *UnsubackPacket) Write(w io.Writer) error {
|
||||||
|
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go
generated
vendored
5
vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go
generated
vendored
@ -15,10 +15,7 @@ type UnsubscribePacket struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *UnsubscribePacket) String() string {
|
func (u *UnsubscribePacket) String() string {
|
||||||
str := fmt.Sprintf("%s", u.FixedHeader)
|
return fmt.Sprintf("%s MessageID: %d", u.FixedHeader, u.MessageID)
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", u.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UnsubscribePacket) Write(w io.Writer) error {
|
func (u *UnsubscribePacket) Write(w io.Writer) error {
|
||||||
|
13
vendor/github.com/eclipse/paho.mqtt.golang/ping.go
generated
vendored
13
vendor/github.com/eclipse/paho.mqtt.golang/ping.go
generated
vendored
@ -16,13 +16,16 @@ package mqtt
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
)
|
)
|
||||||
|
|
||||||
func keepalive(c *client) {
|
// keepalive - Send ping when connection unused for set period
|
||||||
|
// connection passed in to avoid race condition on shutdown
|
||||||
|
func keepalive(c *client, conn io.Writer) {
|
||||||
defer c.workers.Done()
|
defer c.workers.Done()
|
||||||
DEBUG.Println(PNG, "keepalive starting")
|
DEBUG.Println(PNG, "keepalive starting")
|
||||||
var checkInterval int64
|
var checkInterval int64
|
||||||
@ -54,14 +57,16 @@ func keepalive(c *client) {
|
|||||||
// We don't want to wait behind large messages being sent, the Write call
|
// We don't want to wait behind large messages being sent, the Write call
|
||||||
// will block until it it able to send the packet.
|
// will block until it it able to send the packet.
|
||||||
atomic.StoreInt32(&c.pingOutstanding, 1)
|
atomic.StoreInt32(&c.pingOutstanding, 1)
|
||||||
ping.Write(c.conn)
|
if err := ping.Write(conn); err != nil {
|
||||||
|
ERROR.Println(PNG, err)
|
||||||
|
}
|
||||||
c.lastSent.Store(time.Now())
|
c.lastSent.Store(time.Now())
|
||||||
pingSent = time.Now()
|
pingSent = time.Now()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if atomic.LoadInt32(&c.pingOutstanding) > 0 && time.Now().Sub(pingSent) >= c.options.PingTimeout {
|
if atomic.LoadInt32(&c.pingOutstanding) > 0 && time.Since(pingSent) >= c.options.PingTimeout {
|
||||||
CRITICAL.Println(PNG, "pingresp not received, disconnecting")
|
CRITICAL.Println(PNG, "pingresp not received, disconnecting")
|
||||||
c.errors <- errors.New("pingresp not received, disconnecting")
|
c.internalConnLost(errors.New("pingresp not received, disconnecting")) // no harm in calling this if the connection is already down (or shutdown is in progress)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
94
vendor/github.com/eclipse/paho.mqtt.golang/router.go
generated
vendored
94
vendor/github.com/eclipse/paho.mqtt.golang/router.go
generated
vendored
@ -37,17 +37,11 @@ type route struct {
|
|||||||
// and returns a boolean of the outcome
|
// and returns a boolean of the outcome
|
||||||
func match(route []string, topic []string) bool {
|
func match(route []string, topic []string) bool {
|
||||||
if len(route) == 0 {
|
if len(route) == 0 {
|
||||||
if len(topic) == 0 {
|
return len(topic) == 0
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(topic) == 0 {
|
if len(topic) == 0 {
|
||||||
if route[0] == "#" {
|
return route[0] == "#"
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if route[0] == "#" {
|
if route[0] == "#" {
|
||||||
@ -87,15 +81,13 @@ type router struct {
|
|||||||
routes *list.List
|
routes *list.List
|
||||||
defaultHandler MessageHandler
|
defaultHandler MessageHandler
|
||||||
messages chan *packets.PublishPacket
|
messages chan *packets.PublishPacket
|
||||||
stop chan bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// newRouter returns a new instance of a Router and channel which can be used to tell the Router
|
// newRouter returns a new instance of a Router and channel which can be used to tell the Router
|
||||||
// to stop
|
// to stop
|
||||||
func newRouter() (*router, chan bool) {
|
func newRouter() *router {
|
||||||
router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)}
|
router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket)}
|
||||||
stop := router.stop
|
return router
|
||||||
return router, stop
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of
|
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of
|
||||||
@ -105,7 +97,7 @@ func (r *router) addRoute(topic string, callback MessageHandler) {
|
|||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
for e := r.routes.Front(); e != nil; e = e.Next() {
|
for e := r.routes.Front(); e != nil; e = e.Next() {
|
||||||
if e.Value.(*route).match(topic) {
|
if e.Value.(*route).topic == topic {
|
||||||
r := e.Value.(*route)
|
r := e.Value.(*route)
|
||||||
r.callback = callback
|
r.callback = callback
|
||||||
return
|
return
|
||||||
@ -120,7 +112,7 @@ func (r *router) deleteRoute(topic string) {
|
|||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
for e := r.routes.Front(); e != nil; e = e.Next() {
|
for e := r.routes.Front(); e != nil; e = e.Next() {
|
||||||
if e.Value.(*route).match(topic) {
|
if e.Value.(*route).topic == topic {
|
||||||
r.routes.Remove(e)
|
r.routes.Remove(e)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -139,49 +131,99 @@ func (r *router) setDefaultHandler(handler MessageHandler) {
|
|||||||
// takes messages off the channel, matches them against the internal route list and calls the
|
// takes messages off the channel, matches them against the internal route list and calls the
|
||||||
// associated callback (or the defaultHandler, if one exists and no other route matched). If
|
// associated callback (or the defaultHandler, if one exists and no other route matched). If
|
||||||
// anything is sent down the stop channel the function will end.
|
// anything is sent down the stop channel the function will end.
|
||||||
func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client) {
|
func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client) <-chan *PacketAndToken {
|
||||||
go func() {
|
var wg sync.WaitGroup
|
||||||
|
ackOutChan := make(chan *PacketAndToken) // Channel returned to caller; closed when messages channel closed
|
||||||
|
var ackInChan chan *PacketAndToken // ACKs generated by ackFunc get put onto this channel
|
||||||
|
|
||||||
|
stopAckCopy := make(chan struct{}) // Closure requests stop of go routine copying ackInChan to ackOutChan
|
||||||
|
ackCopyStopped := make(chan struct{}) // Closure indicates that it is safe to close ackOutChan
|
||||||
|
goRoutinesDone := make(chan struct{}) // closed on wg.Done()
|
||||||
|
if order {
|
||||||
|
ackInChan = ackOutChan // When order = true no go routines are used so safe to use one channel and close when done
|
||||||
|
} else {
|
||||||
|
// When order = false ACK messages are sent in go routines so ackInChan cannot be closed until all goroutines done
|
||||||
|
ackInChan = make(chan *PacketAndToken)
|
||||||
|
go func() { // go routine to copy from ackInChan to ackOutChan until stopped
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case message := <-messages:
|
case a := <-ackInChan:
|
||||||
|
ackOutChan <- a
|
||||||
|
case <-stopAckCopy:
|
||||||
|
close(ackCopyStopped) // Signal main go routine that it is safe to close ackOutChan
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ackInChan: // drain ackInChan to ensure all goRoutines can complete cleanly (ACK dropped)
|
||||||
|
DEBUG.Println(ROU, "matchAndDispatch received acknowledgment after processing stopped (ACK dropped).")
|
||||||
|
case <-goRoutinesDone:
|
||||||
|
close(ackInChan) // Nothing further should be sent (a panic is probably better than silent failure)
|
||||||
|
DEBUG.Println(ROU, "matchAndDispatch order=false copy goroutine exiting.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() { // Main go routine handling inbound messages
|
||||||
|
for message := range messages {
|
||||||
|
// DEBUG.Println(ROU, "matchAndDispatch received message")
|
||||||
sent := false
|
sent := false
|
||||||
r.RLock()
|
r.RLock()
|
||||||
m := messageFromPublish(message, client.ackFunc(message))
|
m := messageFromPublish(message, ackFunc(ackInChan, client.persist, message))
|
||||||
handlers := []MessageHandler{}
|
var handlers []MessageHandler
|
||||||
for e := r.routes.Front(); e != nil; e = e.Next() {
|
for e := r.routes.Front(); e != nil; e = e.Next() {
|
||||||
if e.Value.(*route).match(message.TopicName) {
|
if e.Value.(*route).match(message.TopicName) {
|
||||||
if order {
|
if order {
|
||||||
handlers = append(handlers, e.Value.(*route).callback)
|
handlers = append(handlers, e.Value.(*route).callback)
|
||||||
} else {
|
} else {
|
||||||
hd := e.Value.(*route).callback
|
hd := e.Value.(*route).callback
|
||||||
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
hd(client, m)
|
hd(client, m)
|
||||||
m.Ack()
|
m.Ack()
|
||||||
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
sent = true
|
sent = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !sent && r.defaultHandler != nil {
|
if !sent {
|
||||||
|
if r.defaultHandler != nil {
|
||||||
if order {
|
if order {
|
||||||
handlers = append(handlers, r.defaultHandler)
|
handlers = append(handlers, r.defaultHandler)
|
||||||
} else {
|
} else {
|
||||||
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
r.defaultHandler(client, m)
|
r.defaultHandler(client, m)
|
||||||
m.Ack()
|
m.Ack()
|
||||||
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
DEBUG.Println(ROU, "matchAndDispatch received message and no handler was available. Message will NOT be acknowledged.")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
r.RUnlock()
|
r.RUnlock()
|
||||||
for _, handler := range handlers {
|
for _, handler := range handlers {
|
||||||
func() {
|
|
||||||
handler(client, m)
|
handler(client, m)
|
||||||
m.Ack()
|
m.Ack()
|
||||||
|
}
|
||||||
|
// DEBUG.Println(ROU, "matchAndDispatch handled message")
|
||||||
|
}
|
||||||
|
if order {
|
||||||
|
close(ackOutChan)
|
||||||
|
} else { // Ensure that nothing further will be written to ackOutChan before closing it
|
||||||
|
close(stopAckCopy)
|
||||||
|
<-ackCopyStopped
|
||||||
|
close(ackOutChan)
|
||||||
|
go func() {
|
||||||
|
wg.Wait() // Note: If this remains running then the user has handlers that are not returning
|
||||||
|
close(goRoutinesDone)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
case <-r.stop:
|
DEBUG.Println(ROU, "matchAndDispatch exiting")
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
}()
|
||||||
|
return ackOutChan
|
||||||
}
|
}
|
||||||
|
36
vendor/github.com/eclipse/paho.mqtt.golang/token.go
generated
vendored
36
vendor/github.com/eclipse/paho.mqtt.golang/token.go
generated
vendored
@ -31,8 +31,24 @@ type PacketAndToken struct {
|
|||||||
// Token defines the interface for the tokens used to indicate when
|
// Token defines the interface for the tokens used to indicate when
|
||||||
// actions have completed.
|
// actions have completed.
|
||||||
type Token interface {
|
type Token interface {
|
||||||
|
// Wait will wait indefinitely for the Token to complete, ie the Publish
|
||||||
|
// to be sent and confirmed receipt from the broker.
|
||||||
Wait() bool
|
Wait() bool
|
||||||
|
|
||||||
|
// WaitTimeout takes a time.Duration to wait for the flow associated with the
|
||||||
|
// Token to complete, returns true if it returned before the timeout or
|
||||||
|
// returns false if the timeout occurred. In the case of a timeout the Token
|
||||||
|
// does not have an error set in case the caller wishes to wait again.
|
||||||
WaitTimeout(time.Duration) bool
|
WaitTimeout(time.Duration) bool
|
||||||
|
|
||||||
|
// Done returns a channel that is closed when the flow associated
|
||||||
|
// with the Token completes. Clients should call Error after the
|
||||||
|
// channel is closed to check if the flow completed successfully.
|
||||||
|
//
|
||||||
|
// Done is provided for use in select statements. Simple use cases may
|
||||||
|
// use Wait or WaitTimeout.
|
||||||
|
Done() <-chan struct{}
|
||||||
|
|
||||||
Error() error
|
Error() error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,21 +68,14 @@ type baseToken struct {
|
|||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait will wait indefinitely for the Token to complete, ie the Publish
|
// Wait implements the Token Wait method.
|
||||||
// to be sent and confirmed receipt from the broker
|
|
||||||
func (b *baseToken) Wait() bool {
|
func (b *baseToken) Wait() bool {
|
||||||
<-b.complete
|
<-b.complete
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// WaitTimeout takes a time.Duration to wait for the flow associated with the
|
// WaitTimeout implements the Token WaitTimeout method.
|
||||||
// Token to complete, returns true if it returned before the timeout or
|
|
||||||
// returns false if the timeout occurred. In the case of a timeout the Token
|
|
||||||
// does not have an error set in case the caller wishes to wait again
|
|
||||||
func (b *baseToken) WaitTimeout(d time.Duration) bool {
|
func (b *baseToken) WaitTimeout(d time.Duration) bool {
|
||||||
b.m.Lock()
|
|
||||||
defer b.m.Unlock()
|
|
||||||
|
|
||||||
timer := time.NewTimer(d)
|
timer := time.NewTimer(d)
|
||||||
select {
|
select {
|
||||||
case <-b.complete:
|
case <-b.complete:
|
||||||
@ -80,6 +89,11 @@ func (b *baseToken) WaitTimeout(d time.Duration) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Done implements the Token Done method.
|
||||||
|
func (b *baseToken) Done() <-chan struct{} {
|
||||||
|
return b.complete
|
||||||
|
}
|
||||||
|
|
||||||
func (b *baseToken) flowComplete() {
|
func (b *baseToken) flowComplete() {
|
||||||
select {
|
select {
|
||||||
case <-b.complete:
|
case <-b.complete:
|
||||||
@ -125,7 +139,7 @@ type ConnectToken struct {
|
|||||||
sessionPresent bool
|
sessionPresent bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReturnCode returns the acknowlegement code in the connack sent
|
// ReturnCode returns the acknowledgement code in the connack sent
|
||||||
// in response to a Connect()
|
// in response to a Connect()
|
||||||
func (c *ConnectToken) ReturnCode() byte {
|
func (c *ConnectToken) ReturnCode() byte {
|
||||||
c.m.RLock()
|
c.m.RLock()
|
||||||
@ -160,6 +174,7 @@ type SubscribeToken struct {
|
|||||||
baseToken
|
baseToken
|
||||||
subs []string
|
subs []string
|
||||||
subResult map[string]byte
|
subResult map[string]byte
|
||||||
|
messageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
// Result returns a map of topics that were subscribed to along with
|
// Result returns a map of topics that were subscribed to along with
|
||||||
@ -175,6 +190,7 @@ func (s *SubscribeToken) Result() map[string]byte {
|
|||||||
// required to provide information about calls to Unsubscribe()
|
// required to provide information about calls to Unsubscribe()
|
||||||
type UnsubscribeToken struct {
|
type UnsubscribeToken struct {
|
||||||
baseToken
|
baseToken
|
||||||
|
messageID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
// DisconnectToken is an extension of Token containing the extra fields
|
// DisconnectToken is an extension of Token containing the extra fields
|
||||||
|
14
vendor/github.com/eclipse/paho.mqtt.golang/topic.go
generated
vendored
14
vendor/github.com/eclipse/paho.mqtt.golang/topic.go
generated
vendored
@ -21,16 +21,16 @@ import (
|
|||||||
|
|
||||||
// ErrInvalidQos is the error returned when an packet is to be sent
|
// ErrInvalidQos is the error returned when an packet is to be sent
|
||||||
// with an invalid Qos value
|
// with an invalid Qos value
|
||||||
var ErrInvalidQos = errors.New("Invalid QoS")
|
var ErrInvalidQos = errors.New("invalid QoS")
|
||||||
|
|
||||||
// ErrInvalidTopicEmptyString is the error returned when a topic string
|
// ErrInvalidTopicEmptyString is the error returned when a topic string
|
||||||
// is passed in that is 0 length
|
// is passed in that is 0 length
|
||||||
var ErrInvalidTopicEmptyString = errors.New("Invalid Topic; empty string")
|
var ErrInvalidTopicEmptyString = errors.New("invalid Topic; empty string")
|
||||||
|
|
||||||
// ErrInvalidTopicMultilevel is the error returned when a topic string
|
// ErrInvalidTopicMultilevel is the error returned when a topic string
|
||||||
// is passed in that has the multi level wildcard in any position but
|
// is passed in that has the multi level wildcard in any position but
|
||||||
// the last
|
// the last
|
||||||
var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard must be last level")
|
var ErrInvalidTopicMultilevel = errors.New("invalid Topic; multi-level wildcard must be last level")
|
||||||
|
|
||||||
// Topic Names and Topic Filters
|
// Topic Names and Topic Filters
|
||||||
// The MQTT v3.1.1 spec clarifies a number of ambiguities with regard
|
// The MQTT v3.1.1 spec clarifies a number of ambiguities with regard
|
||||||
@ -46,10 +46,14 @@ var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard
|
|||||||
// - A TopicName may not contain a wildcard.
|
// - A TopicName may not contain a wildcard.
|
||||||
// - A TopicFilter may only have a # (multi-level) wildcard as the last level.
|
// - A TopicFilter may only have a # (multi-level) wildcard as the last level.
|
||||||
// - A TopicFilter may contain any number of + (single-level) wildcards.
|
// - A TopicFilter may contain any number of + (single-level) wildcards.
|
||||||
// - A TopicFilter with a # will match the absense of a level
|
// - A TopicFilter with a # will match the absence of a level
|
||||||
// Example: a subscription to "foo/#" will match messages published to "foo".
|
// Example: a subscription to "foo/#" will match messages published to "foo".
|
||||||
|
|
||||||
func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error) {
|
func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error) {
|
||||||
|
if len(subs) == 0 {
|
||||||
|
return nil, nil, errors.New("invalid subscription; subscribe map must not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
var topics []string
|
var topics []string
|
||||||
var qoss []byte
|
var qoss []byte
|
||||||
for topic, qos := range subs {
|
for topic, qos := range subs {
|
||||||
@ -75,7 +79,7 @@ func validateTopicAndQos(topic string, qos byte) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if qos < 0 || qos > 2 {
|
if qos > 2 {
|
||||||
return ErrInvalidQos
|
return ErrInvalidQos
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
119
vendor/github.com/eclipse/paho.mqtt.golang/websocket.go
generated
vendored
Normal file
119
vendor/github.com/eclipse/paho.mqtt.golang/websocket.go
generated
vendored
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
package mqtt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WebsocketOptions are config options for a websocket dialer
|
||||||
|
type WebsocketOptions struct {
|
||||||
|
ReadBufferSize int
|
||||||
|
WriteBufferSize int
|
||||||
|
Proxy ProxyFunction
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyFunction func(req *http.Request) (*url.URL, error)
|
||||||
|
|
||||||
|
// NewWebsocket returns a new websocket and returns a net.Conn compatible interface using the gorilla/websocket package
|
||||||
|
func NewWebsocket(host string, tlsc *tls.Config, timeout time.Duration, requestHeader http.Header, options *WebsocketOptions) (net.Conn, error) {
|
||||||
|
if timeout == 0 {
|
||||||
|
timeout = 10 * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
if options == nil {
|
||||||
|
// Apply default options
|
||||||
|
options = &WebsocketOptions{}
|
||||||
|
}
|
||||||
|
if options.Proxy == nil {
|
||||||
|
options.Proxy = http.ProxyFromEnvironment
|
||||||
|
}
|
||||||
|
dialer := &websocket.Dialer{
|
||||||
|
Proxy: options.Proxy,
|
||||||
|
HandshakeTimeout: timeout,
|
||||||
|
EnableCompression: false,
|
||||||
|
TLSClientConfig: tlsc,
|
||||||
|
Subprotocols: []string{"mqtt"},
|
||||||
|
ReadBufferSize: options.ReadBufferSize,
|
||||||
|
WriteBufferSize: options.WriteBufferSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
ws, resp, err := dialer.Dial(host, requestHeader)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if resp != nil {
|
||||||
|
WARN.Println(CLI, fmt.Sprintf("Websocket handshake failure. StatusCode: %d. Body: %s", resp.StatusCode, resp.Body))
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &websocketConnector{
|
||||||
|
Conn: ws,
|
||||||
|
}
|
||||||
|
return wrapper, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// websocketConnector is a websocket wrapper so it satisfies the net.Conn interface so it is a
|
||||||
|
// drop in replacement of the golang.org/x/net/websocket package.
|
||||||
|
// Implementation guide taken from https://github.com/gorilla/websocket/issues/282
|
||||||
|
type websocketConnector struct {
|
||||||
|
*websocket.Conn
|
||||||
|
r io.Reader
|
||||||
|
rio sync.Mutex
|
||||||
|
wio sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDeadline sets both the read and write deadlines
|
||||||
|
func (c *websocketConnector) SetDeadline(t time.Time) error {
|
||||||
|
if err := c.SetReadDeadline(t); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err := c.SetWriteDeadline(t)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes data to the websocket
|
||||||
|
func (c *websocketConnector) Write(p []byte) (int, error) {
|
||||||
|
c.wio.Lock()
|
||||||
|
defer c.wio.Unlock()
|
||||||
|
|
||||||
|
err := c.WriteMessage(websocket.BinaryMessage, p)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read reads the current websocket frame
|
||||||
|
func (c *websocketConnector) Read(p []byte) (int, error) {
|
||||||
|
c.rio.Lock()
|
||||||
|
defer c.rio.Unlock()
|
||||||
|
for {
|
||||||
|
if c.r == nil {
|
||||||
|
// Advance to next message.
|
||||||
|
var err error
|
||||||
|
_, c.r, err = c.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n, err := c.r.Read(p)
|
||||||
|
if err == io.EOF {
|
||||||
|
// At end of message.
|
||||||
|
c.r = nil
|
||||||
|
if n > 0 {
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
// No data read, continue to next message.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
}
|
10
vendor/github.com/golang/protobuf/proto/registry.go
generated
vendored
10
vendor/github.com/golang/protobuf/proto/registry.go
generated
vendored
@ -13,6 +13,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"google.golang.org/protobuf/reflect/protodesc"
|
||||||
"google.golang.org/protobuf/reflect/protoreflect"
|
"google.golang.org/protobuf/reflect/protoreflect"
|
||||||
"google.golang.org/protobuf/reflect/protoregistry"
|
"google.golang.org/protobuf/reflect/protoregistry"
|
||||||
"google.golang.org/protobuf/runtime/protoimpl"
|
"google.golang.org/protobuf/runtime/protoimpl"
|
||||||
@ -62,14 +63,7 @@ func FileDescriptor(s filePath) fileDescGZIP {
|
|||||||
// Find the descriptor in the v2 registry.
|
// Find the descriptor in the v2 registry.
|
||||||
var b []byte
|
var b []byte
|
||||||
if fd, _ := protoregistry.GlobalFiles.FindFileByPath(s); fd != nil {
|
if fd, _ := protoregistry.GlobalFiles.FindFileByPath(s); fd != nil {
|
||||||
if fd, ok := fd.(interface{ ProtoLegacyRawDesc() []byte }); ok {
|
b, _ = Marshal(protodesc.ToFileDescriptorProto(fd))
|
||||||
b = fd.ProtoLegacyRawDesc()
|
|
||||||
} else {
|
|
||||||
// TODO: Use protodesc.ToFileDescriptorProto to construct
|
|
||||||
// a descriptorpb.FileDescriptorProto and marshal it.
|
|
||||||
// However, doing so causes the proto package to have a dependency
|
|
||||||
// on descriptorpb, leading to cyclic dependency issues.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Locally cache the raw descriptor form for the file.
|
// Locally cache the raw descriptor form for the file.
|
||||||
|
2
vendor/github.com/golang/protobuf/proto/text_decode.go
generated
vendored
2
vendor/github.com/golang/protobuf/proto/text_decode.go
generated
vendored
@ -765,7 +765,7 @@ func unescape(s string) (ch string, tail string, err error) {
|
|||||||
if i > utf8.MaxRune {
|
if i > utf8.MaxRune {
|
||||||
return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
|
return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
|
||||||
}
|
}
|
||||||
return string(i), s, nil
|
return string(rune(i)), s, nil
|
||||||
}
|
}
|
||||||
return "", "", fmt.Errorf(`unknown escape \%c`, r)
|
return "", "", fmt.Errorf(`unknown escape \%c`, r)
|
||||||
}
|
}
|
||||||
|
25
vendor/github.com/gorilla/websocket/.gitignore
generated
vendored
Normal file
25
vendor/github.com/gorilla/websocket/.gitignore
generated
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||||
|
*.o
|
||||||
|
*.a
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Folders
|
||||||
|
_obj
|
||||||
|
_test
|
||||||
|
|
||||||
|
# Architecture specific extensions/prefixes
|
||||||
|
*.[568vq]
|
||||||
|
[568vq].out
|
||||||
|
|
||||||
|
*.cgo1.go
|
||||||
|
*.cgo2.c
|
||||||
|
_cgo_defun.c
|
||||||
|
_cgo_gotypes.go
|
||||||
|
_cgo_export.*
|
||||||
|
|
||||||
|
_testmain.go
|
||||||
|
|
||||||
|
*.exe
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
*.iml
|
9
vendor/github.com/gorilla/websocket/AUTHORS
generated
vendored
Normal file
9
vendor/github.com/gorilla/websocket/AUTHORS
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# This is the official list of Gorilla WebSocket authors for copyright
|
||||||
|
# purposes.
|
||||||
|
#
|
||||||
|
# Please keep the list sorted.
|
||||||
|
|
||||||
|
Gary Burd <gary@beagledreams.com>
|
||||||
|
Google LLC (https://opensource.google.com/)
|
||||||
|
Joachim Bauch <mail@joachim-bauch.de>
|
||||||
|
|
22
vendor/github.com/gorilla/websocket/LICENSE
generated
vendored
Normal file
22
vendor/github.com/gorilla/websocket/LICENSE
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
64
vendor/github.com/gorilla/websocket/README.md
generated
vendored
Normal file
64
vendor/github.com/gorilla/websocket/README.md
generated
vendored
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
# Gorilla WebSocket
|
||||||
|
|
||||||
|
[](https://godoc.org/github.com/gorilla/websocket)
|
||||||
|
[](https://circleci.com/gh/gorilla/websocket)
|
||||||
|
|
||||||
|
Gorilla WebSocket is a [Go](http://golang.org/) implementation of the
|
||||||
|
[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol.
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
* [API Reference](https://pkg.go.dev/github.com/gorilla/websocket?tab=doc)
|
||||||
|
* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat)
|
||||||
|
* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command)
|
||||||
|
* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo)
|
||||||
|
* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch)
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
The Gorilla WebSocket package provides a complete and tested implementation of
|
||||||
|
the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The
|
||||||
|
package API is stable.
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
go get github.com/gorilla/websocket
|
||||||
|
|
||||||
|
### Protocol Compliance
|
||||||
|
|
||||||
|
The Gorilla WebSocket package passes the server tests in the [Autobahn Test
|
||||||
|
Suite](https://github.com/crossbario/autobahn-testsuite) using the application in the [examples/autobahn
|
||||||
|
subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn).
|
||||||
|
|
||||||
|
### Gorilla WebSocket compared with other packages
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th></th>
|
||||||
|
<th><a href="http://godoc.org/github.com/gorilla/websocket">github.com/gorilla</a></th>
|
||||||
|
<th><a href="http://godoc.org/golang.org/x/net/websocket">golang.org/x/net</a></th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<tr><td colspan="3"><a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a> Features</td></tr>
|
||||||
|
<tr><td>Passes <a href="https://github.com/crossbario/autobahn-testsuite">Autobahn Test Suite</a></td><td><a href="https://github.com/gorilla/websocket/tree/master/examples/autobahn">Yes</a></td><td>No</td></tr>
|
||||||
|
<tr><td>Receive <a href="https://tools.ietf.org/html/rfc6455#section-5.4">fragmented</a> message<td>Yes</td><td><a href="https://code.google.com/p/go/issues/detail?id=7632">No</a>, see note 1</td></tr>
|
||||||
|
<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">close</a> message</td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td><a href="https://code.google.com/p/go/issues/detail?id=4588">No</a></td></tr>
|
||||||
|
<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">pings</a> and receive <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pongs</a></td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td>No</td></tr>
|
||||||
|
<tr><td>Get the <a href="https://tools.ietf.org/html/rfc6455#section-5.6">type</a> of a received data message</td><td>Yes</td><td>Yes, see note 2</td></tr>
|
||||||
|
<tr><td colspan="3">Other Features</tr></td>
|
||||||
|
<tr><td><a href="https://tools.ietf.org/html/rfc7692">Compression Extensions</a></td><td>Experimental</td><td>No</td></tr>
|
||||||
|
<tr><td>Read message using io.Reader</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextReader">Yes</a></td><td>No, see note 3</td></tr>
|
||||||
|
<tr><td>Write message using io.WriteCloser</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextWriter">Yes</a></td><td>No, see note 3</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html).
|
||||||
|
2. The application can get the type of a received data message by implementing
|
||||||
|
a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal)
|
||||||
|
function.
|
||||||
|
3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries.
|
||||||
|
Read returns when the input buffer is full or a frame boundary is
|
||||||
|
encountered. Each call to Write sends a single frame message. The Gorilla
|
||||||
|
io.Reader and io.WriteCloser operate on a single WebSocket message.
|
||||||
|
|
395
vendor/github.com/gorilla/websocket/client.go
generated
vendored
Normal file
395
vendor/github.com/gorilla/websocket/client.go
generated
vendored
Normal file
@ -0,0 +1,395 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptrace"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrBadHandshake is returned when the server response to opening handshake is
|
||||||
|
// invalid.
|
||||||
|
var ErrBadHandshake = errors.New("websocket: bad handshake")
|
||||||
|
|
||||||
|
var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
|
||||||
|
|
||||||
|
// NewClient creates a new client connection using the given net connection.
|
||||||
|
// The URL u specifies the host and request URI. Use requestHeader to specify
|
||||||
|
// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
|
||||||
|
// (Cookie). Use the response.Header to get the selected subprotocol
|
||||||
|
// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
|
||||||
|
//
|
||||||
|
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
|
||||||
|
// non-nil *http.Response so that callers can handle redirects, authentication,
|
||||||
|
// etc.
|
||||||
|
//
|
||||||
|
// Deprecated: Use Dialer instead.
|
||||||
|
func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
|
||||||
|
d := Dialer{
|
||||||
|
ReadBufferSize: readBufSize,
|
||||||
|
WriteBufferSize: writeBufSize,
|
||||||
|
NetDial: func(net, addr string) (net.Conn, error) {
|
||||||
|
return netConn, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return d.Dial(u.String(), requestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Dialer contains options for connecting to WebSocket server.
|
||||||
|
type Dialer struct {
|
||||||
|
// NetDial specifies the dial function for creating TCP connections. If
|
||||||
|
// NetDial is nil, net.Dial is used.
|
||||||
|
NetDial func(network, addr string) (net.Conn, error)
|
||||||
|
|
||||||
|
// NetDialContext specifies the dial function for creating TCP connections. If
|
||||||
|
// NetDialContext is nil, net.DialContext is used.
|
||||||
|
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||||
|
|
||||||
|
// Proxy specifies a function to return a proxy for a given
|
||||||
|
// Request. If the function returns a non-nil error, the
|
||||||
|
// request is aborted with the provided error.
|
||||||
|
// If Proxy is nil or returns a nil *URL, no proxy is used.
|
||||||
|
Proxy func(*http.Request) (*url.URL, error)
|
||||||
|
|
||||||
|
// TLSClientConfig specifies the TLS configuration to use with tls.Client.
|
||||||
|
// If nil, the default configuration is used.
|
||||||
|
TLSClientConfig *tls.Config
|
||||||
|
|
||||||
|
// HandshakeTimeout specifies the duration for the handshake to complete.
|
||||||
|
HandshakeTimeout time.Duration
|
||||||
|
|
||||||
|
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
|
||||||
|
// size is zero, then a useful default size is used. The I/O buffer sizes
|
||||||
|
// do not limit the size of the messages that can be sent or received.
|
||||||
|
ReadBufferSize, WriteBufferSize int
|
||||||
|
|
||||||
|
// WriteBufferPool is a pool of buffers for write operations. If the value
|
||||||
|
// is not set, then write buffers are allocated to the connection for the
|
||||||
|
// lifetime of the connection.
|
||||||
|
//
|
||||||
|
// A pool is most useful when the application has a modest volume of writes
|
||||||
|
// across a large number of connections.
|
||||||
|
//
|
||||||
|
// Applications should use a single pool for each unique value of
|
||||||
|
// WriteBufferSize.
|
||||||
|
WriteBufferPool BufferPool
|
||||||
|
|
||||||
|
// Subprotocols specifies the client's requested subprotocols.
|
||||||
|
Subprotocols []string
|
||||||
|
|
||||||
|
// EnableCompression specifies if the client should attempt to negotiate
|
||||||
|
// per message compression (RFC 7692). Setting this value to true does not
|
||||||
|
// guarantee that compression will be supported. Currently only "no context
|
||||||
|
// takeover" modes are supported.
|
||||||
|
EnableCompression bool
|
||||||
|
|
||||||
|
// Jar specifies the cookie jar.
|
||||||
|
// If Jar is nil, cookies are not sent in requests and ignored
|
||||||
|
// in responses.
|
||||||
|
Jar http.CookieJar
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial creates a new client connection by calling DialContext with a background context.
|
||||||
|
func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
|
||||||
|
return d.DialContext(context.Background(), urlStr, requestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
var errMalformedURL = errors.New("malformed ws or wss URL")
|
||||||
|
|
||||||
|
func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
|
||||||
|
hostPort = u.Host
|
||||||
|
hostNoPort = u.Host
|
||||||
|
if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
|
||||||
|
hostNoPort = hostNoPort[:i]
|
||||||
|
} else {
|
||||||
|
switch u.Scheme {
|
||||||
|
case "wss":
|
||||||
|
hostPort += ":443"
|
||||||
|
case "https":
|
||||||
|
hostPort += ":443"
|
||||||
|
default:
|
||||||
|
hostPort += ":80"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hostPort, hostNoPort
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultDialer is a dialer with all fields set to the default values.
|
||||||
|
var DefaultDialer = &Dialer{
|
||||||
|
Proxy: http.ProxyFromEnvironment,
|
||||||
|
HandshakeTimeout: 45 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
// nilDialer is dialer to use when receiver is nil.
|
||||||
|
var nilDialer = *DefaultDialer
|
||||||
|
|
||||||
|
// DialContext creates a new client connection. Use requestHeader to specify the
|
||||||
|
// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
|
||||||
|
// Use the response.Header to get the selected subprotocol
|
||||||
|
// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
|
||||||
|
//
|
||||||
|
// The context will be used in the request and in the Dialer.
|
||||||
|
//
|
||||||
|
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
|
||||||
|
// non-nil *http.Response so that callers can handle redirects, authentication,
|
||||||
|
// etcetera. The response body may not contain the entire response and does not
|
||||||
|
// need to be closed by the application.
|
||||||
|
func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
|
||||||
|
if d == nil {
|
||||||
|
d = &nilDialer
|
||||||
|
}
|
||||||
|
|
||||||
|
challengeKey, err := generateChallengeKey()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err := url.Parse(urlStr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch u.Scheme {
|
||||||
|
case "ws":
|
||||||
|
u.Scheme = "http"
|
||||||
|
case "wss":
|
||||||
|
u.Scheme = "https"
|
||||||
|
default:
|
||||||
|
return nil, nil, errMalformedURL
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.User != nil {
|
||||||
|
// User name and password are not allowed in websocket URIs.
|
||||||
|
return nil, nil, errMalformedURL
|
||||||
|
}
|
||||||
|
|
||||||
|
req := &http.Request{
|
||||||
|
Method: "GET",
|
||||||
|
URL: u,
|
||||||
|
Proto: "HTTP/1.1",
|
||||||
|
ProtoMajor: 1,
|
||||||
|
ProtoMinor: 1,
|
||||||
|
Header: make(http.Header),
|
||||||
|
Host: u.Host,
|
||||||
|
}
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
// Set the cookies present in the cookie jar of the dialer
|
||||||
|
if d.Jar != nil {
|
||||||
|
for _, cookie := range d.Jar.Cookies(u) {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the request headers using the capitalization for names and values in
|
||||||
|
// RFC examples. Although the capitalization shouldn't matter, there are
|
||||||
|
// servers that depend on it. The Header.Set method is not used because the
|
||||||
|
// method canonicalizes the header names.
|
||||||
|
req.Header["Upgrade"] = []string{"websocket"}
|
||||||
|
req.Header["Connection"] = []string{"Upgrade"}
|
||||||
|
req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
|
||||||
|
req.Header["Sec-WebSocket-Version"] = []string{"13"}
|
||||||
|
if len(d.Subprotocols) > 0 {
|
||||||
|
req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
|
||||||
|
}
|
||||||
|
for k, vs := range requestHeader {
|
||||||
|
switch {
|
||||||
|
case k == "Host":
|
||||||
|
if len(vs) > 0 {
|
||||||
|
req.Host = vs[0]
|
||||||
|
}
|
||||||
|
case k == "Upgrade" ||
|
||||||
|
k == "Connection" ||
|
||||||
|
k == "Sec-Websocket-Key" ||
|
||||||
|
k == "Sec-Websocket-Version" ||
|
||||||
|
k == "Sec-Websocket-Extensions" ||
|
||||||
|
(k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
|
||||||
|
return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
|
||||||
|
case k == "Sec-Websocket-Protocol":
|
||||||
|
req.Header["Sec-WebSocket-Protocol"] = vs
|
||||||
|
default:
|
||||||
|
req.Header[k] = vs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.EnableCompression {
|
||||||
|
req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.HandshakeTimeout != 0 {
|
||||||
|
var cancel func()
|
||||||
|
ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout)
|
||||||
|
defer cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get network dial function.
|
||||||
|
var netDial func(network, add string) (net.Conn, error)
|
||||||
|
|
||||||
|
if d.NetDialContext != nil {
|
||||||
|
netDial = func(network, addr string) (net.Conn, error) {
|
||||||
|
return d.NetDialContext(ctx, network, addr)
|
||||||
|
}
|
||||||
|
} else if d.NetDial != nil {
|
||||||
|
netDial = d.NetDial
|
||||||
|
} else {
|
||||||
|
netDialer := &net.Dialer{}
|
||||||
|
netDial = func(network, addr string) (net.Conn, error) {
|
||||||
|
return netDialer.DialContext(ctx, network, addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If needed, wrap the dial function to set the connection deadline.
|
||||||
|
if deadline, ok := ctx.Deadline(); ok {
|
||||||
|
forwardDial := netDial
|
||||||
|
netDial = func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := forwardDial(network, addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = c.SetDeadline(deadline)
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If needed, wrap the dial function to connect through a proxy.
|
||||||
|
if d.Proxy != nil {
|
||||||
|
proxyURL, err := d.Proxy(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if proxyURL != nil {
|
||||||
|
dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
netDial = dialer.Dial
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hostPort, hostNoPort := hostPortNoPort(u)
|
||||||
|
trace := httptrace.ContextClientTrace(ctx)
|
||||||
|
if trace != nil && trace.GetConn != nil {
|
||||||
|
trace.GetConn(hostPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
netConn, err := netDial("tcp", hostPort)
|
||||||
|
if trace != nil && trace.GotConn != nil {
|
||||||
|
trace.GotConn(httptrace.GotConnInfo{
|
||||||
|
Conn: netConn,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if netConn != nil {
|
||||||
|
netConn.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if u.Scheme == "https" {
|
||||||
|
cfg := cloneTLSConfig(d.TLSClientConfig)
|
||||||
|
if cfg.ServerName == "" {
|
||||||
|
cfg.ServerName = hostNoPort
|
||||||
|
}
|
||||||
|
tlsConn := tls.Client(netConn, cfg)
|
||||||
|
netConn = tlsConn
|
||||||
|
|
||||||
|
var err error
|
||||||
|
if trace != nil {
|
||||||
|
err = doHandshakeWithTrace(trace, tlsConn, cfg)
|
||||||
|
} else {
|
||||||
|
err = doHandshake(tlsConn, cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil)
|
||||||
|
|
||||||
|
if err := req.Write(netConn); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if trace != nil && trace.GotFirstResponseByte != nil {
|
||||||
|
if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 {
|
||||||
|
trace.GotFirstResponseByte()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.ReadResponse(conn.br, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.Jar != nil {
|
||||||
|
if rc := resp.Cookies(); len(rc) > 0 {
|
||||||
|
d.Jar.SetCookies(u, rc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 101 ||
|
||||||
|
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
|
||||||
|
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
|
||||||
|
resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
|
||||||
|
// Before closing the network connection on return from this
|
||||||
|
// function, slurp up some of the response to aid application
|
||||||
|
// debugging.
|
||||||
|
buf := make([]byte, 1024)
|
||||||
|
n, _ := io.ReadFull(resp.Body, buf)
|
||||||
|
resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
|
||||||
|
return nil, resp, ErrBadHandshake
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ext := range parseExtensions(resp.Header) {
|
||||||
|
if ext[""] != "permessage-deflate" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, snct := ext["server_no_context_takeover"]
|
||||||
|
_, cnct := ext["client_no_context_takeover"]
|
||||||
|
if !snct || !cnct {
|
||||||
|
return nil, resp, errInvalidCompression
|
||||||
|
}
|
||||||
|
conn.newCompressionWriter = compressNoContextTakeover
|
||||||
|
conn.newDecompressionReader = decompressNoContextTakeover
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
||||||
|
conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
|
||||||
|
|
||||||
|
netConn.SetDeadline(time.Time{})
|
||||||
|
netConn = nil // to avoid close in defer.
|
||||||
|
return conn, resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func doHandshake(tlsConn *tls.Conn, cfg *tls.Config) error {
|
||||||
|
if err := tlsConn.Handshake(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !cfg.InsecureSkipVerify {
|
||||||
|
if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
16
vendor/github.com/gorilla/websocket/client_clone.go
generated
vendored
Normal file
16
vendor/github.com/gorilla/websocket/client_clone.go
generated
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "crypto/tls"
|
||||||
|
|
||||||
|
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||||
|
if cfg == nil {
|
||||||
|
return &tls.Config{}
|
||||||
|
}
|
||||||
|
return cfg.Clone()
|
||||||
|
}
|
38
vendor/github.com/gorilla/websocket/client_clone_legacy.go
generated
vendored
Normal file
38
vendor/github.com/gorilla/websocket/client_clone_legacy.go
generated
vendored
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build !go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "crypto/tls"
|
||||||
|
|
||||||
|
// cloneTLSConfig clones all public fields except the fields
|
||||||
|
// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
|
||||||
|
// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
|
||||||
|
// config in active use.
|
||||||
|
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||||
|
if cfg == nil {
|
||||||
|
return &tls.Config{}
|
||||||
|
}
|
||||||
|
return &tls.Config{
|
||||||
|
Rand: cfg.Rand,
|
||||||
|
Time: cfg.Time,
|
||||||
|
Certificates: cfg.Certificates,
|
||||||
|
NameToCertificate: cfg.NameToCertificate,
|
||||||
|
GetCertificate: cfg.GetCertificate,
|
||||||
|
RootCAs: cfg.RootCAs,
|
||||||
|
NextProtos: cfg.NextProtos,
|
||||||
|
ServerName: cfg.ServerName,
|
||||||
|
ClientAuth: cfg.ClientAuth,
|
||||||
|
ClientCAs: cfg.ClientCAs,
|
||||||
|
InsecureSkipVerify: cfg.InsecureSkipVerify,
|
||||||
|
CipherSuites: cfg.CipherSuites,
|
||||||
|
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
|
||||||
|
ClientSessionCache: cfg.ClientSessionCache,
|
||||||
|
MinVersion: cfg.MinVersion,
|
||||||
|
MaxVersion: cfg.MaxVersion,
|
||||||
|
CurvePreferences: cfg.CurvePreferences,
|
||||||
|
}
|
||||||
|
}
|
148
vendor/github.com/gorilla/websocket/compression.go
generated
vendored
Normal file
148
vendor/github.com/gorilla/websocket/compression.go
generated
vendored
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"compress/flate"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
|
||||||
|
maxCompressionLevel = flate.BestCompression
|
||||||
|
defaultCompressionLevel = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
|
||||||
|
flateReaderPool = sync.Pool{New: func() interface{} {
|
||||||
|
return flate.NewReader(nil)
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
|
||||||
|
const tail =
|
||||||
|
// Add four bytes as specified in RFC
|
||||||
|
"\x00\x00\xff\xff" +
|
||||||
|
// Add final block to squelch unexpected EOF error from flate reader.
|
||||||
|
"\x01\x00\x00\xff\xff"
|
||||||
|
|
||||||
|
fr, _ := flateReaderPool.Get().(io.ReadCloser)
|
||||||
|
fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
|
||||||
|
return &flateReadWrapper{fr}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidCompressionLevel(level int) bool {
|
||||||
|
return minCompressionLevel <= level && level <= maxCompressionLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
|
||||||
|
p := &flateWriterPools[level-minCompressionLevel]
|
||||||
|
tw := &truncWriter{w: w}
|
||||||
|
fw, _ := p.Get().(*flate.Writer)
|
||||||
|
if fw == nil {
|
||||||
|
fw, _ = flate.NewWriter(tw, level)
|
||||||
|
} else {
|
||||||
|
fw.Reset(tw)
|
||||||
|
}
|
||||||
|
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncWriter is an io.Writer that writes all but the last four bytes of the
|
||||||
|
// stream to another io.Writer.
|
||||||
|
type truncWriter struct {
|
||||||
|
w io.WriteCloser
|
||||||
|
n int
|
||||||
|
p [4]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *truncWriter) Write(p []byte) (int, error) {
|
||||||
|
n := 0
|
||||||
|
|
||||||
|
// fill buffer first for simplicity.
|
||||||
|
if w.n < len(w.p) {
|
||||||
|
n = copy(w.p[w.n:], p)
|
||||||
|
p = p[n:]
|
||||||
|
w.n += n
|
||||||
|
if len(p) == 0 {
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
m := len(p)
|
||||||
|
if m > len(w.p) {
|
||||||
|
m = len(w.p)
|
||||||
|
}
|
||||||
|
|
||||||
|
if nn, err := w.w.Write(w.p[:m]); err != nil {
|
||||||
|
return n + nn, err
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(w.p[:], w.p[m:])
|
||||||
|
copy(w.p[len(w.p)-m:], p[len(p)-m:])
|
||||||
|
nn, err := w.w.Write(p[:len(p)-m])
|
||||||
|
return n + nn, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type flateWriteWrapper struct {
|
||||||
|
fw *flate.Writer
|
||||||
|
tw *truncWriter
|
||||||
|
p *sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *flateWriteWrapper) Write(p []byte) (int, error) {
|
||||||
|
if w.fw == nil {
|
||||||
|
return 0, errWriteClosed
|
||||||
|
}
|
||||||
|
return w.fw.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *flateWriteWrapper) Close() error {
|
||||||
|
if w.fw == nil {
|
||||||
|
return errWriteClosed
|
||||||
|
}
|
||||||
|
err1 := w.fw.Flush()
|
||||||
|
w.p.Put(w.fw)
|
||||||
|
w.fw = nil
|
||||||
|
if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
|
||||||
|
return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
|
||||||
|
}
|
||||||
|
err2 := w.tw.w.Close()
|
||||||
|
if err1 != nil {
|
||||||
|
return err1
|
||||||
|
}
|
||||||
|
return err2
|
||||||
|
}
|
||||||
|
|
||||||
|
type flateReadWrapper struct {
|
||||||
|
fr io.ReadCloser
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *flateReadWrapper) Read(p []byte) (int, error) {
|
||||||
|
if r.fr == nil {
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
n, err := r.fr.Read(p)
|
||||||
|
if err == io.EOF {
|
||||||
|
// Preemptively place the reader back in the pool. This helps with
|
||||||
|
// scenarios where the application does not call NextReader() soon after
|
||||||
|
// this final read.
|
||||||
|
r.Close()
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *flateReadWrapper) Close() error {
|
||||||
|
if r.fr == nil {
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
err := r.fr.Close()
|
||||||
|
flateReaderPool.Put(r.fr)
|
||||||
|
r.fr = nil
|
||||||
|
return err
|
||||||
|
}
|
1201
vendor/github.com/gorilla/websocket/conn.go
generated
vendored
Normal file
1201
vendor/github.com/gorilla/websocket/conn.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
15
vendor/github.com/gorilla/websocket/conn_write.go
generated
vendored
Normal file
15
vendor/github.com/gorilla/websocket/conn_write.go
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
func (c *Conn) writeBufs(bufs ...[]byte) error {
|
||||||
|
b := net.Buffers(bufs)
|
||||||
|
_, err := b.WriteTo(c.conn)
|
||||||
|
return err
|
||||||
|
}
|
18
vendor/github.com/gorilla/websocket/conn_write_legacy.go
generated
vendored
Normal file
18
vendor/github.com/gorilla/websocket/conn_write_legacy.go
generated
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build !go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
func (c *Conn) writeBufs(bufs ...[]byte) error {
|
||||||
|
for _, buf := range bufs {
|
||||||
|
if len(buf) > 0 {
|
||||||
|
if _, err := c.conn.Write(buf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
227
vendor/github.com/gorilla/websocket/doc.go
generated
vendored
Normal file
227
vendor/github.com/gorilla/websocket/doc.go
generated
vendored
Normal file
@ -0,0 +1,227 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Package websocket implements the WebSocket protocol defined in RFC 6455.
|
||||||
|
//
|
||||||
|
// Overview
|
||||||
|
//
|
||||||
|
// The Conn type represents a WebSocket connection. A server application calls
|
||||||
|
// the Upgrader.Upgrade method from an HTTP request handler to get a *Conn:
|
||||||
|
//
|
||||||
|
// var upgrader = websocket.Upgrader{
|
||||||
|
// ReadBufferSize: 1024,
|
||||||
|
// WriteBufferSize: 1024,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// conn, err := upgrader.Upgrade(w, r, nil)
|
||||||
|
// if err != nil {
|
||||||
|
// log.Println(err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// ... Use conn to send and receive messages.
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Call the connection's WriteMessage and ReadMessage methods to send and
|
||||||
|
// receive messages as a slice of bytes. This snippet of code shows how to echo
|
||||||
|
// messages using these methods:
|
||||||
|
//
|
||||||
|
// for {
|
||||||
|
// messageType, p, err := conn.ReadMessage()
|
||||||
|
// if err != nil {
|
||||||
|
// log.Println(err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// if err := conn.WriteMessage(messageType, p); err != nil {
|
||||||
|
// log.Println(err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// In above snippet of code, p is a []byte and messageType is an int with value
|
||||||
|
// websocket.BinaryMessage or websocket.TextMessage.
|
||||||
|
//
|
||||||
|
// An application can also send and receive messages using the io.WriteCloser
|
||||||
|
// and io.Reader interfaces. To send a message, call the connection NextWriter
|
||||||
|
// method to get an io.WriteCloser, write the message to the writer and close
|
||||||
|
// the writer when done. To receive a message, call the connection NextReader
|
||||||
|
// method to get an io.Reader and read until io.EOF is returned. This snippet
|
||||||
|
// shows how to echo messages using the NextWriter and NextReader methods:
|
||||||
|
//
|
||||||
|
// for {
|
||||||
|
// messageType, r, err := conn.NextReader()
|
||||||
|
// if err != nil {
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// w, err := conn.NextWriter(messageType)
|
||||||
|
// if err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// if _, err := io.Copy(w, r); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// if err := w.Close(); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Data Messages
|
||||||
|
//
|
||||||
|
// The WebSocket protocol distinguishes between text and binary data messages.
|
||||||
|
// Text messages are interpreted as UTF-8 encoded text. The interpretation of
|
||||||
|
// binary messages is left to the application.
|
||||||
|
//
|
||||||
|
// This package uses the TextMessage and BinaryMessage integer constants to
|
||||||
|
// identify the two data message types. The ReadMessage and NextReader methods
|
||||||
|
// return the type of the received message. The messageType argument to the
|
||||||
|
// WriteMessage and NextWriter methods specifies the type of a sent message.
|
||||||
|
//
|
||||||
|
// It is the application's responsibility to ensure that text messages are
|
||||||
|
// valid UTF-8 encoded text.
|
||||||
|
//
|
||||||
|
// Control Messages
|
||||||
|
//
|
||||||
|
// The WebSocket protocol defines three types of control messages: close, ping
|
||||||
|
// and pong. Call the connection WriteControl, WriteMessage or NextWriter
|
||||||
|
// methods to send a control message to the peer.
|
||||||
|
//
|
||||||
|
// Connections handle received close messages by calling the handler function
|
||||||
|
// set with the SetCloseHandler method and by returning a *CloseError from the
|
||||||
|
// NextReader, ReadMessage or the message Read method. The default close
|
||||||
|
// handler sends a close message to the peer.
|
||||||
|
//
|
||||||
|
// Connections handle received ping messages by calling the handler function
|
||||||
|
// set with the SetPingHandler method. The default ping handler sends a pong
|
||||||
|
// message to the peer.
|
||||||
|
//
|
||||||
|
// Connections handle received pong messages by calling the handler function
|
||||||
|
// set with the SetPongHandler method. The default pong handler does nothing.
|
||||||
|
// If an application sends ping messages, then the application should set a
|
||||||
|
// pong handler to receive the corresponding pong.
|
||||||
|
//
|
||||||
|
// The control message handler functions are called from the NextReader,
|
||||||
|
// ReadMessage and message reader Read methods. The default close and ping
|
||||||
|
// handlers can block these methods for a short time when the handler writes to
|
||||||
|
// the connection.
|
||||||
|
//
|
||||||
|
// The application must read the connection to process close, ping and pong
|
||||||
|
// messages sent from the peer. If the application is not otherwise interested
|
||||||
|
// in messages from the peer, then the application should start a goroutine to
|
||||||
|
// read and discard messages from the peer. A simple example is:
|
||||||
|
//
|
||||||
|
// func readLoop(c *websocket.Conn) {
|
||||||
|
// for {
|
||||||
|
// if _, _, err := c.NextReader(); err != nil {
|
||||||
|
// c.Close()
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Concurrency
|
||||||
|
//
|
||||||
|
// Connections support one concurrent reader and one concurrent writer.
|
||||||
|
//
|
||||||
|
// Applications are responsible for ensuring that no more than one goroutine
|
||||||
|
// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
|
||||||
|
// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and
|
||||||
|
// that no more than one goroutine calls the read methods (NextReader,
|
||||||
|
// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler)
|
||||||
|
// concurrently.
|
||||||
|
//
|
||||||
|
// The Close and WriteControl methods can be called concurrently with all other
|
||||||
|
// methods.
|
||||||
|
//
|
||||||
|
// Origin Considerations
|
||||||
|
//
|
||||||
|
// Web browsers allow Javascript applications to open a WebSocket connection to
|
||||||
|
// any host. It's up to the server to enforce an origin policy using the Origin
|
||||||
|
// request header sent by the browser.
|
||||||
|
//
|
||||||
|
// The Upgrader calls the function specified in the CheckOrigin field to check
|
||||||
|
// the origin. If the CheckOrigin function returns false, then the Upgrade
|
||||||
|
// method fails the WebSocket handshake with HTTP status 403.
|
||||||
|
//
|
||||||
|
// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail
|
||||||
|
// the handshake if the Origin request header is present and the Origin host is
|
||||||
|
// not equal to the Host request header.
|
||||||
|
//
|
||||||
|
// The deprecated package-level Upgrade function does not perform origin
|
||||||
|
// checking. The application is responsible for checking the Origin header
|
||||||
|
// before calling the Upgrade function.
|
||||||
|
//
|
||||||
|
// Buffers
|
||||||
|
//
|
||||||
|
// Connections buffer network input and output to reduce the number
|
||||||
|
// of system calls when reading or writing messages.
|
||||||
|
//
|
||||||
|
// Write buffers are also used for constructing WebSocket frames. See RFC 6455,
|
||||||
|
// Section 5 for a discussion of message framing. A WebSocket frame header is
|
||||||
|
// written to the network each time a write buffer is flushed to the network.
|
||||||
|
// Decreasing the size of the write buffer can increase the amount of framing
|
||||||
|
// overhead on the connection.
|
||||||
|
//
|
||||||
|
// The buffer sizes in bytes are specified by the ReadBufferSize and
|
||||||
|
// WriteBufferSize fields in the Dialer and Upgrader. The Dialer uses a default
|
||||||
|
// size of 4096 when a buffer size field is set to zero. The Upgrader reuses
|
||||||
|
// buffers created by the HTTP server when a buffer size field is set to zero.
|
||||||
|
// The HTTP server buffers have a size of 4096 at the time of this writing.
|
||||||
|
//
|
||||||
|
// The buffer sizes do not limit the size of a message that can be read or
|
||||||
|
// written by a connection.
|
||||||
|
//
|
||||||
|
// Buffers are held for the lifetime of the connection by default. If the
|
||||||
|
// Dialer or Upgrader WriteBufferPool field is set, then a connection holds the
|
||||||
|
// write buffer only when writing a message.
|
||||||
|
//
|
||||||
|
// Applications should tune the buffer sizes to balance memory use and
|
||||||
|
// performance. Increasing the buffer size uses more memory, but can reduce the
|
||||||
|
// number of system calls to read or write the network. In the case of writing,
|
||||||
|
// increasing the buffer size can reduce the number of frame headers written to
|
||||||
|
// the network.
|
||||||
|
//
|
||||||
|
// Some guidelines for setting buffer parameters are:
|
||||||
|
//
|
||||||
|
// Limit the buffer sizes to the maximum expected message size. Buffers larger
|
||||||
|
// than the largest message do not provide any benefit.
|
||||||
|
//
|
||||||
|
// Depending on the distribution of message sizes, setting the buffer size to
|
||||||
|
// a value less than the maximum expected message size can greatly reduce memory
|
||||||
|
// use with a small impact on performance. Here's an example: If 99% of the
|
||||||
|
// messages are smaller than 256 bytes and the maximum message size is 512
|
||||||
|
// bytes, then a buffer size of 256 bytes will result in 1.01 more system calls
|
||||||
|
// than a buffer size of 512 bytes. The memory savings is 50%.
|
||||||
|
//
|
||||||
|
// A write buffer pool is useful when the application has a modest number
|
||||||
|
// writes over a large number of connections. when buffers are pooled, a larger
|
||||||
|
// buffer size has a reduced impact on total memory use and has the benefit of
|
||||||
|
// reducing system calls and frame overhead.
|
||||||
|
//
|
||||||
|
// Compression EXPERIMENTAL
|
||||||
|
//
|
||||||
|
// Per message compression extensions (RFC 7692) are experimentally supported
|
||||||
|
// by this package in a limited capacity. Setting the EnableCompression option
|
||||||
|
// to true in Dialer or Upgrader will attempt to negotiate per message deflate
|
||||||
|
// support.
|
||||||
|
//
|
||||||
|
// var upgrader = websocket.Upgrader{
|
||||||
|
// EnableCompression: true,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// If compression was successfully negotiated with the connection's peer, any
|
||||||
|
// message received in compressed form will be automatically decompressed.
|
||||||
|
// All Read methods will return uncompressed bytes.
|
||||||
|
//
|
||||||
|
// Per message compression of messages written to a connection can be enabled
|
||||||
|
// or disabled by calling the corresponding Conn method:
|
||||||
|
//
|
||||||
|
// conn.EnableWriteCompression(false)
|
||||||
|
//
|
||||||
|
// Currently this package does not support compression with "context takeover".
|
||||||
|
// This means that messages must be compressed and decompressed in isolation,
|
||||||
|
// without retaining sliding window or dictionary state across messages. For
|
||||||
|
// more details refer to RFC 7692.
|
||||||
|
//
|
||||||
|
// Use of compression is experimental and may result in decreased performance.
|
||||||
|
package websocket
|
42
vendor/github.com/gorilla/websocket/join.go
generated
vendored
Normal file
42
vendor/github.com/gorilla/websocket/join.go
generated
vendored
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
// Copyright 2019 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// JoinMessages concatenates received messages to create a single io.Reader.
|
||||||
|
// The string term is appended to each message. The returned reader does not
|
||||||
|
// support concurrent calls to the Read method.
|
||||||
|
func JoinMessages(c *Conn, term string) io.Reader {
|
||||||
|
return &joinReader{c: c, term: term}
|
||||||
|
}
|
||||||
|
|
||||||
|
type joinReader struct {
|
||||||
|
c *Conn
|
||||||
|
term string
|
||||||
|
r io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *joinReader) Read(p []byte) (int, error) {
|
||||||
|
if r.r == nil {
|
||||||
|
var err error
|
||||||
|
_, r.r, err = r.c.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if r.term != "" {
|
||||||
|
r.r = io.MultiReader(r.r, strings.NewReader(r.term))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n, err := r.r.Read(p)
|
||||||
|
if err == io.EOF {
|
||||||
|
err = nil
|
||||||
|
r.r = nil
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
60
vendor/github.com/gorilla/websocket/json.go
generated
vendored
Normal file
60
vendor/github.com/gorilla/websocket/json.go
generated
vendored
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WriteJSON writes the JSON encoding of v as a message.
|
||||||
|
//
|
||||||
|
// Deprecated: Use c.WriteJSON instead.
|
||||||
|
func WriteJSON(c *Conn, v interface{}) error {
|
||||||
|
return c.WriteJSON(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteJSON writes the JSON encoding of v as a message.
|
||||||
|
//
|
||||||
|
// See the documentation for encoding/json Marshal for details about the
|
||||||
|
// conversion of Go values to JSON.
|
||||||
|
func (c *Conn) WriteJSON(v interface{}) error {
|
||||||
|
w, err := c.NextWriter(TextMessage)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err1 := json.NewEncoder(w).Encode(v)
|
||||||
|
err2 := w.Close()
|
||||||
|
if err1 != nil {
|
||||||
|
return err1
|
||||||
|
}
|
||||||
|
return err2
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadJSON reads the next JSON-encoded message from the connection and stores
|
||||||
|
// it in the value pointed to by v.
|
||||||
|
//
|
||||||
|
// Deprecated: Use c.ReadJSON instead.
|
||||||
|
func ReadJSON(c *Conn, v interface{}) error {
|
||||||
|
return c.ReadJSON(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadJSON reads the next JSON-encoded message from the connection and stores
|
||||||
|
// it in the value pointed to by v.
|
||||||
|
//
|
||||||
|
// See the documentation for the encoding/json Unmarshal function for details
|
||||||
|
// about the conversion of JSON to a Go value.
|
||||||
|
func (c *Conn) ReadJSON(v interface{}) error {
|
||||||
|
_, r, err := c.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = json.NewDecoder(r).Decode(v)
|
||||||
|
if err == io.EOF {
|
||||||
|
// One value is expected in the message.
|
||||||
|
err = io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
54
vendor/github.com/gorilla/websocket/mask.go
generated
vendored
Normal file
54
vendor/github.com/gorilla/websocket/mask.go
generated
vendored
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
|
||||||
|
// this source code is governed by a BSD-style license that can be found in the
|
||||||
|
// LICENSE file.
|
||||||
|
|
||||||
|
// +build !appengine
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "unsafe"
|
||||||
|
|
||||||
|
const wordSize = int(unsafe.Sizeof(uintptr(0)))
|
||||||
|
|
||||||
|
func maskBytes(key [4]byte, pos int, b []byte) int {
|
||||||
|
// Mask one byte at a time for small buffers.
|
||||||
|
if len(b) < 2*wordSize {
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
return pos & 3
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mask one byte at a time to word boundary.
|
||||||
|
if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
|
||||||
|
n = wordSize - n
|
||||||
|
for i := range b[:n] {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
b = b[n:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create aligned word size key.
|
||||||
|
var k [wordSize]byte
|
||||||
|
for i := range k {
|
||||||
|
k[i] = key[(pos+i)&3]
|
||||||
|
}
|
||||||
|
kw := *(*uintptr)(unsafe.Pointer(&k))
|
||||||
|
|
||||||
|
// Mask one word at a time.
|
||||||
|
n := (len(b) / wordSize) * wordSize
|
||||||
|
for i := 0; i < n; i += wordSize {
|
||||||
|
*(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mask one byte at a time for remaining bytes.
|
||||||
|
b = b[n:]
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
|
||||||
|
return pos & 3
|
||||||
|
}
|
15
vendor/github.com/gorilla/websocket/mask_safe.go
generated
vendored
Normal file
15
vendor/github.com/gorilla/websocket/mask_safe.go
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
|
||||||
|
// this source code is governed by a BSD-style license that can be found in the
|
||||||
|
// LICENSE file.
|
||||||
|
|
||||||
|
// +build appengine
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
func maskBytes(key [4]byte, pos int, b []byte) int {
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
return pos & 3
|
||||||
|
}
|
102
vendor/github.com/gorilla/websocket/prepared.go
generated
vendored
Normal file
102
vendor/github.com/gorilla/websocket/prepared.go
generated
vendored
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PreparedMessage caches on the wire representations of a message payload.
|
||||||
|
// Use PreparedMessage to efficiently send a message payload to multiple
|
||||||
|
// connections. PreparedMessage is especially useful when compression is used
|
||||||
|
// because the CPU and memory expensive compression operation can be executed
|
||||||
|
// once for a given set of compression options.
|
||||||
|
type PreparedMessage struct {
|
||||||
|
messageType int
|
||||||
|
data []byte
|
||||||
|
mu sync.Mutex
|
||||||
|
frames map[prepareKey]*preparedFrame
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
|
||||||
|
type prepareKey struct {
|
||||||
|
isServer bool
|
||||||
|
compress bool
|
||||||
|
compressionLevel int
|
||||||
|
}
|
||||||
|
|
||||||
|
// preparedFrame contains data in wire representation.
|
||||||
|
type preparedFrame struct {
|
||||||
|
once sync.Once
|
||||||
|
data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPreparedMessage returns an initialized PreparedMessage. You can then send
|
||||||
|
// it to connection using WritePreparedMessage method. Valid wire
|
||||||
|
// representation will be calculated lazily only once for a set of current
|
||||||
|
// connection options.
|
||||||
|
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
|
||||||
|
pm := &PreparedMessage{
|
||||||
|
messageType: messageType,
|
||||||
|
frames: make(map[prepareKey]*preparedFrame),
|
||||||
|
data: data,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare a plain server frame.
|
||||||
|
_, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// To protect against caller modifying the data argument, remember the data
|
||||||
|
// copied to the plain server frame.
|
||||||
|
pm.data = frameData[len(frameData)-len(data):]
|
||||||
|
return pm, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
|
||||||
|
pm.mu.Lock()
|
||||||
|
frame, ok := pm.frames[key]
|
||||||
|
if !ok {
|
||||||
|
frame = &preparedFrame{}
|
||||||
|
pm.frames[key] = frame
|
||||||
|
}
|
||||||
|
pm.mu.Unlock()
|
||||||
|
|
||||||
|
var err error
|
||||||
|
frame.once.Do(func() {
|
||||||
|
// Prepare a frame using a 'fake' connection.
|
||||||
|
// TODO: Refactor code in conn.go to allow more direct construction of
|
||||||
|
// the frame.
|
||||||
|
mu := make(chan struct{}, 1)
|
||||||
|
mu <- struct{}{}
|
||||||
|
var nc prepareConn
|
||||||
|
c := &Conn{
|
||||||
|
conn: &nc,
|
||||||
|
mu: mu,
|
||||||
|
isServer: key.isServer,
|
||||||
|
compressionLevel: key.compressionLevel,
|
||||||
|
enableWriteCompression: true,
|
||||||
|
writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
|
||||||
|
}
|
||||||
|
if key.compress {
|
||||||
|
c.newCompressionWriter = compressNoContextTakeover
|
||||||
|
}
|
||||||
|
err = c.WriteMessage(pm.messageType, pm.data)
|
||||||
|
frame.data = nc.buf.Bytes()
|
||||||
|
})
|
||||||
|
return pm.messageType, frame.data, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type prepareConn struct {
|
||||||
|
buf bytes.Buffer
|
||||||
|
net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
|
||||||
|
func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
|
77
vendor/github.com/gorilla/websocket/proxy.go
generated
vendored
Normal file
77
vendor/github.com/gorilla/websocket/proxy.go
generated
vendored
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type netDialerFunc func(network, addr string) (net.Conn, error)
|
||||||
|
|
||||||
|
func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) {
|
||||||
|
return fn(network, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) {
|
||||||
|
return &httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDialer.Dial}, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpProxyDialer struct {
|
||||||
|
proxyURL *url.URL
|
||||||
|
forwardDial func(network, addr string) (net.Conn, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) {
|
||||||
|
hostPort, _ := hostPortNoPort(hpd.proxyURL)
|
||||||
|
conn, err := hpd.forwardDial(network, hostPort)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
connectHeader := make(http.Header)
|
||||||
|
if user := hpd.proxyURL.User; user != nil {
|
||||||
|
proxyUser := user.Username()
|
||||||
|
if proxyPassword, passwordSet := user.Password(); passwordSet {
|
||||||
|
credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword))
|
||||||
|
connectHeader.Set("Proxy-Authorization", "Basic "+credential)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connectReq := &http.Request{
|
||||||
|
Method: "CONNECT",
|
||||||
|
URL: &url.URL{Opaque: addr},
|
||||||
|
Host: addr,
|
||||||
|
Header: connectHeader,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := connectReq.Write(conn); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read response. It's OK to use and discard buffered reader here becaue
|
||||||
|
// the remote server does not speak until spoken to.
|
||||||
|
br := bufio.NewReader(conn)
|
||||||
|
resp, err := http.ReadResponse(br, connectReq)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
conn.Close()
|
||||||
|
f := strings.SplitN(resp.Status, " ", 2)
|
||||||
|
return nil, errors.New(f[1])
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
363
vendor/github.com/gorilla/websocket/server.go
generated
vendored
Normal file
363
vendor/github.com/gorilla/websocket/server.go
generated
vendored
Normal file
@ -0,0 +1,363 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HandshakeError describes an error with the handshake from the peer.
|
||||||
|
type HandshakeError struct {
|
||||||
|
message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e HandshakeError) Error() string { return e.message }
|
||||||
|
|
||||||
|
// Upgrader specifies parameters for upgrading an HTTP connection to a
|
||||||
|
// WebSocket connection.
|
||||||
|
type Upgrader struct {
|
||||||
|
// HandshakeTimeout specifies the duration for the handshake to complete.
|
||||||
|
HandshakeTimeout time.Duration
|
||||||
|
|
||||||
|
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
|
||||||
|
// size is zero, then buffers allocated by the HTTP server are used. The
|
||||||
|
// I/O buffer sizes do not limit the size of the messages that can be sent
|
||||||
|
// or received.
|
||||||
|
ReadBufferSize, WriteBufferSize int
|
||||||
|
|
||||||
|
// WriteBufferPool is a pool of buffers for write operations. If the value
|
||||||
|
// is not set, then write buffers are allocated to the connection for the
|
||||||
|
// lifetime of the connection.
|
||||||
|
//
|
||||||
|
// A pool is most useful when the application has a modest volume of writes
|
||||||
|
// across a large number of connections.
|
||||||
|
//
|
||||||
|
// Applications should use a single pool for each unique value of
|
||||||
|
// WriteBufferSize.
|
||||||
|
WriteBufferPool BufferPool
|
||||||
|
|
||||||
|
// Subprotocols specifies the server's supported protocols in order of
|
||||||
|
// preference. If this field is not nil, then the Upgrade method negotiates a
|
||||||
|
// subprotocol by selecting the first match in this list with a protocol
|
||||||
|
// requested by the client. If there's no match, then no protocol is
|
||||||
|
// negotiated (the Sec-Websocket-Protocol header is not included in the
|
||||||
|
// handshake response).
|
||||||
|
Subprotocols []string
|
||||||
|
|
||||||
|
// Error specifies the function for generating HTTP error responses. If Error
|
||||||
|
// is nil, then http.Error is used to generate the HTTP response.
|
||||||
|
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
|
||||||
|
|
||||||
|
// CheckOrigin returns true if the request Origin header is acceptable. If
|
||||||
|
// CheckOrigin is nil, then a safe default is used: return false if the
|
||||||
|
// Origin request header is present and the origin host is not equal to
|
||||||
|
// request Host header.
|
||||||
|
//
|
||||||
|
// A CheckOrigin function should carefully validate the request origin to
|
||||||
|
// prevent cross-site request forgery.
|
||||||
|
CheckOrigin func(r *http.Request) bool
|
||||||
|
|
||||||
|
// EnableCompression specify if the server should attempt to negotiate per
|
||||||
|
// message compression (RFC 7692). Setting this value to true does not
|
||||||
|
// guarantee that compression will be supported. Currently only "no context
|
||||||
|
// takeover" modes are supported.
|
||||||
|
EnableCompression bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
|
||||||
|
err := HandshakeError{reason}
|
||||||
|
if u.Error != nil {
|
||||||
|
u.Error(w, r, status, err)
|
||||||
|
} else {
|
||||||
|
w.Header().Set("Sec-Websocket-Version", "13")
|
||||||
|
http.Error(w, http.StatusText(status), status)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkSameOrigin returns true if the origin is not set or is equal to the request host.
|
||||||
|
func checkSameOrigin(r *http.Request) bool {
|
||||||
|
origin := r.Header["Origin"]
|
||||||
|
if len(origin) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
u, err := url.Parse(origin[0])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return equalASCIIFold(u.Host, r.Host)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
|
||||||
|
if u.Subprotocols != nil {
|
||||||
|
clientProtocols := Subprotocols(r)
|
||||||
|
for _, serverProtocol := range u.Subprotocols {
|
||||||
|
for _, clientProtocol := range clientProtocols {
|
||||||
|
if clientProtocol == serverProtocol {
|
||||||
|
return clientProtocol
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if responseHeader != nil {
|
||||||
|
return responseHeader.Get("Sec-Websocket-Protocol")
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
|
||||||
|
//
|
||||||
|
// The responseHeader is included in the response to the client's upgrade
|
||||||
|
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
||||||
|
// application negotiated subprotocol (Sec-WebSocket-Protocol).
|
||||||
|
//
|
||||||
|
// If the upgrade fails, then Upgrade replies to the client with an HTTP error
|
||||||
|
// response.
|
||||||
|
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
|
||||||
|
const badHandshake = "websocket: the client is not using the websocket protocol: "
|
||||||
|
|
||||||
|
if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Method != "GET" {
|
||||||
|
return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
|
||||||
|
return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
|
||||||
|
}
|
||||||
|
|
||||||
|
checkOrigin := u.CheckOrigin
|
||||||
|
if checkOrigin == nil {
|
||||||
|
checkOrigin = checkSameOrigin
|
||||||
|
}
|
||||||
|
if !checkOrigin(r) {
|
||||||
|
return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
|
||||||
|
}
|
||||||
|
|
||||||
|
challengeKey := r.Header.Get("Sec-Websocket-Key")
|
||||||
|
if challengeKey == "" {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header is missing or blank")
|
||||||
|
}
|
||||||
|
|
||||||
|
subprotocol := u.selectSubprotocol(r, responseHeader)
|
||||||
|
|
||||||
|
// Negotiate PMCE
|
||||||
|
var compress bool
|
||||||
|
if u.EnableCompression {
|
||||||
|
for _, ext := range parseExtensions(r.Header) {
|
||||||
|
if ext[""] != "permessage-deflate" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
compress = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
|
||||||
|
}
|
||||||
|
var brw *bufio.ReadWriter
|
||||||
|
netConn, brw, err := h.Hijack()
|
||||||
|
if err != nil {
|
||||||
|
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if brw.Reader.Buffered() > 0 {
|
||||||
|
netConn.Close()
|
||||||
|
return nil, errors.New("websocket: client sent data before handshake is complete")
|
||||||
|
}
|
||||||
|
|
||||||
|
var br *bufio.Reader
|
||||||
|
if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 {
|
||||||
|
// Reuse hijacked buffered reader as connection reader.
|
||||||
|
br = brw.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufioWriterBuffer(netConn, brw.Writer)
|
||||||
|
|
||||||
|
var writeBuf []byte
|
||||||
|
if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
|
||||||
|
// Reuse hijacked write buffer as connection buffer.
|
||||||
|
writeBuf = buf
|
||||||
|
}
|
||||||
|
|
||||||
|
c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf)
|
||||||
|
c.subprotocol = subprotocol
|
||||||
|
|
||||||
|
if compress {
|
||||||
|
c.newCompressionWriter = compressNoContextTakeover
|
||||||
|
c.newDecompressionReader = decompressNoContextTakeover
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use larger of hijacked buffer and connection write buffer for header.
|
||||||
|
p := buf
|
||||||
|
if len(c.writeBuf) > len(p) {
|
||||||
|
p = c.writeBuf
|
||||||
|
}
|
||||||
|
p = p[:0]
|
||||||
|
|
||||||
|
p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
|
||||||
|
p = append(p, computeAcceptKey(challengeKey)...)
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
if c.subprotocol != "" {
|
||||||
|
p = append(p, "Sec-WebSocket-Protocol: "...)
|
||||||
|
p = append(p, c.subprotocol...)
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
}
|
||||||
|
if compress {
|
||||||
|
p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
|
||||||
|
}
|
||||||
|
for k, vs := range responseHeader {
|
||||||
|
if k == "Sec-Websocket-Protocol" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, v := range vs {
|
||||||
|
p = append(p, k...)
|
||||||
|
p = append(p, ": "...)
|
||||||
|
for i := 0; i < len(v); i++ {
|
||||||
|
b := v[i]
|
||||||
|
if b <= 31 {
|
||||||
|
// prevent response splitting.
|
||||||
|
b = ' '
|
||||||
|
}
|
||||||
|
p = append(p, b)
|
||||||
|
}
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
|
||||||
|
// Clear deadlines set by HTTP server.
|
||||||
|
netConn.SetDeadline(time.Time{})
|
||||||
|
|
||||||
|
if u.HandshakeTimeout > 0 {
|
||||||
|
netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
|
||||||
|
}
|
||||||
|
if _, err = netConn.Write(p); err != nil {
|
||||||
|
netConn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if u.HandshakeTimeout > 0 {
|
||||||
|
netConn.SetWriteDeadline(time.Time{})
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
|
||||||
|
//
|
||||||
|
// Deprecated: Use websocket.Upgrader instead.
|
||||||
|
//
|
||||||
|
// Upgrade does not perform origin checking. The application is responsible for
|
||||||
|
// checking the Origin header before calling Upgrade. An example implementation
|
||||||
|
// of the same origin policy check is:
|
||||||
|
//
|
||||||
|
// if req.Header.Get("Origin") != "http://"+req.Host {
|
||||||
|
// http.Error(w, "Origin not allowed", http.StatusForbidden)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// If the endpoint supports subprotocols, then the application is responsible
|
||||||
|
// for negotiating the protocol used on the connection. Use the Subprotocols()
|
||||||
|
// function to get the subprotocols requested by the client. Use the
|
||||||
|
// Sec-Websocket-Protocol response header to specify the subprotocol selected
|
||||||
|
// by the application.
|
||||||
|
//
|
||||||
|
// The responseHeader is included in the response to the client's upgrade
|
||||||
|
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
||||||
|
// negotiated subprotocol (Sec-Websocket-Protocol).
|
||||||
|
//
|
||||||
|
// The connection buffers IO to the underlying network connection. The
|
||||||
|
// readBufSize and writeBufSize parameters specify the size of the buffers to
|
||||||
|
// use. Messages can be larger than the buffers.
|
||||||
|
//
|
||||||
|
// If the request is not a valid WebSocket handshake, then Upgrade returns an
|
||||||
|
// error of type HandshakeError. Applications should handle this error by
|
||||||
|
// replying to the client with an HTTP error response.
|
||||||
|
func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
|
||||||
|
u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
|
||||||
|
u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
|
||||||
|
// don't return errors to maintain backwards compatibility
|
||||||
|
}
|
||||||
|
u.CheckOrigin = func(r *http.Request) bool {
|
||||||
|
// allow all connections by default
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return u.Upgrade(w, r, responseHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subprotocols returns the subprotocols requested by the client in the
|
||||||
|
// Sec-Websocket-Protocol header.
|
||||||
|
func Subprotocols(r *http.Request) []string {
|
||||||
|
h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
|
||||||
|
if h == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
protocols := strings.Split(h, ",")
|
||||||
|
for i := range protocols {
|
||||||
|
protocols[i] = strings.TrimSpace(protocols[i])
|
||||||
|
}
|
||||||
|
return protocols
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsWebSocketUpgrade returns true if the client requested upgrade to the
|
||||||
|
// WebSocket protocol.
|
||||||
|
func IsWebSocketUpgrade(r *http.Request) bool {
|
||||||
|
return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
|
||||||
|
tokenListContainsValue(r.Header, "Upgrade", "websocket")
|
||||||
|
}
|
||||||
|
|
||||||
|
// bufioReaderSize size returns the size of a bufio.Reader.
|
||||||
|
func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int {
|
||||||
|
// This code assumes that peek on a reset reader returns
|
||||||
|
// bufio.Reader.buf[:0].
|
||||||
|
// TODO: Use bufio.Reader.Size() after Go 1.10
|
||||||
|
br.Reset(originalReader)
|
||||||
|
if p, err := br.Peek(0); err == nil {
|
||||||
|
return cap(p)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeHook is an io.Writer that records the last slice passed to it vio
|
||||||
|
// io.Writer.Write.
|
||||||
|
type writeHook struct {
|
||||||
|
p []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wh *writeHook) Write(p []byte) (int, error) {
|
||||||
|
wh.p = p
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bufioWriterBuffer grabs the buffer from a bufio.Writer.
|
||||||
|
func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
|
||||||
|
// This code assumes that bufio.Writer.buf[:1] is passed to the
|
||||||
|
// bufio.Writer's underlying writer.
|
||||||
|
var wh writeHook
|
||||||
|
bw.Reset(&wh)
|
||||||
|
bw.WriteByte(0)
|
||||||
|
bw.Flush()
|
||||||
|
|
||||||
|
bw.Reset(originalWriter)
|
||||||
|
|
||||||
|
return wh.p[:cap(wh.p)]
|
||||||
|
}
|
19
vendor/github.com/gorilla/websocket/trace.go
generated
vendored
Normal file
19
vendor/github.com/gorilla/websocket/trace.go
generated
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net/http/httptrace"
|
||||||
|
)
|
||||||
|
|
||||||
|
func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error {
|
||||||
|
if trace.TLSHandshakeStart != nil {
|
||||||
|
trace.TLSHandshakeStart()
|
||||||
|
}
|
||||||
|
err := doHandshake(tlsConn, cfg)
|
||||||
|
if trace.TLSHandshakeDone != nil {
|
||||||
|
trace.TLSHandshakeDone(tlsConn.ConnectionState(), err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
12
vendor/github.com/gorilla/websocket/trace_17.go
generated
vendored
Normal file
12
vendor/github.com/gorilla/websocket/trace_17.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
// +build !go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net/http/httptrace"
|
||||||
|
)
|
||||||
|
|
||||||
|
func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error {
|
||||||
|
return doHandshake(tlsConn, cfg)
|
||||||
|
}
|
283
vendor/github.com/gorilla/websocket/util.go
generated
vendored
Normal file
283
vendor/github.com/gorilla/websocket/util.go
generated
vendored
Normal file
@ -0,0 +1,283 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/base64"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
|
||||||
|
|
||||||
|
func computeAcceptKey(challengeKey string) string {
|
||||||
|
h := sha1.New()
|
||||||
|
h.Write([]byte(challengeKey))
|
||||||
|
h.Write(keyGUID)
|
||||||
|
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateChallengeKey() (string, error) {
|
||||||
|
p := make([]byte, 16)
|
||||||
|
if _, err := io.ReadFull(rand.Reader, p); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token octets per RFC 2616.
|
||||||
|
var isTokenOctet = [256]bool{
|
||||||
|
'!': true,
|
||||||
|
'#': true,
|
||||||
|
'$': true,
|
||||||
|
'%': true,
|
||||||
|
'&': true,
|
||||||
|
'\'': true,
|
||||||
|
'*': true,
|
||||||
|
'+': true,
|
||||||
|
'-': true,
|
||||||
|
'.': true,
|
||||||
|
'0': true,
|
||||||
|
'1': true,
|
||||||
|
'2': true,
|
||||||
|
'3': true,
|
||||||
|
'4': true,
|
||||||
|
'5': true,
|
||||||
|
'6': true,
|
||||||
|
'7': true,
|
||||||
|
'8': true,
|
||||||
|
'9': true,
|
||||||
|
'A': true,
|
||||||
|
'B': true,
|
||||||
|
'C': true,
|
||||||
|
'D': true,
|
||||||
|
'E': true,
|
||||||
|
'F': true,
|
||||||
|
'G': true,
|
||||||
|
'H': true,
|
||||||
|
'I': true,
|
||||||
|
'J': true,
|
||||||
|
'K': true,
|
||||||
|
'L': true,
|
||||||
|
'M': true,
|
||||||
|
'N': true,
|
||||||
|
'O': true,
|
||||||
|
'P': true,
|
||||||
|
'Q': true,
|
||||||
|
'R': true,
|
||||||
|
'S': true,
|
||||||
|
'T': true,
|
||||||
|
'U': true,
|
||||||
|
'W': true,
|
||||||
|
'V': true,
|
||||||
|
'X': true,
|
||||||
|
'Y': true,
|
||||||
|
'Z': true,
|
||||||
|
'^': true,
|
||||||
|
'_': true,
|
||||||
|
'`': true,
|
||||||
|
'a': true,
|
||||||
|
'b': true,
|
||||||
|
'c': true,
|
||||||
|
'd': true,
|
||||||
|
'e': true,
|
||||||
|
'f': true,
|
||||||
|
'g': true,
|
||||||
|
'h': true,
|
||||||
|
'i': true,
|
||||||
|
'j': true,
|
||||||
|
'k': true,
|
||||||
|
'l': true,
|
||||||
|
'm': true,
|
||||||
|
'n': true,
|
||||||
|
'o': true,
|
||||||
|
'p': true,
|
||||||
|
'q': true,
|
||||||
|
'r': true,
|
||||||
|
's': true,
|
||||||
|
't': true,
|
||||||
|
'u': true,
|
||||||
|
'v': true,
|
||||||
|
'w': true,
|
||||||
|
'x': true,
|
||||||
|
'y': true,
|
||||||
|
'z': true,
|
||||||
|
'|': true,
|
||||||
|
'~': true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// skipSpace returns a slice of the string s with all leading RFC 2616 linear
|
||||||
|
// whitespace removed.
|
||||||
|
func skipSpace(s string) (rest string) {
|
||||||
|
i := 0
|
||||||
|
for ; i < len(s); i++ {
|
||||||
|
if b := s[i]; b != ' ' && b != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s[i:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextToken returns the leading RFC 2616 token of s and the string following
|
||||||
|
// the token.
|
||||||
|
func nextToken(s string) (token, rest string) {
|
||||||
|
i := 0
|
||||||
|
for ; i < len(s); i++ {
|
||||||
|
if !isTokenOctet[s[i]] {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s[:i], s[i:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextTokenOrQuoted returns the leading token or quoted string per RFC 2616
|
||||||
|
// and the string following the token or quoted string.
|
||||||
|
func nextTokenOrQuoted(s string) (value string, rest string) {
|
||||||
|
if !strings.HasPrefix(s, "\"") {
|
||||||
|
return nextToken(s)
|
||||||
|
}
|
||||||
|
s = s[1:]
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
switch s[i] {
|
||||||
|
case '"':
|
||||||
|
return s[:i], s[i+1:]
|
||||||
|
case '\\':
|
||||||
|
p := make([]byte, len(s)-1)
|
||||||
|
j := copy(p, s[:i])
|
||||||
|
escape := true
|
||||||
|
for i = i + 1; i < len(s); i++ {
|
||||||
|
b := s[i]
|
||||||
|
switch {
|
||||||
|
case escape:
|
||||||
|
escape = false
|
||||||
|
p[j] = b
|
||||||
|
j++
|
||||||
|
case b == '\\':
|
||||||
|
escape = true
|
||||||
|
case b == '"':
|
||||||
|
return string(p[:j]), s[i+1:]
|
||||||
|
default:
|
||||||
|
p[j] = b
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// equalASCIIFold returns true if s is equal to t with ASCII case folding as
|
||||||
|
// defined in RFC 4790.
|
||||||
|
func equalASCIIFold(s, t string) bool {
|
||||||
|
for s != "" && t != "" {
|
||||||
|
sr, size := utf8.DecodeRuneInString(s)
|
||||||
|
s = s[size:]
|
||||||
|
tr, size := utf8.DecodeRuneInString(t)
|
||||||
|
t = t[size:]
|
||||||
|
if sr == tr {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if 'A' <= sr && sr <= 'Z' {
|
||||||
|
sr = sr + 'a' - 'A'
|
||||||
|
}
|
||||||
|
if 'A' <= tr && tr <= 'Z' {
|
||||||
|
tr = tr + 'a' - 'A'
|
||||||
|
}
|
||||||
|
if sr != tr {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s == t
|
||||||
|
}
|
||||||
|
|
||||||
|
// tokenListContainsValue returns true if the 1#token header with the given
|
||||||
|
// name contains a token equal to value with ASCII case folding.
|
||||||
|
func tokenListContainsValue(header http.Header, name string, value string) bool {
|
||||||
|
headers:
|
||||||
|
for _, s := range header[name] {
|
||||||
|
for {
|
||||||
|
var t string
|
||||||
|
t, s = nextToken(skipSpace(s))
|
||||||
|
if t == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = skipSpace(s)
|
||||||
|
if s != "" && s[0] != ',' {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
if equalASCIIFold(t, value) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if s == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = s[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseExtensions parses WebSocket extensions from a header.
|
||||||
|
func parseExtensions(header http.Header) []map[string]string {
|
||||||
|
// From RFC 6455:
|
||||||
|
//
|
||||||
|
// Sec-WebSocket-Extensions = extension-list
|
||||||
|
// extension-list = 1#extension
|
||||||
|
// extension = extension-token *( ";" extension-param )
|
||||||
|
// extension-token = registered-token
|
||||||
|
// registered-token = token
|
||||||
|
// extension-param = token [ "=" (token | quoted-string) ]
|
||||||
|
// ;When using the quoted-string syntax variant, the value
|
||||||
|
// ;after quoted-string unescaping MUST conform to the
|
||||||
|
// ;'token' ABNF.
|
||||||
|
|
||||||
|
var result []map[string]string
|
||||||
|
headers:
|
||||||
|
for _, s := range header["Sec-Websocket-Extensions"] {
|
||||||
|
for {
|
||||||
|
var t string
|
||||||
|
t, s = nextToken(skipSpace(s))
|
||||||
|
if t == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
ext := map[string]string{"": t}
|
||||||
|
for {
|
||||||
|
s = skipSpace(s)
|
||||||
|
if !strings.HasPrefix(s, ";") {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var k string
|
||||||
|
k, s = nextToken(skipSpace(s[1:]))
|
||||||
|
if k == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = skipSpace(s)
|
||||||
|
var v string
|
||||||
|
if strings.HasPrefix(s, "=") {
|
||||||
|
v, s = nextTokenOrQuoted(skipSpace(s[1:]))
|
||||||
|
s = skipSpace(s)
|
||||||
|
}
|
||||||
|
if s != "" && s[0] != ',' && s[0] != ';' {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
ext[k] = v
|
||||||
|
}
|
||||||
|
if s != "" && s[0] != ',' {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
result = append(result, ext)
|
||||||
|
if s == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = s[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
473
vendor/github.com/gorilla/websocket/x_net_proxy.go
generated
vendored
Normal file
473
vendor/github.com/gorilla/websocket/x_net_proxy.go
generated
vendored
Normal file
@ -0,0 +1,473 @@
|
|||||||
|
// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT.
|
||||||
|
//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy
|
||||||
|
|
||||||
|
// Package proxy provides support for a variety of protocols to proxy network
|
||||||
|
// data.
|
||||||
|
//
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type proxy_direct struct{}
|
||||||
|
|
||||||
|
// Direct is a direct proxy: one that makes network connections directly.
|
||||||
|
var proxy_Direct = proxy_direct{}
|
||||||
|
|
||||||
|
func (proxy_direct) Dial(network, addr string) (net.Conn, error) {
|
||||||
|
return net.Dial(network, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A PerHost directs connections to a default Dialer unless the host name
|
||||||
|
// requested matches one of a number of exceptions.
|
||||||
|
type proxy_PerHost struct {
|
||||||
|
def, bypass proxy_Dialer
|
||||||
|
|
||||||
|
bypassNetworks []*net.IPNet
|
||||||
|
bypassIPs []net.IP
|
||||||
|
bypassZones []string
|
||||||
|
bypassHosts []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPerHost returns a PerHost Dialer that directs connections to either
|
||||||
|
// defaultDialer or bypass, depending on whether the connection matches one of
|
||||||
|
// the configured rules.
|
||||||
|
func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost {
|
||||||
|
return &proxy_PerHost{
|
||||||
|
def: defaultDialer,
|
||||||
|
bypass: bypass,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial connects to the address addr on the given network through either
|
||||||
|
// defaultDialer or bypass.
|
||||||
|
func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) {
|
||||||
|
host, _, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return p.dialerForRequest(host).Dial(network, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer {
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
for _, net := range p.bypassNetworks {
|
||||||
|
if net.Contains(ip) {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bypassIP := range p.bypassIPs {
|
||||||
|
if bypassIP.Equal(ip) {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p.def
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, zone := range p.bypassZones {
|
||||||
|
if strings.HasSuffix(host, zone) {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
if host == zone[1:] {
|
||||||
|
// For a zone ".example.com", we match "example.com"
|
||||||
|
// too.
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bypassHost := range p.bypassHosts {
|
||||||
|
if bypassHost == host {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p.def
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddFromString parses a string that contains comma-separated values
|
||||||
|
// specifying hosts that should use the bypass proxy. Each value is either an
|
||||||
|
// IP address, a CIDR range, a zone (*.example.com) or a host name
|
||||||
|
// (localhost). A best effort is made to parse the string and errors are
|
||||||
|
// ignored.
|
||||||
|
func (p *proxy_PerHost) AddFromString(s string) {
|
||||||
|
hosts := strings.Split(s, ",")
|
||||||
|
for _, host := range hosts {
|
||||||
|
host = strings.TrimSpace(host)
|
||||||
|
if len(host) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(host, "/") {
|
||||||
|
// We assume that it's a CIDR address like 127.0.0.0/8
|
||||||
|
if _, net, err := net.ParseCIDR(host); err == nil {
|
||||||
|
p.AddNetwork(net)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
p.AddIP(ip)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(host, "*.") {
|
||||||
|
p.AddZone(host[1:])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p.AddHost(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddIP specifies an IP address that will use the bypass proxy. Note that
|
||||||
|
// this will only take effect if a literal IP address is dialed. A connection
|
||||||
|
// to a named host will never match an IP.
|
||||||
|
func (p *proxy_PerHost) AddIP(ip net.IP) {
|
||||||
|
p.bypassIPs = append(p.bypassIPs, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddNetwork specifies an IP range that will use the bypass proxy. Note that
|
||||||
|
// this will only take effect if a literal IP address is dialed. A connection
|
||||||
|
// to a named host will never match.
|
||||||
|
func (p *proxy_PerHost) AddNetwork(net *net.IPNet) {
|
||||||
|
p.bypassNetworks = append(p.bypassNetworks, net)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of
|
||||||
|
// "example.com" matches "example.com" and all of its subdomains.
|
||||||
|
func (p *proxy_PerHost) AddZone(zone string) {
|
||||||
|
if strings.HasSuffix(zone, ".") {
|
||||||
|
zone = zone[:len(zone)-1]
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(zone, ".") {
|
||||||
|
zone = "." + zone
|
||||||
|
}
|
||||||
|
p.bypassZones = append(p.bypassZones, zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddHost specifies a host name that will use the bypass proxy.
|
||||||
|
func (p *proxy_PerHost) AddHost(host string) {
|
||||||
|
if strings.HasSuffix(host, ".") {
|
||||||
|
host = host[:len(host)-1]
|
||||||
|
}
|
||||||
|
p.bypassHosts = append(p.bypassHosts, host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Dialer is a means to establish a connection.
|
||||||
|
type proxy_Dialer interface {
|
||||||
|
// Dial connects to the given address via the proxy.
|
||||||
|
Dial(network, addr string) (c net.Conn, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth contains authentication parameters that specific Dialers may require.
|
||||||
|
type proxy_Auth struct {
|
||||||
|
User, Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromEnvironment returns the dialer specified by the proxy related variables in
|
||||||
|
// the environment.
|
||||||
|
func proxy_FromEnvironment() proxy_Dialer {
|
||||||
|
allProxy := proxy_allProxyEnv.Get()
|
||||||
|
if len(allProxy) == 0 {
|
||||||
|
return proxy_Direct
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyURL, err := url.Parse(allProxy)
|
||||||
|
if err != nil {
|
||||||
|
return proxy_Direct
|
||||||
|
}
|
||||||
|
proxy, err := proxy_FromURL(proxyURL, proxy_Direct)
|
||||||
|
if err != nil {
|
||||||
|
return proxy_Direct
|
||||||
|
}
|
||||||
|
|
||||||
|
noProxy := proxy_noProxyEnv.Get()
|
||||||
|
if len(noProxy) == 0 {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
perHost := proxy_NewPerHost(proxy, proxy_Direct)
|
||||||
|
perHost.AddFromString(noProxy)
|
||||||
|
return perHost
|
||||||
|
}
|
||||||
|
|
||||||
|
// proxySchemes is a map from URL schemes to a function that creates a Dialer
|
||||||
|
// from a URL with such a scheme.
|
||||||
|
var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)
|
||||||
|
|
||||||
|
// RegisterDialerType takes a URL scheme and a function to generate Dialers from
|
||||||
|
// a URL with that scheme and a forwarding Dialer. Registered schemes are used
|
||||||
|
// by FromURL.
|
||||||
|
func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) {
|
||||||
|
if proxy_proxySchemes == nil {
|
||||||
|
proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error))
|
||||||
|
}
|
||||||
|
proxy_proxySchemes[scheme] = f
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromURL returns a Dialer given a URL specification and an underlying
|
||||||
|
// Dialer for it to make network requests.
|
||||||
|
func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) {
|
||||||
|
var auth *proxy_Auth
|
||||||
|
if u.User != nil {
|
||||||
|
auth = new(proxy_Auth)
|
||||||
|
auth.User = u.User.Username()
|
||||||
|
if p, ok := u.User.Password(); ok {
|
||||||
|
auth.Password = p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch u.Scheme {
|
||||||
|
case "socks5":
|
||||||
|
return proxy_SOCKS5("tcp", u.Host, auth, forward)
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the scheme doesn't match any of the built-in schemes, see if it
|
||||||
|
// was registered by another package.
|
||||||
|
if proxy_proxySchemes != nil {
|
||||||
|
if f, ok := proxy_proxySchemes[u.Scheme]; ok {
|
||||||
|
return f(u, forward)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New("proxy: unknown scheme: " + u.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
proxy_allProxyEnv = &proxy_envOnce{
|
||||||
|
names: []string{"ALL_PROXY", "all_proxy"},
|
||||||
|
}
|
||||||
|
proxy_noProxyEnv = &proxy_envOnce{
|
||||||
|
names: []string{"NO_PROXY", "no_proxy"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// envOnce looks up an environment variable (optionally by multiple
|
||||||
|
// names) once. It mitigates expensive lookups on some platforms
|
||||||
|
// (e.g. Windows).
|
||||||
|
// (Borrowed from net/http/transport.go)
|
||||||
|
type proxy_envOnce struct {
|
||||||
|
names []string
|
||||||
|
once sync.Once
|
||||||
|
val string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *proxy_envOnce) Get() string {
|
||||||
|
e.once.Do(e.init)
|
||||||
|
return e.val
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *proxy_envOnce) init() {
|
||||||
|
for _, n := range e.names {
|
||||||
|
e.val = os.Getenv(n)
|
||||||
|
if e.val != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address
|
||||||
|
// with an optional username and password. See RFC 1928 and RFC 1929.
|
||||||
|
func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) {
|
||||||
|
s := &proxy_socks5{
|
||||||
|
network: network,
|
||||||
|
addr: addr,
|
||||||
|
forward: forward,
|
||||||
|
}
|
||||||
|
if auth != nil {
|
||||||
|
s.user = auth.User
|
||||||
|
s.password = auth.Password
|
||||||
|
}
|
||||||
|
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxy_socks5 struct {
|
||||||
|
user, password string
|
||||||
|
network, addr string
|
||||||
|
forward proxy_Dialer
|
||||||
|
}
|
||||||
|
|
||||||
|
const proxy_socks5Version = 5
|
||||||
|
|
||||||
|
const (
|
||||||
|
proxy_socks5AuthNone = 0
|
||||||
|
proxy_socks5AuthPassword = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
const proxy_socks5Connect = 1
|
||||||
|
|
||||||
|
const (
|
||||||
|
proxy_socks5IP4 = 1
|
||||||
|
proxy_socks5Domain = 3
|
||||||
|
proxy_socks5IP6 = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
var proxy_socks5Errors = []string{
|
||||||
|
"",
|
||||||
|
"general failure",
|
||||||
|
"connection forbidden",
|
||||||
|
"network unreachable",
|
||||||
|
"host unreachable",
|
||||||
|
"connection refused",
|
||||||
|
"TTL expired",
|
||||||
|
"command not supported",
|
||||||
|
"address type not supported",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial connects to the address addr on the given network via the SOCKS5 proxy.
|
||||||
|
func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp", "tcp6", "tcp4":
|
||||||
|
default:
|
||||||
|
return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := s.forward.Dial(s.network, s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := s.connect(conn, addr); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// connect takes an existing connection to a socks5 proxy server,
|
||||||
|
// and commands the server to extend that connection to target,
|
||||||
|
// which must be a canonical address with a host and port.
|
||||||
|
func (s *proxy_socks5) connect(conn net.Conn, target string) error {
|
||||||
|
host, portStr, err := net.SplitHostPort(target)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := strconv.Atoi(portStr)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("proxy: failed to parse port number: " + portStr)
|
||||||
|
}
|
||||||
|
if port < 1 || port > 0xffff {
|
||||||
|
return errors.New("proxy: port number out of range: " + portStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// the size here is just an estimate
|
||||||
|
buf := make([]byte, 0, 6+len(host))
|
||||||
|
|
||||||
|
buf = append(buf, proxy_socks5Version)
|
||||||
|
if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 {
|
||||||
|
buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword)
|
||||||
|
} else {
|
||||||
|
buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
if buf[0] != 5 {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0])))
|
||||||
|
}
|
||||||
|
if buf[1] == 0xff {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication")
|
||||||
|
}
|
||||||
|
|
||||||
|
// See RFC 1929
|
||||||
|
if buf[1] == proxy_socks5AuthPassword {
|
||||||
|
buf = buf[:0]
|
||||||
|
buf = append(buf, 1 /* password protocol version */)
|
||||||
|
buf = append(buf, uint8(len(s.user)))
|
||||||
|
buf = append(buf, s.user...)
|
||||||
|
buf = append(buf, uint8(len(s.password)))
|
||||||
|
buf = append(buf, s.password...)
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[1] != 0 {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buf = buf[:0]
|
||||||
|
buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */)
|
||||||
|
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
buf = append(buf, proxy_socks5IP4)
|
||||||
|
ip = ip4
|
||||||
|
} else {
|
||||||
|
buf = append(buf, proxy_socks5IP6)
|
||||||
|
}
|
||||||
|
buf = append(buf, ip...)
|
||||||
|
} else {
|
||||||
|
if len(host) > 255 {
|
||||||
|
return errors.New("proxy: destination host name too long: " + host)
|
||||||
|
}
|
||||||
|
buf = append(buf, proxy_socks5Domain)
|
||||||
|
buf = append(buf, byte(len(host)))
|
||||||
|
buf = append(buf, host...)
|
||||||
|
}
|
||||||
|
buf = append(buf, byte(port>>8), byte(port))
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(conn, buf[:4]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
failure := "unknown error"
|
||||||
|
if int(buf[1]) < len(proxy_socks5Errors) {
|
||||||
|
failure = proxy_socks5Errors[buf[1]]
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(failure) > 0 {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure)
|
||||||
|
}
|
||||||
|
|
||||||
|
bytesToDiscard := 0
|
||||||
|
switch buf[3] {
|
||||||
|
case proxy_socks5IP4:
|
||||||
|
bytesToDiscard = net.IPv4len
|
||||||
|
case proxy_socks5IP6:
|
||||||
|
bytesToDiscard = net.IPv6len
|
||||||
|
case proxy_socks5Domain:
|
||||||
|
_, err := io.ReadFull(conn, buf[:1])
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
bytesToDiscard = int(buf[0])
|
||||||
|
default:
|
||||||
|
return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cap(buf) < bytesToDiscard {
|
||||||
|
buf = make([]byte, bytesToDiscard)
|
||||||
|
} else {
|
||||||
|
buf = buf[:bytesToDiscard]
|
||||||
|
}
|
||||||
|
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also need to discard the port number
|
||||||
|
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
9
vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE
generated
vendored
9
vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE
generated
vendored
@ -1,9 +0,0 @@
|
|||||||
(The MIT License)
|
|
||||||
|
|
||||||
Copyright (c) 2017 marvin + konsorten GmbH (open-source@konsorten.de)
|
|
||||||
|
|
||||||
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.
|
|
42
vendor/github.com/konsorten/go-windows-terminal-sequences/README.md
generated
vendored
42
vendor/github.com/konsorten/go-windows-terminal-sequences/README.md
generated
vendored
@ -1,42 +0,0 @@
|
|||||||
# Windows Terminal Sequences
|
|
||||||
|
|
||||||
This library allow for enabling Windows terminal color support for Go.
|
|
||||||
|
|
||||||
See [Console Virtual Terminal Sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) for details.
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
sequences "github.com/konsorten/go-windows-terminal-sequences"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
sequences.EnableVirtualTerminalProcessing(syscall.Stdout, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## Authors
|
|
||||||
|
|
||||||
The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de).
|
|
||||||
|
|
||||||
We thank all the authors who provided code to this library:
|
|
||||||
|
|
||||||
* Felix Kollmann
|
|
||||||
* Nicolas Perraut
|
|
||||||
* @dirty49374
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
(The MIT License)
|
|
||||||
|
|
||||||
Copyright (c) 2018 marvin + konsorten GmbH (open-source@konsorten.de)
|
|
||||||
|
|
||||||
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.
|
|
1
vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod
generated
vendored
1
vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod
generated
vendored
@ -1 +0,0 @@
|
|||||||
module github.com/konsorten/go-windows-terminal-sequences
|
|
35
vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go
generated
vendored
35
vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go
generated
vendored
@ -1,35 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package sequences
|
|
||||||
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
kernel32Dll *syscall.LazyDLL = syscall.NewLazyDLL("Kernel32.dll")
|
|
||||||
setConsoleMode *syscall.LazyProc = kernel32Dll.NewProc("SetConsoleMode")
|
|
||||||
)
|
|
||||||
|
|
||||||
func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error {
|
|
||||||
const ENABLE_VIRTUAL_TERMINAL_PROCESSING uint32 = 0x4
|
|
||||||
|
|
||||||
var mode uint32
|
|
||||||
err := syscall.GetConsoleMode(syscall.Stdout, &mode)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if enable {
|
|
||||||
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
|
||||||
} else {
|
|
||||||
mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
|
||||||
}
|
|
||||||
|
|
||||||
ret, _, err := setConsoleMode.Call(uintptr(stream), uintptr(mode))
|
|
||||||
if ret == 0 {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
11
vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go
generated
vendored
11
vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go
generated
vendored
@ -1,11 +0,0 @@
|
|||||||
// +build linux darwin
|
|
||||||
|
|
||||||
package sequences
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func EnableVirtualTerminalProcessing(stream uintptr, enable bool) error {
|
|
||||||
return fmt.Errorf("windows only package")
|
|
||||||
}
|
|
2
vendor/github.com/sirupsen/logrus/.gitignore
generated
vendored
2
vendor/github.com/sirupsen/logrus/.gitignore
generated
vendored
@ -1,2 +1,4 @@
|
|||||||
logrus
|
logrus
|
||||||
vendor
|
vendor
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
14
vendor/github.com/sirupsen/logrus/.travis.yml
generated
vendored
14
vendor/github.com/sirupsen/logrus/.travis.yml
generated
vendored
@ -4,14 +4,12 @@ git:
|
|||||||
depth: 1
|
depth: 1
|
||||||
env:
|
env:
|
||||||
- GO111MODULE=on
|
- GO111MODULE=on
|
||||||
go: [1.13.x, 1.14.x]
|
go: 1.15.x
|
||||||
os: [linux, osx]
|
os: linux
|
||||||
install:
|
install:
|
||||||
- ./travis/install.sh
|
- ./travis/install.sh
|
||||||
script:
|
script:
|
||||||
- ./travis/cross_build.sh
|
- cd ci
|
||||||
- ./travis/lint.sh
|
- go run mage.go -v -w ../ crossBuild
|
||||||
- export GOMAXPROCS=4
|
- go run mage.go -v -w ../ lint
|
||||||
- export GORACE=halt_on_error=1
|
- go run mage.go -v -w ../ test
|
||||||
- go test -race -v ./...
|
|
||||||
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then go test -race -v -tags appengine ./... ; fi
|
|
||||||
|
36
vendor/github.com/sirupsen/logrus/CHANGELOG.md
generated
vendored
36
vendor/github.com/sirupsen/logrus/CHANGELOG.md
generated
vendored
@ -1,3 +1,39 @@
|
|||||||
|
# 1.8.1
|
||||||
|
Code quality:
|
||||||
|
* move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer
|
||||||
|
* improve timestamp format documentation
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
* fix race condition on logger hooks
|
||||||
|
|
||||||
|
|
||||||
|
# 1.8.0
|
||||||
|
|
||||||
|
Correct versioning number replacing v1.7.1.
|
||||||
|
|
||||||
|
# 1.7.1
|
||||||
|
|
||||||
|
Beware this release has introduced a new public API and its semver is therefore incorrect.
|
||||||
|
|
||||||
|
Code quality:
|
||||||
|
* use go 1.15 in travis
|
||||||
|
* use magefile as task runner
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
* small fixes about new go 1.13 error formatting system
|
||||||
|
* Fix for long time race condiction with mutating data hooks
|
||||||
|
|
||||||
|
Features:
|
||||||
|
* build support for zos
|
||||||
|
|
||||||
|
# 1.7.0
|
||||||
|
Fixes:
|
||||||
|
* the dependency toward a windows terminal library has been removed
|
||||||
|
|
||||||
|
Features:
|
||||||
|
* a new buffer pool management API has been added
|
||||||
|
* a set of `<LogLevel>Fn()` functions have been added
|
||||||
|
|
||||||
# 1.6.0
|
# 1.6.0
|
||||||
Fixes:
|
Fixes:
|
||||||
* end of line cleanup
|
* end of line cleanup
|
||||||
|
2
vendor/github.com/sirupsen/logrus/README.md
generated
vendored
2
vendor/github.com/sirupsen/logrus/README.md
generated
vendored
@ -402,7 +402,7 @@ func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
|
|||||||
// source of the official loggers.
|
// source of the official loggers.
|
||||||
serialized, err := json.Marshal(entry.Data)
|
serialized, err := json.Marshal(entry.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err)
|
||||||
}
|
}
|
||||||
return append(serialized, '\n'), nil
|
return append(serialized, '\n'), nil
|
||||||
}
|
}
|
||||||
|
52
vendor/github.com/sirupsen/logrus/buffer_pool.go
generated
vendored
Normal file
52
vendor/github.com/sirupsen/logrus/buffer_pool.go
generated
vendored
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bufferPool BufferPool
|
||||||
|
)
|
||||||
|
|
||||||
|
type BufferPool interface {
|
||||||
|
Put(*bytes.Buffer)
|
||||||
|
Get() *bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
type defaultPool struct {
|
||||||
|
pool *sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *defaultPool) Put(buf *bytes.Buffer) {
|
||||||
|
p.pool.Put(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *defaultPool) Get() *bytes.Buffer {
|
||||||
|
return p.pool.Get().(*bytes.Buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getBuffer() *bytes.Buffer {
|
||||||
|
return bufferPool.Get()
|
||||||
|
}
|
||||||
|
|
||||||
|
func putBuffer(buf *bytes.Buffer) {
|
||||||
|
buf.Reset()
|
||||||
|
bufferPool.Put(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetBufferPool allows to replace the default logrus buffer pool
|
||||||
|
// to better meets the specific needs of an application.
|
||||||
|
func SetBufferPool(bp BufferPool) {
|
||||||
|
bufferPool = bp
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
SetBufferPool(&defaultPool{
|
||||||
|
pool: &sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return new(bytes.Buffer)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
85
vendor/github.com/sirupsen/logrus/entry.go
generated
vendored
85
vendor/github.com/sirupsen/logrus/entry.go
generated
vendored
@ -13,7 +13,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
bufferPool *sync.Pool
|
|
||||||
|
|
||||||
// qualified package name, cached at first use
|
// qualified package name, cached at first use
|
||||||
logrusPackage string
|
logrusPackage string
|
||||||
@ -31,12 +30,6 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
bufferPool = &sync.Pool{
|
|
||||||
New: func() interface{} {
|
|
||||||
return new(bytes.Buffer)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// start at the bottom of the stack before the package-name cache is primed
|
// start at the bottom of the stack before the package-name cache is primed
|
||||||
minimumCallerDepth = 1
|
minimumCallerDepth = 1
|
||||||
}
|
}
|
||||||
@ -85,6 +78,14 @@ func NewEntry(logger *Logger) *Entry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Dup() *Entry {
|
||||||
|
data := make(Fields, len(entry.Data))
|
||||||
|
for k, v := range entry.Data {
|
||||||
|
data[k] = v
|
||||||
|
}
|
||||||
|
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err}
|
||||||
|
}
|
||||||
|
|
||||||
// Returns the bytes representation of this entry from the formatter.
|
// Returns the bytes representation of this entry from the formatter.
|
||||||
func (entry *Entry) Bytes() ([]byte, error) {
|
func (entry *Entry) Bytes() ([]byte, error) {
|
||||||
return entry.Logger.Formatter.Format(entry)
|
return entry.Logger.Formatter.Format(entry)
|
||||||
@ -130,11 +131,9 @@ func (entry *Entry) WithFields(fields Fields) *Entry {
|
|||||||
for k, v := range fields {
|
for k, v := range fields {
|
||||||
isErrField := false
|
isErrField := false
|
||||||
if t := reflect.TypeOf(v); t != nil {
|
if t := reflect.TypeOf(v); t != nil {
|
||||||
switch t.Kind() {
|
switch {
|
||||||
case reflect.Func:
|
case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func:
|
||||||
isErrField = true
|
isErrField = true
|
||||||
case reflect.Ptr:
|
|
||||||
isErrField = t.Elem().Kind() == reflect.Func
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if isErrField {
|
if isErrField {
|
||||||
@ -219,65 +218,72 @@ func (entry Entry) HasCaller() (has bool) {
|
|||||||
entry.Caller != nil
|
entry.Caller != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// This function is not declared with a pointer value because otherwise
|
func (entry *Entry) log(level Level, msg string) {
|
||||||
// race conditions will occur when using multiple goroutines
|
|
||||||
func (entry Entry) log(level Level, msg string) {
|
|
||||||
var buffer *bytes.Buffer
|
var buffer *bytes.Buffer
|
||||||
|
|
||||||
// Default to now, but allow users to override if they want.
|
newEntry := entry.Dup()
|
||||||
//
|
|
||||||
// We don't have to worry about polluting future calls to Entry#log()
|
if newEntry.Time.IsZero() {
|
||||||
// with this assignment because this function is declared with a
|
newEntry.Time = time.Now()
|
||||||
// non-pointer receiver.
|
|
||||||
if entry.Time.IsZero() {
|
|
||||||
entry.Time = time.Now()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
entry.Level = level
|
newEntry.Level = level
|
||||||
entry.Message = msg
|
newEntry.Message = msg
|
||||||
entry.Logger.mu.Lock()
|
|
||||||
if entry.Logger.ReportCaller {
|
newEntry.Logger.mu.Lock()
|
||||||
entry.Caller = getCaller()
|
reportCaller := newEntry.Logger.ReportCaller
|
||||||
|
newEntry.Logger.mu.Unlock()
|
||||||
|
|
||||||
|
if reportCaller {
|
||||||
|
newEntry.Caller = getCaller()
|
||||||
}
|
}
|
||||||
entry.Logger.mu.Unlock()
|
|
||||||
|
|
||||||
entry.fireHooks()
|
newEntry.fireHooks()
|
||||||
|
|
||||||
buffer = bufferPool.Get().(*bytes.Buffer)
|
buffer = getBuffer()
|
||||||
|
defer func() {
|
||||||
|
newEntry.Buffer = nil
|
||||||
|
putBuffer(buffer)
|
||||||
|
}()
|
||||||
buffer.Reset()
|
buffer.Reset()
|
||||||
defer bufferPool.Put(buffer)
|
newEntry.Buffer = buffer
|
||||||
entry.Buffer = buffer
|
|
||||||
|
|
||||||
entry.write()
|
newEntry.write()
|
||||||
|
|
||||||
entry.Buffer = nil
|
newEntry.Buffer = nil
|
||||||
|
|
||||||
// To avoid Entry#log() returning a value that only would make sense for
|
// To avoid Entry#log() returning a value that only would make sense for
|
||||||
// panic() to use in Entry#Panic(), we avoid the allocation by checking
|
// panic() to use in Entry#Panic(), we avoid the allocation by checking
|
||||||
// directly here.
|
// directly here.
|
||||||
if level <= PanicLevel {
|
if level <= PanicLevel {
|
||||||
panic(&entry)
|
panic(newEntry)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry *Entry) fireHooks() {
|
func (entry *Entry) fireHooks() {
|
||||||
|
var tmpHooks LevelHooks
|
||||||
entry.Logger.mu.Lock()
|
entry.Logger.mu.Lock()
|
||||||
defer entry.Logger.mu.Unlock()
|
tmpHooks = make(LevelHooks, len(entry.Logger.Hooks))
|
||||||
err := entry.Logger.Hooks.Fire(entry.Level, entry)
|
for k, v := range entry.Logger.Hooks {
|
||||||
|
tmpHooks[k] = v
|
||||||
|
}
|
||||||
|
entry.Logger.mu.Unlock()
|
||||||
|
|
||||||
|
err := tmpHooks.Fire(entry.Level, entry)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry *Entry) write() {
|
func (entry *Entry) write() {
|
||||||
entry.Logger.mu.Lock()
|
|
||||||
defer entry.Logger.mu.Unlock()
|
|
||||||
serialized, err := entry.Logger.Formatter.Format(entry)
|
serialized, err := entry.Logger.Formatter.Format(entry)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
|
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err = entry.Logger.Out.Write(serialized); err != nil {
|
entry.Logger.mu.Lock()
|
||||||
|
defer entry.Logger.mu.Unlock()
|
||||||
|
if _, err := entry.Logger.Out.Write(serialized); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -323,7 +329,6 @@ func (entry *Entry) Fatal(args ...interface{}) {
|
|||||||
|
|
||||||
func (entry *Entry) Panic(args ...interface{}) {
|
func (entry *Entry) Panic(args ...interface{}) {
|
||||||
entry.Log(PanicLevel, args...)
|
entry.Log(PanicLevel, args...)
|
||||||
panic(fmt.Sprint(args...))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Entry Printf family functions
|
// Entry Printf family functions
|
||||||
|
45
vendor/github.com/sirupsen/logrus/exported.go
generated
vendored
45
vendor/github.com/sirupsen/logrus/exported.go
generated
vendored
@ -134,6 +134,51 @@ func Fatal(args ...interface{}) {
|
|||||||
std.Fatal(args...)
|
std.Fatal(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TraceFn logs a message from a func at level Trace on the standard logger.
|
||||||
|
func TraceFn(fn LogFunction) {
|
||||||
|
std.TraceFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DebugFn logs a message from a func at level Debug on the standard logger.
|
||||||
|
func DebugFn(fn LogFunction) {
|
||||||
|
std.DebugFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrintFn logs a message from a func at level Info on the standard logger.
|
||||||
|
func PrintFn(fn LogFunction) {
|
||||||
|
std.PrintFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InfoFn logs a message from a func at level Info on the standard logger.
|
||||||
|
func InfoFn(fn LogFunction) {
|
||||||
|
std.InfoFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WarnFn logs a message from a func at level Warn on the standard logger.
|
||||||
|
func WarnFn(fn LogFunction) {
|
||||||
|
std.WarnFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WarningFn logs a message from a func at level Warn on the standard logger.
|
||||||
|
func WarningFn(fn LogFunction) {
|
||||||
|
std.WarningFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorFn logs a message from a func at level Error on the standard logger.
|
||||||
|
func ErrorFn(fn LogFunction) {
|
||||||
|
std.ErrorFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PanicFn logs a message from a func at level Panic on the standard logger.
|
||||||
|
func PanicFn(fn LogFunction) {
|
||||||
|
std.PanicFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.
|
||||||
|
func FatalFn(fn LogFunction) {
|
||||||
|
std.FatalFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
// Tracef logs a message at level Trace on the standard logger.
|
// Tracef logs a message at level Trace on the standard logger.
|
||||||
func Tracef(format string, args ...interface{}) {
|
func Tracef(format string, args ...interface{}) {
|
||||||
std.Tracef(format, args...)
|
std.Tracef(format, args...)
|
||||||
|
11
vendor/github.com/sirupsen/logrus/go.mod
generated
vendored
11
vendor/github.com/sirupsen/logrus/go.mod
generated
vendored
@ -1,11 +0,0 @@
|
|||||||
module github.com/sirupsen/logrus
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
|
||||||
github.com/stretchr/testify v1.2.2
|
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894
|
|
||||||
)
|
|
||||||
|
|
||||||
go 1.13
|
|
12
vendor/github.com/sirupsen/logrus/go.sum
generated
vendored
12
vendor/github.com/sirupsen/logrus/go.sum
generated
vendored
@ -1,12 +0,0 @@
|
|||||||
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/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
|
||||||
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.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
|
||||||
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/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
5
vendor/github.com/sirupsen/logrus/json_formatter.go
generated
vendored
5
vendor/github.com/sirupsen/logrus/json_formatter.go
generated
vendored
@ -23,6 +23,9 @@ func (f FieldMap) resolve(key fieldKey) string {
|
|||||||
// JSONFormatter formats logs into parsable json
|
// JSONFormatter formats logs into parsable json
|
||||||
type JSONFormatter struct {
|
type JSONFormatter struct {
|
||||||
// TimestampFormat sets the format used for marshaling timestamps.
|
// TimestampFormat sets the format used for marshaling timestamps.
|
||||||
|
// The format to use is the same than for time.Format or time.Parse from the standard
|
||||||
|
// library.
|
||||||
|
// The standard Library already provides a set of predefined format.
|
||||||
TimestampFormat string
|
TimestampFormat string
|
||||||
|
|
||||||
// DisableTimestamp allows disabling automatic timestamps in output
|
// DisableTimestamp allows disabling automatic timestamps in output
|
||||||
@ -118,7 +121,7 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
|||||||
encoder.SetIndent("", " ")
|
encoder.SetIndent("", " ")
|
||||||
}
|
}
|
||||||
if err := encoder.Encode(data); err != nil {
|
if err := encoder.Encode(data); err != nil {
|
||||||
return nil, fmt.Errorf("failed to marshal fields to JSON, %v", err)
|
return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return b.Bytes(), nil
|
return b.Bytes(), nil
|
||||||
|
54
vendor/github.com/sirupsen/logrus/logger.go
generated
vendored
54
vendor/github.com/sirupsen/logrus/logger.go
generated
vendored
@ -9,6 +9,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// LogFunction For big messages, it can be more efficient to pass a function
|
||||||
|
// and only call it if the log level is actually enables rather than
|
||||||
|
// generating the log message and then checking if the level is enabled
|
||||||
|
type LogFunction func() []interface{}
|
||||||
|
|
||||||
type Logger struct {
|
type Logger struct {
|
||||||
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
|
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
|
||||||
// file, or leave it default which is `os.Stderr`. You can also set this to
|
// file, or leave it default which is `os.Stderr`. You can also set this to
|
||||||
@ -70,7 +75,7 @@ func (mw *MutexWrap) Disable() {
|
|||||||
//
|
//
|
||||||
// var log = &logrus.Logger{
|
// var log = &logrus.Logger{
|
||||||
// Out: os.Stderr,
|
// Out: os.Stderr,
|
||||||
// Formatter: new(logrus.JSONFormatter),
|
// Formatter: new(logrus.TextFormatter),
|
||||||
// Hooks: make(logrus.LevelHooks),
|
// Hooks: make(logrus.LevelHooks),
|
||||||
// Level: logrus.DebugLevel,
|
// Level: logrus.DebugLevel,
|
||||||
// }
|
// }
|
||||||
@ -195,6 +200,14 @@ func (logger *Logger) Log(level Level, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) LogFn(level Level, fn LogFunction) {
|
||||||
|
if logger.IsLevelEnabled(level) {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Log(level, fn()...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (logger *Logger) Trace(args ...interface{}) {
|
func (logger *Logger) Trace(args ...interface{}) {
|
||||||
logger.Log(TraceLevel, args...)
|
logger.Log(TraceLevel, args...)
|
||||||
}
|
}
|
||||||
@ -234,6 +247,45 @@ func (logger *Logger) Panic(args ...interface{}) {
|
|||||||
logger.Log(PanicLevel, args...)
|
logger.Log(PanicLevel, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) TraceFn(fn LogFunction) {
|
||||||
|
logger.LogFn(TraceLevel, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) DebugFn(fn LogFunction) {
|
||||||
|
logger.LogFn(DebugLevel, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) InfoFn(fn LogFunction) {
|
||||||
|
logger.LogFn(InfoLevel, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) PrintFn(fn LogFunction) {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Print(fn()...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) WarnFn(fn LogFunction) {
|
||||||
|
logger.LogFn(WarnLevel, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) WarningFn(fn LogFunction) {
|
||||||
|
logger.WarnFn(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) ErrorFn(fn LogFunction) {
|
||||||
|
logger.LogFn(ErrorLevel, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) FatalFn(fn LogFunction) {
|
||||||
|
logger.LogFn(FatalLevel, fn)
|
||||||
|
logger.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) PanicFn(fn LogFunction) {
|
||||||
|
logger.LogFn(PanicLevel, fn)
|
||||||
|
}
|
||||||
|
|
||||||
func (logger *Logger) Logln(level Level, args ...interface{}) {
|
func (logger *Logger) Logln(level Level, args ...interface{}) {
|
||||||
if logger.IsLevelEnabled(level) {
|
if logger.IsLevelEnabled(level) {
|
||||||
entry := logger.newEntry()
|
entry := logger.newEntry()
|
||||||
|
2
vendor/github.com/sirupsen/logrus/terminal_check_unix.go
generated
vendored
2
vendor/github.com/sirupsen/logrus/terminal_check_unix.go
generated
vendored
@ -1,4 +1,4 @@
|
|||||||
// +build linux aix
|
// +build linux aix zos
|
||||||
// +build !js
|
// +build !js
|
||||||
|
|
||||||
package logrus
|
package logrus
|
||||||
|
27
vendor/github.com/sirupsen/logrus/terminal_check_windows.go
generated
vendored
27
vendor/github.com/sirupsen/logrus/terminal_check_windows.go
generated
vendored
@ -5,30 +5,23 @@ package logrus
|
|||||||
import (
|
import (
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"syscall"
|
|
||||||
|
|
||||||
sequences "github.com/konsorten/go-windows-terminal-sequences"
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
func initTerminal(w io.Writer) {
|
|
||||||
switch v := w.(type) {
|
|
||||||
case *os.File:
|
|
||||||
sequences.EnableVirtualTerminalProcessing(syscall.Handle(v.Fd()), true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkIfTerminal(w io.Writer) bool {
|
func checkIfTerminal(w io.Writer) bool {
|
||||||
var ret bool
|
|
||||||
switch v := w.(type) {
|
switch v := w.(type) {
|
||||||
case *os.File:
|
case *os.File:
|
||||||
|
handle := windows.Handle(v.Fd())
|
||||||
var mode uint32
|
var mode uint32
|
||||||
err := syscall.GetConsoleMode(syscall.Handle(v.Fd()), &mode)
|
if err := windows.GetConsoleMode(handle, &mode); err != nil {
|
||||||
ret = (err == nil)
|
return false
|
||||||
default:
|
|
||||||
ret = false
|
|
||||||
}
|
}
|
||||||
if ret {
|
mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
||||||
initTerminal(w)
|
if err := windows.SetConsoleMode(handle, mode); err != nil {
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
return ret
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
7
vendor/github.com/sirupsen/logrus/text_formatter.go
generated
vendored
7
vendor/github.com/sirupsen/logrus/text_formatter.go
generated
vendored
@ -53,7 +53,10 @@ type TextFormatter struct {
|
|||||||
// the time passed since beginning of execution.
|
// the time passed since beginning of execution.
|
||||||
FullTimestamp bool
|
FullTimestamp bool
|
||||||
|
|
||||||
// TimestampFormat to use for display when a full timestamp is printed
|
// TimestampFormat to use for display when a full timestamp is printed.
|
||||||
|
// The format to use is the same than for time.Format or time.Parse from the standard
|
||||||
|
// library.
|
||||||
|
// The standard Library already provides a set of predefined format.
|
||||||
TimestampFormat string
|
TimestampFormat string
|
||||||
|
|
||||||
// The fields are sorted by default for a consistent output. For applications
|
// The fields are sorted by default for a consistent output. For applications
|
||||||
@ -235,6 +238,8 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin
|
|||||||
levelColor = yellow
|
levelColor = yellow
|
||||||
case ErrorLevel, FatalLevel, PanicLevel:
|
case ErrorLevel, FatalLevel, PanicLevel:
|
||||||
levelColor = red
|
levelColor = red
|
||||||
|
case InfoLevel:
|
||||||
|
levelColor = blue
|
||||||
default:
|
default:
|
||||||
levelColor = blue
|
levelColor = blue
|
||||||
}
|
}
|
||||||
|
106
vendor/golang.org/x/net/websocket/client.go
generated
vendored
106
vendor/golang.org/x/net/websocket/client.go
generated
vendored
@ -1,106 +0,0 @@
|
|||||||
// Copyright 2009 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package websocket
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DialError is an error that occurs while dialling a websocket server.
|
|
||||||
type DialError struct {
|
|
||||||
*Config
|
|
||||||
Err error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *DialError) Error() string {
|
|
||||||
return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewConfig creates a new WebSocket config for client connection.
|
|
||||||
func NewConfig(server, origin string) (config *Config, err error) {
|
|
||||||
config = new(Config)
|
|
||||||
config.Version = ProtocolVersionHybi13
|
|
||||||
config.Location, err = url.ParseRequestURI(server)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
config.Origin, err = url.ParseRequestURI(origin)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
config.Header = http.Header(make(map[string][]string))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewClient creates a new WebSocket client connection over rwc.
|
|
||||||
func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) {
|
|
||||||
br := bufio.NewReader(rwc)
|
|
||||||
bw := bufio.NewWriter(rwc)
|
|
||||||
err = hybiClientHandshake(config, br, bw)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
buf := bufio.NewReadWriter(br, bw)
|
|
||||||
ws = newHybiClientConn(config, buf, rwc)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dial opens a new client connection to a WebSocket.
|
|
||||||
func Dial(url_, protocol, origin string) (ws *Conn, err error) {
|
|
||||||
config, err := NewConfig(url_, origin)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if protocol != "" {
|
|
||||||
config.Protocol = []string{protocol}
|
|
||||||
}
|
|
||||||
return DialConfig(config)
|
|
||||||
}
|
|
||||||
|
|
||||||
var portMap = map[string]string{
|
|
||||||
"ws": "80",
|
|
||||||
"wss": "443",
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseAuthority(location *url.URL) string {
|
|
||||||
if _, ok := portMap[location.Scheme]; ok {
|
|
||||||
if _, _, err := net.SplitHostPort(location.Host); err != nil {
|
|
||||||
return net.JoinHostPort(location.Host, portMap[location.Scheme])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return location.Host
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialConfig opens a new client connection to a WebSocket with a config.
|
|
||||||
func DialConfig(config *Config) (ws *Conn, err error) {
|
|
||||||
var client net.Conn
|
|
||||||
if config.Location == nil {
|
|
||||||
return nil, &DialError{config, ErrBadWebSocketLocation}
|
|
||||||
}
|
|
||||||
if config.Origin == nil {
|
|
||||||
return nil, &DialError{config, ErrBadWebSocketOrigin}
|
|
||||||
}
|
|
||||||
dialer := config.Dialer
|
|
||||||
if dialer == nil {
|
|
||||||
dialer = &net.Dialer{}
|
|
||||||
}
|
|
||||||
client, err = dialWithDialer(dialer, config)
|
|
||||||
if err != nil {
|
|
||||||
goto Error
|
|
||||||
}
|
|
||||||
ws, err = NewClient(config, client)
|
|
||||||
if err != nil {
|
|
||||||
client.Close()
|
|
||||||
goto Error
|
|
||||||
}
|
|
||||||
return
|
|
||||||
|
|
||||||
Error:
|
|
||||||
return nil, &DialError{config, err}
|
|
||||||
}
|
|
24
vendor/golang.org/x/net/websocket/dial.go
generated
vendored
24
vendor/golang.org/x/net/websocket/dial.go
generated
vendored
@ -1,24 +0,0 @@
|
|||||||
// Copyright 2015 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package websocket
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) {
|
|
||||||
switch config.Location.Scheme {
|
|
||||||
case "ws":
|
|
||||||
conn, err = dialer.Dial("tcp", parseAuthority(config.Location))
|
|
||||||
|
|
||||||
case "wss":
|
|
||||||
conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig)
|
|
||||||
|
|
||||||
default:
|
|
||||||
err = ErrBadScheme
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
583
vendor/golang.org/x/net/websocket/hybi.go
generated
vendored
583
vendor/golang.org/x/net/websocket/hybi.go
generated
vendored
@ -1,583 +0,0 @@
|
|||||||
// Copyright 2011 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package websocket
|
|
||||||
|
|
||||||
// This file implements a protocol of hybi draft.
|
|
||||||
// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"bytes"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha1"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
||||||
|
|
||||||
closeStatusNormal = 1000
|
|
||||||
closeStatusGoingAway = 1001
|
|
||||||
closeStatusProtocolError = 1002
|
|
||||||
closeStatusUnsupportedData = 1003
|
|
||||||
closeStatusFrameTooLarge = 1004
|
|
||||||
closeStatusNoStatusRcvd = 1005
|
|
||||||
closeStatusAbnormalClosure = 1006
|
|
||||||
closeStatusBadMessageData = 1007
|
|
||||||
closeStatusPolicyViolation = 1008
|
|
||||||
closeStatusTooBigData = 1009
|
|
||||||
closeStatusExtensionMismatch = 1010
|
|
||||||
|
|
||||||
maxControlFramePayloadLength = 125
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrBadMaskingKey = &ProtocolError{"bad masking key"}
|
|
||||||
ErrBadPongMessage = &ProtocolError{"bad pong message"}
|
|
||||||
ErrBadClosingStatus = &ProtocolError{"bad closing status"}
|
|
||||||
ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"}
|
|
||||||
ErrNotImplemented = &ProtocolError{"not implemented"}
|
|
||||||
|
|
||||||
handshakeHeader = map[string]bool{
|
|
||||||
"Host": true,
|
|
||||||
"Upgrade": true,
|
|
||||||
"Connection": true,
|
|
||||||
"Sec-Websocket-Key": true,
|
|
||||||
"Sec-Websocket-Origin": true,
|
|
||||||
"Sec-Websocket-Version": true,
|
|
||||||
"Sec-Websocket-Protocol": true,
|
|
||||||
"Sec-Websocket-Accept": true,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// A hybiFrameHeader is a frame header as defined in hybi draft.
|
|
||||||
type hybiFrameHeader struct {
|
|
||||||
Fin bool
|
|
||||||
Rsv [3]bool
|
|
||||||
OpCode byte
|
|
||||||
Length int64
|
|
||||||
MaskingKey []byte
|
|
||||||
|
|
||||||
data *bytes.Buffer
|
|
||||||
}
|
|
||||||
|
|
||||||
// A hybiFrameReader is a reader for hybi frame.
|
|
||||||
type hybiFrameReader struct {
|
|
||||||
reader io.Reader
|
|
||||||
|
|
||||||
header hybiFrameHeader
|
|
||||||
pos int64
|
|
||||||
length int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) {
|
|
||||||
n, err = frame.reader.Read(msg)
|
|
||||||
if frame.header.MaskingKey != nil {
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4]
|
|
||||||
frame.pos++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (frame *hybiFrameReader) PayloadType() byte { return frame.header.OpCode }
|
|
||||||
|
|
||||||
func (frame *hybiFrameReader) HeaderReader() io.Reader {
|
|
||||||
if frame.header.data == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if frame.header.data.Len() == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return frame.header.data
|
|
||||||
}
|
|
||||||
|
|
||||||
func (frame *hybiFrameReader) TrailerReader() io.Reader { return nil }
|
|
||||||
|
|
||||||
func (frame *hybiFrameReader) Len() (n int) { return frame.length }
|
|
||||||
|
|
||||||
// A hybiFrameReaderFactory creates new frame reader based on its frame type.
|
|
||||||
type hybiFrameReaderFactory struct {
|
|
||||||
*bufio.Reader
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewFrameReader reads a frame header from the connection, and creates new reader for the frame.
|
|
||||||
// See Section 5.2 Base Framing protocol for detail.
|
|
||||||
// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2
|
|
||||||
func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) {
|
|
||||||
hybiFrame := new(hybiFrameReader)
|
|
||||||
frame = hybiFrame
|
|
||||||
var header []byte
|
|
||||||
var b byte
|
|
||||||
// First byte. FIN/RSV1/RSV2/RSV3/OpCode(4bits)
|
|
||||||
b, err = buf.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
header = append(header, b)
|
|
||||||
hybiFrame.header.Fin = ((header[0] >> 7) & 1) != 0
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
j := uint(6 - i)
|
|
||||||
hybiFrame.header.Rsv[i] = ((header[0] >> j) & 1) != 0
|
|
||||||
}
|
|
||||||
hybiFrame.header.OpCode = header[0] & 0x0f
|
|
||||||
|
|
||||||
// Second byte. Mask/Payload len(7bits)
|
|
||||||
b, err = buf.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
header = append(header, b)
|
|
||||||
mask := (b & 0x80) != 0
|
|
||||||
b &= 0x7f
|
|
||||||
lengthFields := 0
|
|
||||||
switch {
|
|
||||||
case b <= 125: // Payload length 7bits.
|
|
||||||
hybiFrame.header.Length = int64(b)
|
|
||||||
case b == 126: // Payload length 7+16bits
|
|
||||||
lengthFields = 2
|
|
||||||
case b == 127: // Payload length 7+64bits
|
|
||||||
lengthFields = 8
|
|
||||||
}
|
|
||||||
for i := 0; i < lengthFields; i++ {
|
|
||||||
b, err = buf.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if lengthFields == 8 && i == 0 { // MSB must be zero when 7+64 bits
|
|
||||||
b &= 0x7f
|
|
||||||
}
|
|
||||||
header = append(header, b)
|
|
||||||
hybiFrame.header.Length = hybiFrame.header.Length*256 + int64(b)
|
|
||||||
}
|
|
||||||
if mask {
|
|
||||||
// Masking key. 4 bytes.
|
|
||||||
for i := 0; i < 4; i++ {
|
|
||||||
b, err = buf.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
header = append(header, b)
|
|
||||||
hybiFrame.header.MaskingKey = append(hybiFrame.header.MaskingKey, b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
hybiFrame.reader = io.LimitReader(buf.Reader, hybiFrame.header.Length)
|
|
||||||
hybiFrame.header.data = bytes.NewBuffer(header)
|
|
||||||
hybiFrame.length = len(header) + int(hybiFrame.header.Length)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HybiFrameWriter is a writer for hybi frame.
|
|
||||||
type hybiFrameWriter struct {
|
|
||||||
writer *bufio.Writer
|
|
||||||
|
|
||||||
header *hybiFrameHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) {
|
|
||||||
var header []byte
|
|
||||||
var b byte
|
|
||||||
if frame.header.Fin {
|
|
||||||
b |= 0x80
|
|
||||||
}
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
if frame.header.Rsv[i] {
|
|
||||||
j := uint(6 - i)
|
|
||||||
b |= 1 << j
|
|
||||||
}
|
|
||||||
}
|
|
||||||
b |= frame.header.OpCode
|
|
||||||
header = append(header, b)
|
|
||||||
if frame.header.MaskingKey != nil {
|
|
||||||
b = 0x80
|
|
||||||
} else {
|
|
||||||
b = 0
|
|
||||||
}
|
|
||||||
lengthFields := 0
|
|
||||||
length := len(msg)
|
|
||||||
switch {
|
|
||||||
case length <= 125:
|
|
||||||
b |= byte(length)
|
|
||||||
case length < 65536:
|
|
||||||
b |= 126
|
|
||||||
lengthFields = 2
|
|
||||||
default:
|
|
||||||
b |= 127
|
|
||||||
lengthFields = 8
|
|
||||||
}
|
|
||||||
header = append(header, b)
|
|
||||||
for i := 0; i < lengthFields; i++ {
|
|
||||||
j := uint((lengthFields - i - 1) * 8)
|
|
||||||
b = byte((length >> j) & 0xff)
|
|
||||||
header = append(header, b)
|
|
||||||
}
|
|
||||||
if frame.header.MaskingKey != nil {
|
|
||||||
if len(frame.header.MaskingKey) != 4 {
|
|
||||||
return 0, ErrBadMaskingKey
|
|
||||||
}
|
|
||||||
header = append(header, frame.header.MaskingKey...)
|
|
||||||
frame.writer.Write(header)
|
|
||||||
data := make([]byte, length)
|
|
||||||
for i := range data {
|
|
||||||
data[i] = msg[i] ^ frame.header.MaskingKey[i%4]
|
|
||||||
}
|
|
||||||
frame.writer.Write(data)
|
|
||||||
err = frame.writer.Flush()
|
|
||||||
return length, err
|
|
||||||
}
|
|
||||||
frame.writer.Write(header)
|
|
||||||
frame.writer.Write(msg)
|
|
||||||
err = frame.writer.Flush()
|
|
||||||
return length, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (frame *hybiFrameWriter) Close() error { return nil }
|
|
||||||
|
|
||||||
type hybiFrameWriterFactory struct {
|
|
||||||
*bufio.Writer
|
|
||||||
needMaskingKey bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) {
|
|
||||||
frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType}
|
|
||||||
if buf.needMaskingKey {
|
|
||||||
frameHeader.MaskingKey, err = generateMaskingKey()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &hybiFrameWriter{writer: buf.Writer, header: frameHeader}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type hybiFrameHandler struct {
|
|
||||||
conn *Conn
|
|
||||||
payloadType byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, error) {
|
|
||||||
if handler.conn.IsServerConn() {
|
|
||||||
// The client MUST mask all frames sent to the server.
|
|
||||||
if frame.(*hybiFrameReader).header.MaskingKey == nil {
|
|
||||||
handler.WriteClose(closeStatusProtocolError)
|
|
||||||
return nil, io.EOF
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// The server MUST NOT mask all frames.
|
|
||||||
if frame.(*hybiFrameReader).header.MaskingKey != nil {
|
|
||||||
handler.WriteClose(closeStatusProtocolError)
|
|
||||||
return nil, io.EOF
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if header := frame.HeaderReader(); header != nil {
|
|
||||||
io.Copy(ioutil.Discard, header)
|
|
||||||
}
|
|
||||||
switch frame.PayloadType() {
|
|
||||||
case ContinuationFrame:
|
|
||||||
frame.(*hybiFrameReader).header.OpCode = handler.payloadType
|
|
||||||
case TextFrame, BinaryFrame:
|
|
||||||
handler.payloadType = frame.PayloadType()
|
|
||||||
case CloseFrame:
|
|
||||||
return nil, io.EOF
|
|
||||||
case PingFrame, PongFrame:
|
|
||||||
b := make([]byte, maxControlFramePayloadLength)
|
|
||||||
n, err := io.ReadFull(frame, b)
|
|
||||||
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
io.Copy(ioutil.Discard, frame)
|
|
||||||
if frame.PayloadType() == PingFrame {
|
|
||||||
if _, err := handler.WritePong(b[:n]); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return frame, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (handler *hybiFrameHandler) WriteClose(status int) (err error) {
|
|
||||||
handler.conn.wio.Lock()
|
|
||||||
defer handler.conn.wio.Unlock()
|
|
||||||
w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
msg := make([]byte, 2)
|
|
||||||
binary.BigEndian.PutUint16(msg, uint16(status))
|
|
||||||
_, err = w.Write(msg)
|
|
||||||
w.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) {
|
|
||||||
handler.conn.wio.Lock()
|
|
||||||
defer handler.conn.wio.Unlock()
|
|
||||||
w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err = w.Write(msg)
|
|
||||||
w.Close()
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// newHybiConn creates a new WebSocket connection speaking hybi draft protocol.
|
|
||||||
func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn {
|
|
||||||
if buf == nil {
|
|
||||||
br := bufio.NewReader(rwc)
|
|
||||||
bw := bufio.NewWriter(rwc)
|
|
||||||
buf = bufio.NewReadWriter(br, bw)
|
|
||||||
}
|
|
||||||
ws := &Conn{config: config, request: request, buf: buf, rwc: rwc,
|
|
||||||
frameReaderFactory: hybiFrameReaderFactory{buf.Reader},
|
|
||||||
frameWriterFactory: hybiFrameWriterFactory{
|
|
||||||
buf.Writer, request == nil},
|
|
||||||
PayloadType: TextFrame,
|
|
||||||
defaultCloseStatus: closeStatusNormal}
|
|
||||||
ws.frameHandler = &hybiFrameHandler{conn: ws}
|
|
||||||
return ws
|
|
||||||
}
|
|
||||||
|
|
||||||
// generateMaskingKey generates a masking key for a frame.
|
|
||||||
func generateMaskingKey() (maskingKey []byte, err error) {
|
|
||||||
maskingKey = make([]byte, 4)
|
|
||||||
if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// generateNonce generates a nonce consisting of a randomly selected 16-byte
|
|
||||||
// value that has been base64-encoded.
|
|
||||||
func generateNonce() (nonce []byte) {
|
|
||||||
key := make([]byte, 16)
|
|
||||||
if _, err := io.ReadFull(rand.Reader, key); err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
nonce = make([]byte, 24)
|
|
||||||
base64.StdEncoding.Encode(nonce, key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// removeZone removes IPv6 zone identifer from host.
|
|
||||||
// E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"
|
|
||||||
func removeZone(host string) string {
|
|
||||||
if !strings.HasPrefix(host, "[") {
|
|
||||||
return host
|
|
||||||
}
|
|
||||||
i := strings.LastIndex(host, "]")
|
|
||||||
if i < 0 {
|
|
||||||
return host
|
|
||||||
}
|
|
||||||
j := strings.LastIndex(host[:i], "%")
|
|
||||||
if j < 0 {
|
|
||||||
return host
|
|
||||||
}
|
|
||||||
return host[:j] + host[i:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// getNonceAccept computes the base64-encoded SHA-1 of the concatenation of
|
|
||||||
// the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string.
|
|
||||||
func getNonceAccept(nonce []byte) (expected []byte, err error) {
|
|
||||||
h := sha1.New()
|
|
||||||
if _, err = h.Write(nonce); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if _, err = h.Write([]byte(websocketGUID)); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expected = make([]byte, 28)
|
|
||||||
base64.StdEncoding.Encode(expected, h.Sum(nil))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client handshake described in draft-ietf-hybi-thewebsocket-protocol-17
|
|
||||||
func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) {
|
|
||||||
bw.WriteString("GET " + config.Location.RequestURI() + " HTTP/1.1\r\n")
|
|
||||||
|
|
||||||
// According to RFC 6874, an HTTP client, proxy, or other
|
|
||||||
// intermediary must remove any IPv6 zone identifier attached
|
|
||||||
// to an outgoing URI.
|
|
||||||
bw.WriteString("Host: " + removeZone(config.Location.Host) + "\r\n")
|
|
||||||
bw.WriteString("Upgrade: websocket\r\n")
|
|
||||||
bw.WriteString("Connection: Upgrade\r\n")
|
|
||||||
nonce := generateNonce()
|
|
||||||
if config.handshakeData != nil {
|
|
||||||
nonce = []byte(config.handshakeData["key"])
|
|
||||||
}
|
|
||||||
bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n")
|
|
||||||
bw.WriteString("Origin: " + strings.ToLower(config.Origin.String()) + "\r\n")
|
|
||||||
|
|
||||||
if config.Version != ProtocolVersionHybi13 {
|
|
||||||
return ErrBadProtocolVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
bw.WriteString("Sec-WebSocket-Version: " + fmt.Sprintf("%d", config.Version) + "\r\n")
|
|
||||||
if len(config.Protocol) > 0 {
|
|
||||||
bw.WriteString("Sec-WebSocket-Protocol: " + strings.Join(config.Protocol, ", ") + "\r\n")
|
|
||||||
}
|
|
||||||
// TODO(ukai): send Sec-WebSocket-Extensions.
|
|
||||||
err = config.Header.WriteSubset(bw, handshakeHeader)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
bw.WriteString("\r\n")
|
|
||||||
if err = bw.Flush(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := http.ReadResponse(br, &http.Request{Method: "GET"})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if resp.StatusCode != 101 {
|
|
||||||
return ErrBadStatus
|
|
||||||
}
|
|
||||||
if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" ||
|
|
||||||
strings.ToLower(resp.Header.Get("Connection")) != "upgrade" {
|
|
||||||
return ErrBadUpgrade
|
|
||||||
}
|
|
||||||
expectedAccept, err := getNonceAccept(nonce)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if resp.Header.Get("Sec-WebSocket-Accept") != string(expectedAccept) {
|
|
||||||
return ErrChallengeResponse
|
|
||||||
}
|
|
||||||
if resp.Header.Get("Sec-WebSocket-Extensions") != "" {
|
|
||||||
return ErrUnsupportedExtensions
|
|
||||||
}
|
|
||||||
offeredProtocol := resp.Header.Get("Sec-WebSocket-Protocol")
|
|
||||||
if offeredProtocol != "" {
|
|
||||||
protocolMatched := false
|
|
||||||
for i := 0; i < len(config.Protocol); i++ {
|
|
||||||
if config.Protocol[i] == offeredProtocol {
|
|
||||||
protocolMatched = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !protocolMatched {
|
|
||||||
return ErrBadWebSocketProtocol
|
|
||||||
}
|
|
||||||
config.Protocol = []string{offeredProtocol}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// newHybiClientConn creates a client WebSocket connection after handshake.
|
|
||||||
func newHybiClientConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser) *Conn {
|
|
||||||
return newHybiConn(config, buf, rwc, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HybiServerHandshaker performs a server handshake using hybi draft protocol.
|
|
||||||
type hybiServerHandshaker struct {
|
|
||||||
*Config
|
|
||||||
accept []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
|
|
||||||
c.Version = ProtocolVersionHybi13
|
|
||||||
if req.Method != "GET" {
|
|
||||||
return http.StatusMethodNotAllowed, ErrBadRequestMethod
|
|
||||||
}
|
|
||||||
// HTTP version can be safely ignored.
|
|
||||||
|
|
||||||
if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" ||
|
|
||||||
!strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") {
|
|
||||||
return http.StatusBadRequest, ErrNotWebSocket
|
|
||||||
}
|
|
||||||
|
|
||||||
key := req.Header.Get("Sec-Websocket-Key")
|
|
||||||
if key == "" {
|
|
||||||
return http.StatusBadRequest, ErrChallengeResponse
|
|
||||||
}
|
|
||||||
version := req.Header.Get("Sec-Websocket-Version")
|
|
||||||
switch version {
|
|
||||||
case "13":
|
|
||||||
c.Version = ProtocolVersionHybi13
|
|
||||||
default:
|
|
||||||
return http.StatusBadRequest, ErrBadWebSocketVersion
|
|
||||||
}
|
|
||||||
var scheme string
|
|
||||||
if req.TLS != nil {
|
|
||||||
scheme = "wss"
|
|
||||||
} else {
|
|
||||||
scheme = "ws"
|
|
||||||
}
|
|
||||||
c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI())
|
|
||||||
if err != nil {
|
|
||||||
return http.StatusBadRequest, err
|
|
||||||
}
|
|
||||||
protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol"))
|
|
||||||
if protocol != "" {
|
|
||||||
protocols := strings.Split(protocol, ",")
|
|
||||||
for i := 0; i < len(protocols); i++ {
|
|
||||||
c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.accept, err = getNonceAccept([]byte(key))
|
|
||||||
if err != nil {
|
|
||||||
return http.StatusInternalServerError, err
|
|
||||||
}
|
|
||||||
return http.StatusSwitchingProtocols, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Origin parses the Origin header in req.
|
|
||||||
// If the Origin header is not set, it returns nil and nil.
|
|
||||||
func Origin(config *Config, req *http.Request) (*url.URL, error) {
|
|
||||||
var origin string
|
|
||||||
switch config.Version {
|
|
||||||
case ProtocolVersionHybi13:
|
|
||||||
origin = req.Header.Get("Origin")
|
|
||||||
}
|
|
||||||
if origin == "" {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return url.ParseRequestURI(origin)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) {
|
|
||||||
if len(c.Protocol) > 0 {
|
|
||||||
if len(c.Protocol) != 1 {
|
|
||||||
// You need choose a Protocol in Handshake func in Server.
|
|
||||||
return ErrBadWebSocketProtocol
|
|
||||||
}
|
|
||||||
}
|
|
||||||
buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n")
|
|
||||||
buf.WriteString("Upgrade: websocket\r\n")
|
|
||||||
buf.WriteString("Connection: Upgrade\r\n")
|
|
||||||
buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n")
|
|
||||||
if len(c.Protocol) > 0 {
|
|
||||||
buf.WriteString("Sec-WebSocket-Protocol: " + c.Protocol[0] + "\r\n")
|
|
||||||
}
|
|
||||||
// TODO(ukai): send Sec-WebSocket-Extensions.
|
|
||||||
if c.Header != nil {
|
|
||||||
err := c.Header.WriteSubset(buf, handshakeHeader)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
return buf.Flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *hybiServerHandshaker) NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn {
|
|
||||||
return newHybiServerConn(c.Config, buf, rwc, request)
|
|
||||||
}
|
|
||||||
|
|
||||||
// newHybiServerConn returns a new WebSocket connection speaking hybi draft protocol.
|
|
||||||
func newHybiServerConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn {
|
|
||||||
return newHybiConn(config, buf, rwc, request)
|
|
||||||
}
|
|
113
vendor/golang.org/x/net/websocket/server.go
generated
vendored
113
vendor/golang.org/x/net/websocket/server.go
generated
vendored
@ -1,113 +0,0 @@
|
|||||||
// Copyright 2009 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package websocket
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) {
|
|
||||||
var hs serverHandshaker = &hybiServerHandshaker{Config: config}
|
|
||||||
code, err := hs.ReadHandshake(buf.Reader, req)
|
|
||||||
if err == ErrBadWebSocketVersion {
|
|
||||||
fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
|
|
||||||
fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
buf.WriteString(err.Error())
|
|
||||||
buf.Flush()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
buf.WriteString(err.Error())
|
|
||||||
buf.Flush()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if handshake != nil {
|
|
||||||
err = handshake(config, req)
|
|
||||||
if err != nil {
|
|
||||||
code = http.StatusForbidden
|
|
||||||
fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
buf.Flush()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = hs.AcceptHandshake(buf.Writer)
|
|
||||||
if err != nil {
|
|
||||||
code = http.StatusBadRequest
|
|
||||||
fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
buf.Flush()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
conn = hs.NewServerConn(buf, rwc, req)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server represents a server of a WebSocket.
|
|
||||||
type Server struct {
|
|
||||||
// Config is a WebSocket configuration for new WebSocket connection.
|
|
||||||
Config
|
|
||||||
|
|
||||||
// Handshake is an optional function in WebSocket handshake.
|
|
||||||
// For example, you can check, or don't check Origin header.
|
|
||||||
// Another example, you can select config.Protocol.
|
|
||||||
Handshake func(*Config, *http.Request) error
|
|
||||||
|
|
||||||
// Handler handles a WebSocket connection.
|
|
||||||
Handler
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServeHTTP implements the http.Handler interface for a WebSocket
|
|
||||||
func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
s.serveWebSocket(w, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) {
|
|
||||||
rwc, buf, err := w.(http.Hijacker).Hijack()
|
|
||||||
if err != nil {
|
|
||||||
panic("Hijack failed: " + err.Error())
|
|
||||||
}
|
|
||||||
// The server should abort the WebSocket connection if it finds
|
|
||||||
// the client did not send a handshake that matches with protocol
|
|
||||||
// specification.
|
|
||||||
defer rwc.Close()
|
|
||||||
conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if conn == nil {
|
|
||||||
panic("unexpected nil conn")
|
|
||||||
}
|
|
||||||
s.Handler(conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handler is a simple interface to a WebSocket browser client.
|
|
||||||
// It checks if Origin header is valid URL by default.
|
|
||||||
// You might want to verify websocket.Conn.Config().Origin in the func.
|
|
||||||
// If you use Server instead of Handler, you could call websocket.Origin and
|
|
||||||
// check the origin in your Handshake func. So, if you want to accept
|
|
||||||
// non-browser clients, which do not send an Origin header, set a
|
|
||||||
// Server.Handshake that does not check the origin.
|
|
||||||
type Handler func(*Conn)
|
|
||||||
|
|
||||||
func checkOrigin(config *Config, req *http.Request) (err error) {
|
|
||||||
config.Origin, err = Origin(config, req)
|
|
||||||
if err == nil && config.Origin == nil {
|
|
||||||
return fmt.Errorf("null origin")
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServeHTTP implements the http.Handler interface for a WebSocket
|
|
||||||
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
s := Server{Handler: h, Handshake: checkOrigin}
|
|
||||||
s.serveWebSocket(w, req)
|
|
||||||
}
|
|
451
vendor/golang.org/x/net/websocket/websocket.go
generated
vendored
451
vendor/golang.org/x/net/websocket/websocket.go
generated
vendored
@ -1,451 +0,0 @@
|
|||||||
// Copyright 2009 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// Package websocket implements a client and server for the WebSocket protocol
|
|
||||||
// as specified in RFC 6455.
|
|
||||||
//
|
|
||||||
// This package currently lacks some features found in alternative
|
|
||||||
// and more actively maintained WebSocket packages:
|
|
||||||
//
|
|
||||||
// https://godoc.org/github.com/gorilla/websocket
|
|
||||||
// https://godoc.org/nhooyr.io/websocket
|
|
||||||
package websocket // import "golang.org/x/net/websocket"
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
ProtocolVersionHybi13 = 13
|
|
||||||
ProtocolVersionHybi = ProtocolVersionHybi13
|
|
||||||
SupportedProtocolVersion = "13"
|
|
||||||
|
|
||||||
ContinuationFrame = 0
|
|
||||||
TextFrame = 1
|
|
||||||
BinaryFrame = 2
|
|
||||||
CloseFrame = 8
|
|
||||||
PingFrame = 9
|
|
||||||
PongFrame = 10
|
|
||||||
UnknownFrame = 255
|
|
||||||
|
|
||||||
DefaultMaxPayloadBytes = 32 << 20 // 32MB
|
|
||||||
)
|
|
||||||
|
|
||||||
// ProtocolError represents WebSocket protocol errors.
|
|
||||||
type ProtocolError struct {
|
|
||||||
ErrorString string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (err *ProtocolError) Error() string { return err.ErrorString }
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrBadProtocolVersion = &ProtocolError{"bad protocol version"}
|
|
||||||
ErrBadScheme = &ProtocolError{"bad scheme"}
|
|
||||||
ErrBadStatus = &ProtocolError{"bad status"}
|
|
||||||
ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"}
|
|
||||||
ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"}
|
|
||||||
ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"}
|
|
||||||
ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"}
|
|
||||||
ErrBadWebSocketVersion = &ProtocolError{"missing or bad WebSocket Version"}
|
|
||||||
ErrChallengeResponse = &ProtocolError{"mismatch challenge/response"}
|
|
||||||
ErrBadFrame = &ProtocolError{"bad frame"}
|
|
||||||
ErrBadFrameBoundary = &ProtocolError{"not on frame boundary"}
|
|
||||||
ErrNotWebSocket = &ProtocolError{"not websocket protocol"}
|
|
||||||
ErrBadRequestMethod = &ProtocolError{"bad method"}
|
|
||||||
ErrNotSupported = &ProtocolError{"not supported"}
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrFrameTooLarge is returned by Codec's Receive method if payload size
|
|
||||||
// exceeds limit set by Conn.MaxPayloadBytes
|
|
||||||
var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit")
|
|
||||||
|
|
||||||
// Addr is an implementation of net.Addr for WebSocket.
|
|
||||||
type Addr struct {
|
|
||||||
*url.URL
|
|
||||||
}
|
|
||||||
|
|
||||||
// Network returns the network type for a WebSocket, "websocket".
|
|
||||||
func (addr *Addr) Network() string { return "websocket" }
|
|
||||||
|
|
||||||
// Config is a WebSocket configuration
|
|
||||||
type Config struct {
|
|
||||||
// A WebSocket server address.
|
|
||||||
Location *url.URL
|
|
||||||
|
|
||||||
// A Websocket client origin.
|
|
||||||
Origin *url.URL
|
|
||||||
|
|
||||||
// WebSocket subprotocols.
|
|
||||||
Protocol []string
|
|
||||||
|
|
||||||
// WebSocket protocol version.
|
|
||||||
Version int
|
|
||||||
|
|
||||||
// TLS config for secure WebSocket (wss).
|
|
||||||
TlsConfig *tls.Config
|
|
||||||
|
|
||||||
// Additional header fields to be sent in WebSocket opening handshake.
|
|
||||||
Header http.Header
|
|
||||||
|
|
||||||
// Dialer used when opening websocket connections.
|
|
||||||
Dialer *net.Dialer
|
|
||||||
|
|
||||||
handshakeData map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
// serverHandshaker is an interface to handle WebSocket server side handshake.
|
|
||||||
type serverHandshaker interface {
|
|
||||||
// ReadHandshake reads handshake request message from client.
|
|
||||||
// Returns http response code and error if any.
|
|
||||||
ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error)
|
|
||||||
|
|
||||||
// AcceptHandshake accepts the client handshake request and sends
|
|
||||||
// handshake response back to client.
|
|
||||||
AcceptHandshake(buf *bufio.Writer) (err error)
|
|
||||||
|
|
||||||
// NewServerConn creates a new WebSocket connection.
|
|
||||||
NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// frameReader is an interface to read a WebSocket frame.
|
|
||||||
type frameReader interface {
|
|
||||||
// Reader is to read payload of the frame.
|
|
||||||
io.Reader
|
|
||||||
|
|
||||||
// PayloadType returns payload type.
|
|
||||||
PayloadType() byte
|
|
||||||
|
|
||||||
// HeaderReader returns a reader to read header of the frame.
|
|
||||||
HeaderReader() io.Reader
|
|
||||||
|
|
||||||
// TrailerReader returns a reader to read trailer of the frame.
|
|
||||||
// If it returns nil, there is no trailer in the frame.
|
|
||||||
TrailerReader() io.Reader
|
|
||||||
|
|
||||||
// Len returns total length of the frame, including header and trailer.
|
|
||||||
Len() int
|
|
||||||
}
|
|
||||||
|
|
||||||
// frameReaderFactory is an interface to creates new frame reader.
|
|
||||||
type frameReaderFactory interface {
|
|
||||||
NewFrameReader() (r frameReader, err error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// frameWriter is an interface to write a WebSocket frame.
|
|
||||||
type frameWriter interface {
|
|
||||||
// Writer is to write payload of the frame.
|
|
||||||
io.WriteCloser
|
|
||||||
}
|
|
||||||
|
|
||||||
// frameWriterFactory is an interface to create new frame writer.
|
|
||||||
type frameWriterFactory interface {
|
|
||||||
NewFrameWriter(payloadType byte) (w frameWriter, err error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type frameHandler interface {
|
|
||||||
HandleFrame(frame frameReader) (r frameReader, err error)
|
|
||||||
WriteClose(status int) (err error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Conn represents a WebSocket connection.
|
|
||||||
//
|
|
||||||
// Multiple goroutines may invoke methods on a Conn simultaneously.
|
|
||||||
type Conn struct {
|
|
||||||
config *Config
|
|
||||||
request *http.Request
|
|
||||||
|
|
||||||
buf *bufio.ReadWriter
|
|
||||||
rwc io.ReadWriteCloser
|
|
||||||
|
|
||||||
rio sync.Mutex
|
|
||||||
frameReaderFactory
|
|
||||||
frameReader
|
|
||||||
|
|
||||||
wio sync.Mutex
|
|
||||||
frameWriterFactory
|
|
||||||
|
|
||||||
frameHandler
|
|
||||||
PayloadType byte
|
|
||||||
defaultCloseStatus int
|
|
||||||
|
|
||||||
// MaxPayloadBytes limits the size of frame payload received over Conn
|
|
||||||
// by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used.
|
|
||||||
MaxPayloadBytes int
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read implements the io.Reader interface:
|
|
||||||
// it reads data of a frame from the WebSocket connection.
|
|
||||||
// if msg is not large enough for the frame data, it fills the msg and next Read
|
|
||||||
// will read the rest of the frame data.
|
|
||||||
// it reads Text frame or Binary frame.
|
|
||||||
func (ws *Conn) Read(msg []byte) (n int, err error) {
|
|
||||||
ws.rio.Lock()
|
|
||||||
defer ws.rio.Unlock()
|
|
||||||
again:
|
|
||||||
if ws.frameReader == nil {
|
|
||||||
frame, err := ws.frameReaderFactory.NewFrameReader()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
ws.frameReader, err = ws.frameHandler.HandleFrame(frame)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
if ws.frameReader == nil {
|
|
||||||
goto again
|
|
||||||
}
|
|
||||||
}
|
|
||||||
n, err = ws.frameReader.Read(msg)
|
|
||||||
if err == io.EOF {
|
|
||||||
if trailer := ws.frameReader.TrailerReader(); trailer != nil {
|
|
||||||
io.Copy(ioutil.Discard, trailer)
|
|
||||||
}
|
|
||||||
ws.frameReader = nil
|
|
||||||
goto again
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write implements the io.Writer interface:
|
|
||||||
// it writes data as a frame to the WebSocket connection.
|
|
||||||
func (ws *Conn) Write(msg []byte) (n int, err error) {
|
|
||||||
ws.wio.Lock()
|
|
||||||
defer ws.wio.Unlock()
|
|
||||||
w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err = w.Write(msg)
|
|
||||||
w.Close()
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close implements the io.Closer interface.
|
|
||||||
func (ws *Conn) Close() error {
|
|
||||||
err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
|
|
||||||
err1 := ws.rwc.Close()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return err1
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsClientConn reports whether ws is a client-side connection.
|
|
||||||
func (ws *Conn) IsClientConn() bool { return ws.request == nil }
|
|
||||||
|
|
||||||
// IsServerConn reports whether ws is a server-side connection.
|
|
||||||
func (ws *Conn) IsServerConn() bool { return ws.request != nil }
|
|
||||||
|
|
||||||
// LocalAddr returns the WebSocket Origin for the connection for client, or
|
|
||||||
// the WebSocket location for server.
|
|
||||||
func (ws *Conn) LocalAddr() net.Addr {
|
|
||||||
if ws.IsClientConn() {
|
|
||||||
return &Addr{ws.config.Origin}
|
|
||||||
}
|
|
||||||
return &Addr{ws.config.Location}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoteAddr returns the WebSocket location for the connection for client, or
|
|
||||||
// the Websocket Origin for server.
|
|
||||||
func (ws *Conn) RemoteAddr() net.Addr {
|
|
||||||
if ws.IsClientConn() {
|
|
||||||
return &Addr{ws.config.Location}
|
|
||||||
}
|
|
||||||
return &Addr{ws.config.Origin}
|
|
||||||
}
|
|
||||||
|
|
||||||
var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn")
|
|
||||||
|
|
||||||
// SetDeadline sets the connection's network read & write deadlines.
|
|
||||||
func (ws *Conn) SetDeadline(t time.Time) error {
|
|
||||||
if conn, ok := ws.rwc.(net.Conn); ok {
|
|
||||||
return conn.SetDeadline(t)
|
|
||||||
}
|
|
||||||
return errSetDeadline
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetReadDeadline sets the connection's network read deadline.
|
|
||||||
func (ws *Conn) SetReadDeadline(t time.Time) error {
|
|
||||||
if conn, ok := ws.rwc.(net.Conn); ok {
|
|
||||||
return conn.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
return errSetDeadline
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetWriteDeadline sets the connection's network write deadline.
|
|
||||||
func (ws *Conn) SetWriteDeadline(t time.Time) error {
|
|
||||||
if conn, ok := ws.rwc.(net.Conn); ok {
|
|
||||||
return conn.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
return errSetDeadline
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config returns the WebSocket config.
|
|
||||||
func (ws *Conn) Config() *Config { return ws.config }
|
|
||||||
|
|
||||||
// Request returns the http request upgraded to the WebSocket.
|
|
||||||
// It is nil for client side.
|
|
||||||
func (ws *Conn) Request() *http.Request { return ws.request }
|
|
||||||
|
|
||||||
// Codec represents a symmetric pair of functions that implement a codec.
|
|
||||||
type Codec struct {
|
|
||||||
Marshal func(v interface{}) (data []byte, payloadType byte, err error)
|
|
||||||
Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send sends v marshaled by cd.Marshal as single frame to ws.
|
|
||||||
func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
|
|
||||||
data, payloadType, err := cd.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ws.wio.Lock()
|
|
||||||
defer ws.wio.Unlock()
|
|
||||||
w, err := ws.frameWriterFactory.NewFrameWriter(payloadType)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = w.Write(data)
|
|
||||||
w.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores
|
|
||||||
// in v. The whole frame payload is read to an in-memory buffer; max size of
|
|
||||||
// payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds
|
|
||||||
// limit, ErrFrameTooLarge is returned; in this case frame is not read off wire
|
|
||||||
// completely. The next call to Receive would read and discard leftover data of
|
|
||||||
// previous oversized frame before processing next frame.
|
|
||||||
func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
|
|
||||||
ws.rio.Lock()
|
|
||||||
defer ws.rio.Unlock()
|
|
||||||
if ws.frameReader != nil {
|
|
||||||
_, err = io.Copy(ioutil.Discard, ws.frameReader)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ws.frameReader = nil
|
|
||||||
}
|
|
||||||
again:
|
|
||||||
frame, err := ws.frameReaderFactory.NewFrameReader()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
frame, err = ws.frameHandler.HandleFrame(frame)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if frame == nil {
|
|
||||||
goto again
|
|
||||||
}
|
|
||||||
maxPayloadBytes := ws.MaxPayloadBytes
|
|
||||||
if maxPayloadBytes == 0 {
|
|
||||||
maxPayloadBytes = DefaultMaxPayloadBytes
|
|
||||||
}
|
|
||||||
if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) {
|
|
||||||
// payload size exceeds limit, no need to call Unmarshal
|
|
||||||
//
|
|
||||||
// set frameReader to current oversized frame so that
|
|
||||||
// the next call to this function can drain leftover
|
|
||||||
// data before processing the next frame
|
|
||||||
ws.frameReader = frame
|
|
||||||
return ErrFrameTooLarge
|
|
||||||
}
|
|
||||||
payloadType := frame.PayloadType()
|
|
||||||
data, err := ioutil.ReadAll(frame)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return cd.Unmarshal(data, payloadType, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func marshal(v interface{}) (msg []byte, payloadType byte, err error) {
|
|
||||||
switch data := v.(type) {
|
|
||||||
case string:
|
|
||||||
return []byte(data), TextFrame, nil
|
|
||||||
case []byte:
|
|
||||||
return data, BinaryFrame, nil
|
|
||||||
}
|
|
||||||
return nil, UnknownFrame, ErrNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
|
|
||||||
switch data := v.(type) {
|
|
||||||
case *string:
|
|
||||||
*data = string(msg)
|
|
||||||
return nil
|
|
||||||
case *[]byte:
|
|
||||||
*data = msg
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return ErrNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
Message is a codec to send/receive text/binary data in a frame on WebSocket connection.
|
|
||||||
To send/receive text frame, use string type.
|
|
||||||
To send/receive binary frame, use []byte type.
|
|
||||||
|
|
||||||
Trivial usage:
|
|
||||||
|
|
||||||
import "websocket"
|
|
||||||
|
|
||||||
// receive text frame
|
|
||||||
var message string
|
|
||||||
websocket.Message.Receive(ws, &message)
|
|
||||||
|
|
||||||
// send text frame
|
|
||||||
message = "hello"
|
|
||||||
websocket.Message.Send(ws, message)
|
|
||||||
|
|
||||||
// receive binary frame
|
|
||||||
var data []byte
|
|
||||||
websocket.Message.Receive(ws, &data)
|
|
||||||
|
|
||||||
// send binary frame
|
|
||||||
data = []byte{0, 1, 2}
|
|
||||||
websocket.Message.Send(ws, data)
|
|
||||||
|
|
||||||
*/
|
|
||||||
var Message = Codec{marshal, unmarshal}
|
|
||||||
|
|
||||||
func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
|
|
||||||
msg, err = json.Marshal(v)
|
|
||||||
return msg, TextFrame, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
|
|
||||||
return json.Unmarshal(msg, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.
|
|
||||||
|
|
||||||
Trivial usage:
|
|
||||||
|
|
||||||
import "websocket"
|
|
||||||
|
|
||||||
type T struct {
|
|
||||||
Msg string
|
|
||||||
Count int
|
|
||||||
}
|
|
||||||
|
|
||||||
// receive JSON type T
|
|
||||||
var data T
|
|
||||||
websocket.JSON.Receive(ws, &data)
|
|
||||||
|
|
||||||
// send JSON type T
|
|
||||||
websocket.JSON.Send(ws, data)
|
|
||||||
*/
|
|
||||||
var JSON = Codec{jsonMarshal, jsonUnmarshal}
|
|
30
vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go
generated
vendored
30
vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go
generated
vendored
@ -1,30 +0,0 @@
|
|||||||
// Copyright 2020 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// Package unsafeheader contains header declarations for the Go runtime's
|
|
||||||
// slice and string implementations.
|
|
||||||
//
|
|
||||||
// This package allows x/sys to use types equivalent to
|
|
||||||
// reflect.SliceHeader and reflect.StringHeader without introducing
|
|
||||||
// a dependency on the (relatively heavy) "reflect" package.
|
|
||||||
package unsafeheader
|
|
||||||
|
|
||||||
import (
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Slice is the runtime representation of a slice.
|
|
||||||
// It cannot be used safely or portably and its representation may change in a later release.
|
|
||||||
type Slice struct {
|
|
||||||
Data unsafe.Pointer
|
|
||||||
Len int
|
|
||||||
Cap int
|
|
||||||
}
|
|
||||||
|
|
||||||
// String is the runtime representation of a string.
|
|
||||||
// It cannot be used safely or portably and its representation may change in a later release.
|
|
||||||
type String struct {
|
|
||||||
Data unsafe.Pointer
|
|
||||||
Len int
|
|
||||||
}
|
|
4
vendor/golang.org/x/sys/unix/README.md
generated
vendored
4
vendor/golang.org/x/sys/unix/README.md
generated
vendored
@ -89,7 +89,7 @@ constants.
|
|||||||
|
|
||||||
Adding new syscall numbers is mostly done by running the build on a sufficiently
|
Adding new syscall numbers is mostly done by running the build on a sufficiently
|
||||||
new installation of the target OS (or updating the source checkouts for the
|
new installation of the target OS (or updating the source checkouts for the
|
||||||
new build system). However, depending on the OS, you may need to update the
|
new build system). However, depending on the OS, you make need to update the
|
||||||
parsing in mksysnum.
|
parsing in mksysnum.
|
||||||
|
|
||||||
### mksyscall.go
|
### mksyscall.go
|
||||||
@ -163,7 +163,7 @@ The merge is performed in the following steps:
|
|||||||
|
|
||||||
## Generated files
|
## Generated files
|
||||||
|
|
||||||
### `zerrors_${GOOS}_${GOARCH}.go`
|
### `zerror_${GOOS}_${GOARCH}.go`
|
||||||
|
|
||||||
A file containing all of the system's generated error numbers, error strings,
|
A file containing all of the system's generated error numbers, error strings,
|
||||||
signal numbers, and constants. Generated by `mkerrors.sh` (see above).
|
signal numbers, and constants. Generated by `mkerrors.sh` (see above).
|
||||||
|
29
vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s
generated
vendored
29
vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s
generated
vendored
@ -1,29 +0,0 @@
|
|||||||
// Copyright 2019 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// +build !gccgo
|
|
||||||
|
|
||||||
#include "textflag.h"
|
|
||||||
|
|
||||||
//
|
|
||||||
// System call support for mips64, OpenBSD
|
|
||||||
//
|
|
||||||
|
|
||||||
// Just jump to package syscall's implementation for all these functions.
|
|
||||||
// The runtime may know about them.
|
|
||||||
|
|
||||||
TEXT ·Syscall(SB),NOSPLIT,$0-56
|
|
||||||
JMP syscall·Syscall(SB)
|
|
||||||
|
|
||||||
TEXT ·Syscall6(SB),NOSPLIT,$0-80
|
|
||||||
JMP syscall·Syscall6(SB)
|
|
||||||
|
|
||||||
TEXT ·Syscall9(SB),NOSPLIT,$0-104
|
|
||||||
JMP syscall·Syscall9(SB)
|
|
||||||
|
|
||||||
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
|
|
||||||
JMP syscall·RawSyscall(SB)
|
|
||||||
|
|
||||||
TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
|
|
||||||
JMP syscall·RawSyscall6(SB)
|
|
9
vendor/golang.org/x/sys/unix/ioctl.go
generated
vendored
9
vendor/golang.org/x/sys/unix/ioctl.go
generated
vendored
@ -20,15 +20,6 @@ func IoctlSetInt(fd int, req uint, value int) error {
|
|||||||
return ioctl(fd, req, uintptr(value))
|
return ioctl(fd, req, uintptr(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
// IoctlSetPointerInt performs an ioctl operation which sets an
|
|
||||||
// integer value on fd, using the specified request number. The ioctl
|
|
||||||
// argument is called with a pointer to the integer value, rather than
|
|
||||||
// passing the integer value directly.
|
|
||||||
func IoctlSetPointerInt(fd int, req uint, value int) error {
|
|
||||||
v := int32(value)
|
|
||||||
return ioctl(fd, req, uintptr(unsafe.Pointer(&v)))
|
|
||||||
}
|
|
||||||
|
|
||||||
// IoctlSetWinsize performs an ioctl on fd with a *Winsize argument.
|
// IoctlSetWinsize performs an ioctl on fd with a *Winsize argument.
|
||||||
//
|
//
|
||||||
// To change fd's window size, the req argument should be TIOCSWINSZ.
|
// To change fd's window size, the req argument should be TIOCSWINSZ.
|
||||||
|
15
vendor/golang.org/x/sys/unix/mkall.sh
generated
vendored
15
vendor/golang.org/x/sys/unix/mkall.sh
generated
vendored
@ -73,22 +73,26 @@ aix_ppc64)
|
|||||||
darwin_386)
|
darwin_386)
|
||||||
mkerrors="$mkerrors -m32"
|
mkerrors="$mkerrors -m32"
|
||||||
mksyscall="go run mksyscall.go -l32"
|
mksyscall="go run mksyscall.go -l32"
|
||||||
|
mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
|
||||||
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
||||||
mkasm="go run mkasm_darwin.go"
|
mkasm="go run mkasm_darwin.go"
|
||||||
;;
|
;;
|
||||||
darwin_amd64)
|
darwin_amd64)
|
||||||
mkerrors="$mkerrors -m64"
|
mkerrors="$mkerrors -m64"
|
||||||
|
mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
|
||||||
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
||||||
mkasm="go run mkasm_darwin.go"
|
mkasm="go run mkasm_darwin.go"
|
||||||
;;
|
;;
|
||||||
darwin_arm)
|
darwin_arm)
|
||||||
mkerrors="$mkerrors"
|
mkerrors="$mkerrors"
|
||||||
mksyscall="go run mksyscall.go -l32"
|
mksyscall="go run mksyscall.go -l32"
|
||||||
|
mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
|
||||||
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
||||||
mkasm="go run mkasm_darwin.go"
|
mkasm="go run mkasm_darwin.go"
|
||||||
;;
|
;;
|
||||||
darwin_arm64)
|
darwin_arm64)
|
||||||
mkerrors="$mkerrors -m64"
|
mkerrors="$mkerrors -m64"
|
||||||
|
mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
|
||||||
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
mktypes="GOARCH=$GOARCH go tool cgo -godefs"
|
||||||
mkasm="go run mkasm_darwin.go"
|
mkasm="go run mkasm_darwin.go"
|
||||||
;;
|
;;
|
||||||
@ -180,15 +184,6 @@ openbsd_arm64)
|
|||||||
# API consistent across platforms.
|
# API consistent across platforms.
|
||||||
mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
|
mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
|
||||||
;;
|
;;
|
||||||
openbsd_mips64)
|
|
||||||
mkerrors="$mkerrors -m64"
|
|
||||||
mksyscall="go run mksyscall.go -openbsd"
|
|
||||||
mksysctl="go run mksysctl_openbsd.go"
|
|
||||||
mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
|
|
||||||
# Let the type of C char be signed for making the bare syscall
|
|
||||||
# API consistent across platforms.
|
|
||||||
mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
|
|
||||||
;;
|
|
||||||
solaris_amd64)
|
solaris_amd64)
|
||||||
mksyscall="go run mksyscall_solaris.go"
|
mksyscall="go run mksyscall_solaris.go"
|
||||||
mkerrors="$mkerrors -m64"
|
mkerrors="$mkerrors -m64"
|
||||||
@ -222,6 +217,8 @@ esac
|
|||||||
# aix/ppc64 script generates files instead of writing to stdin.
|
# aix/ppc64 script generates files instead of writing to stdin.
|
||||||
echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
|
echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
|
||||||
elif [ "$GOOS" == "darwin" ]; then
|
elif [ "$GOOS" == "darwin" ]; then
|
||||||
|
# pre-1.12, direct syscalls
|
||||||
|
echo "$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos syscall_darwin_${GOARCH}.1_11.go $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go";
|
||||||
# 1.12 and later, syscalls via libSystem
|
# 1.12 and later, syscalls via libSystem
|
||||||
echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
|
echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
|
||||||
# 1.13 and later, syscalls via libSystem (including syscallPtr)
|
# 1.13 and later, syscalls via libSystem (including syscallPtr)
|
||||||
|
17
vendor/golang.org/x/sys/unix/mkerrors.sh
generated
vendored
17
vendor/golang.org/x/sys/unix/mkerrors.sh
generated
vendored
@ -107,7 +107,6 @@ includes_FreeBSD='
|
|||||||
#include <sys/types.h>
|
#include <sys/types.h>
|
||||||
#include <sys/disk.h>
|
#include <sys/disk.h>
|
||||||
#include <sys/event.h>
|
#include <sys/event.h>
|
||||||
#include <sys/sched.h>
|
|
||||||
#include <sys/select.h>
|
#include <sys/select.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <sys/sockio.h>
|
#include <sys/sockio.h>
|
||||||
@ -188,24 +187,19 @@ struct ltchars {
|
|||||||
#include <sys/select.h>
|
#include <sys/select.h>
|
||||||
#include <sys/signalfd.h>
|
#include <sys/signalfd.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <sys/timerfd.h>
|
|
||||||
#include <sys/uio.h>
|
#include <sys/uio.h>
|
||||||
#include <sys/xattr.h>
|
#include <sys/xattr.h>
|
||||||
#include <linux/bpf.h>
|
#include <linux/bpf.h>
|
||||||
#include <linux/can.h>
|
#include <linux/can.h>
|
||||||
#include <linux/can/error.h>
|
|
||||||
#include <linux/can/raw.h>
|
|
||||||
#include <linux/capability.h>
|
#include <linux/capability.h>
|
||||||
#include <linux/cryptouser.h>
|
#include <linux/cryptouser.h>
|
||||||
#include <linux/devlink.h>
|
#include <linux/devlink.h>
|
||||||
#include <linux/dm-ioctl.h>
|
|
||||||
#include <linux/errqueue.h>
|
#include <linux/errqueue.h>
|
||||||
#include <linux/falloc.h>
|
#include <linux/falloc.h>
|
||||||
#include <linux/fanotify.h>
|
#include <linux/fanotify.h>
|
||||||
#include <linux/filter.h>
|
#include <linux/filter.h>
|
||||||
#include <linux/fs.h>
|
#include <linux/fs.h>
|
||||||
#include <linux/fscrypt.h>
|
#include <linux/fscrypt.h>
|
||||||
#include <linux/fsverity.h>
|
|
||||||
#include <linux/genetlink.h>
|
#include <linux/genetlink.h>
|
||||||
#include <linux/hdreg.h>
|
#include <linux/hdreg.h>
|
||||||
#include <linux/icmpv6.h>
|
#include <linux/icmpv6.h>
|
||||||
@ -301,7 +295,6 @@ includes_NetBSD='
|
|||||||
#include <sys/extattr.h>
|
#include <sys/extattr.h>
|
||||||
#include <sys/mman.h>
|
#include <sys/mman.h>
|
||||||
#include <sys/mount.h>
|
#include <sys/mount.h>
|
||||||
#include <sys/sched.h>
|
|
||||||
#include <sys/select.h>
|
#include <sys/select.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <sys/sockio.h>
|
#include <sys/sockio.h>
|
||||||
@ -330,7 +323,6 @@ includes_OpenBSD='
|
|||||||
#include <sys/mman.h>
|
#include <sys/mman.h>
|
||||||
#include <sys/mount.h>
|
#include <sys/mount.h>
|
||||||
#include <sys/select.h>
|
#include <sys/select.h>
|
||||||
#include <sys/sched.h>
|
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <sys/sockio.h>
|
#include <sys/sockio.h>
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
@ -487,13 +479,12 @@ ccflags="$@"
|
|||||||
$2 ~ /^(MS|MNT|UMOUNT)_/ ||
|
$2 ~ /^(MS|MNT|UMOUNT)_/ ||
|
||||||
$2 ~ /^NS_GET_/ ||
|
$2 ~ /^NS_GET_/ ||
|
||||||
$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
|
$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
|
||||||
$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|TFD)_/ ||
|
$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||
|
||||||
$2 ~ /^KEXEC_/ ||
|
$2 ~ /^KEXEC_/ ||
|
||||||
$2 ~ /^LINUX_REBOOT_CMD_/ ||
|
$2 ~ /^LINUX_REBOOT_CMD_/ ||
|
||||||
$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
|
$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
|
||||||
$2 ~ /^MODULE_INIT_/ ||
|
$2 ~ /^MODULE_INIT_/ ||
|
||||||
$2 !~ "NLA_TYPE_MASK" &&
|
$2 !~ "NLA_TYPE_MASK" &&
|
||||||
$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&
|
|
||||||
$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||
|
$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||
|
||||||
$2 ~ /^SIOC/ ||
|
$2 ~ /^SIOC/ ||
|
||||||
$2 ~ /^TIOC/ ||
|
$2 ~ /^TIOC/ ||
|
||||||
@ -513,14 +504,10 @@ ccflags="$@"
|
|||||||
$2 ~ /^(CLOCK|TIMER)_/ ||
|
$2 ~ /^(CLOCK|TIMER)_/ ||
|
||||||
$2 ~ /^CAN_/ ||
|
$2 ~ /^CAN_/ ||
|
||||||
$2 ~ /^CAP_/ ||
|
$2 ~ /^CAP_/ ||
|
||||||
$2 ~ /^CP_/ ||
|
|
||||||
$2 ~ /^CPUSTATES$/ ||
|
|
||||||
$2 ~ /^ALG_/ ||
|
$2 ~ /^ALG_/ ||
|
||||||
$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||
|
$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||
|
||||||
$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||
|
$2 ~ /^FS_IOC_.*ENCRYPTION/ ||
|
||||||
$2 ~ /^FS_VERITY_/ ||
|
|
||||||
$2 ~ /^FSCRYPT_/ ||
|
$2 ~ /^FSCRYPT_/ ||
|
||||||
$2 ~ /^DM_/ ||
|
|
||||||
$2 ~ /^GRND_/ ||
|
$2 ~ /^GRND_/ ||
|
||||||
$2 ~ /^RND/ ||
|
$2 ~ /^RND/ ||
|
||||||
$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
|
$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
|
||||||
|
17
vendor/golang.org/x/sys/unix/syscall_bsd.go
generated
vendored
17
vendor/golang.org/x/sys/unix/syscall_bsd.go
generated
vendored
@ -527,23 +527,6 @@ func SysctlClockinfo(name string) (*Clockinfo, error) {
|
|||||||
return &ci, nil
|
return &ci, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func SysctlTimeval(name string) (*Timeval, error) {
|
|
||||||
mib, err := sysctlmib(name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var tv Timeval
|
|
||||||
n := uintptr(unsafe.Sizeof(tv))
|
|
||||||
if err := sysctl(mib, (*byte)(unsafe.Pointer(&tv)), &n, nil, 0); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if n != unsafe.Sizeof(tv) {
|
|
||||||
return nil, EIO
|
|
||||||
}
|
|
||||||
return &tv, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//sys utimes(path string, timeval *[2]Timeval) (err error)
|
//sys utimes(path string, timeval *[2]Timeval) (err error)
|
||||||
|
|
||||||
func Utimes(path string, tv []Timeval) error {
|
func Utimes(path string, tv []Timeval) error {
|
||||||
|
4
vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go
generated
vendored
4
vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go
generated
vendored
@ -10,8 +10,6 @@ import (
|
|||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
const _SYS_GETDIRENTRIES64 = 344
|
|
||||||
|
|
||||||
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
|
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
|
||||||
// To implement this using libSystem we'd need syscall_syscallPtr for
|
// To implement this using libSystem we'd need syscall_syscallPtr for
|
||||||
// fdopendir. However, syscallPtr was only added in Go 1.13, so we fall
|
// fdopendir. However, syscallPtr was only added in Go 1.13, so we fall
|
||||||
@ -22,7 +20,7 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
|
|||||||
} else {
|
} else {
|
||||||
p = unsafe.Pointer(&_zero)
|
p = unsafe.Pointer(&_zero)
|
||||||
}
|
}
|
||||||
r0, _, e1 := Syscall6(_SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
|
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
|
||||||
n = int(r0)
|
n = int(r0)
|
||||||
if e1 != 0 {
|
if e1 != 0 {
|
||||||
return n, errnoErr(e1)
|
return n, errnoErr(e1)
|
||||||
|
21
vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go
generated
vendored
21
vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go
generated
vendored
@ -6,11 +6,7 @@
|
|||||||
|
|
||||||
package unix
|
package unix
|
||||||
|
|
||||||
import (
|
import "unsafe"
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"golang.org/x/sys/internal/unsafeheader"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys closedir(dir uintptr) (err error)
|
//sys closedir(dir uintptr) (err error)
|
||||||
//sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
|
//sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
|
||||||
@ -75,7 +71,6 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
|
|||||||
cnt++
|
cnt++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
reclen := int(entry.Reclen)
|
reclen := int(entry.Reclen)
|
||||||
if reclen > len(buf) {
|
if reclen > len(buf) {
|
||||||
// Not enough room. Return for now.
|
// Not enough room. Return for now.
|
||||||
@ -84,15 +79,13 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
|
|||||||
// restarting is O(n^2) in the length of the directory. Oh well.
|
// restarting is O(n^2) in the length of the directory. Oh well.
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy entry into return buffer.
|
// Copy entry into return buffer.
|
||||||
var s []byte
|
s := struct {
|
||||||
hdr := (*unsafeheader.Slice)(unsafe.Pointer(&s))
|
ptr unsafe.Pointer
|
||||||
hdr.Data = unsafe.Pointer(&entry)
|
siz int
|
||||||
hdr.Cap = reclen
|
cap int
|
||||||
hdr.Len = reclen
|
}{ptr: unsafe.Pointer(&entry), siz: reclen, cap: reclen}
|
||||||
copy(buf, s)
|
copy(buf, *(*[]byte)(unsafe.Pointer(&s)))
|
||||||
|
|
||||||
buf = buf[reclen:]
|
buf = buf[reclen:]
|
||||||
n += reclen
|
n += reclen
|
||||||
cnt++
|
cnt++
|
||||||
|
6
vendor/golang.org/x/sys/unix/syscall_darwin.go
generated
vendored
6
vendor/golang.org/x/sys/unix/syscall_darwin.go
generated
vendored
@ -49,11 +49,6 @@ type SockaddrDatalink struct {
|
|||||||
raw RawSockaddrDatalink
|
raw RawSockaddrDatalink
|
||||||
}
|
}
|
||||||
|
|
||||||
// Some external packages rely on SYS___SYSCTL being defined to implement their
|
|
||||||
// own sysctl wrappers. Provide it here, even though direct syscalls are no
|
|
||||||
// longer supported on darwin.
|
|
||||||
const SYS___SYSCTL = 202
|
|
||||||
|
|
||||||
// Translate "kern.hostname" to []_C_int{0,1,2,3}.
|
// Translate "kern.hostname" to []_C_int{0,1,2,3}.
|
||||||
func nametomib(name string) (mib []_C_int, err error) {
|
func nametomib(name string) (mib []_C_int, err error) {
|
||||||
const siz = unsafe.Sizeof(mib[0])
|
const siz = unsafe.Sizeof(mib[0])
|
||||||
@ -428,7 +423,6 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
|
|||||||
//sysnb Getrlimit(which int, lim *Rlimit) (err error)
|
//sysnb Getrlimit(which int, lim *Rlimit) (err error)
|
||||||
//sysnb Getrusage(who int, rusage *Rusage) (err error)
|
//sysnb Getrusage(who int, rusage *Rusage) (err error)
|
||||||
//sysnb Getsid(pid int) (sid int, err error)
|
//sysnb Getsid(pid int) (sid int, err error)
|
||||||
//sysnb Gettimeofday(tp *Timeval) (err error)
|
|
||||||
//sysnb Getuid() (uid int)
|
//sysnb Getuid() (uid int)
|
||||||
//sysnb Issetugid() (tainted bool)
|
//sysnb Issetugid() (tainted bool)
|
||||||
//sys Kqueue() (fd int, err error)
|
//sys Kqueue() (fd int, err error)
|
||||||
|
@ -2,6 +2,8 @@
|
|||||||
// Use of this source code is governed by a BSD-style
|
// Use of this source code is governed by a BSD-style
|
||||||
// license that can be found in the LICENSE file.
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
// Package fieldnum contains constants for field numbers of fields in messages
|
// +build darwin,386,!go1.12
|
||||||
// declared in descriptor.proto and any of the well-known types.
|
|
||||||
package fieldnum
|
package unix
|
||||||
|
|
||||||
|
//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
|
15
vendor/golang.org/x/sys/unix/syscall_darwin_386.go
generated
vendored
15
vendor/golang.org/x/sys/unix/syscall_darwin_386.go
generated
vendored
@ -20,6 +20,17 @@ func setTimeval(sec, usec int64) Timeval {
|
|||||||
return Timeval{Sec: int32(sec), Usec: int32(usec)}
|
return Timeval{Sec: int32(sec), Usec: int32(usec)}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error)
|
||||||
|
func Gettimeofday(tv *Timeval) (err error) {
|
||||||
|
// The tv passed to gettimeofday must be non-nil
|
||||||
|
// but is otherwise unused. The answers come back
|
||||||
|
// in the two registers.
|
||||||
|
sec, usec, err := gettimeofday(tv)
|
||||||
|
tv.Sec = int32(sec)
|
||||||
|
tv.Usec = int32(usec)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func SetKevent(k *Kevent_t, fd, mode, flags int) {
|
func SetKevent(k *Kevent_t, fd, mode, flags int) {
|
||||||
k.Ident = uint32(fd)
|
k.Ident = uint32(fd)
|
||||||
k.Filter = int16(mode)
|
k.Filter = int16(mode)
|
||||||
@ -44,6 +55,10 @@ func (cmsg *Cmsghdr) SetLen(length int) {
|
|||||||
|
|
||||||
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||||
|
|
||||||
|
// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
|
||||||
|
// of darwin/386 the syscall is called sysctl instead of __sysctl.
|
||||||
|
const SYS___SYSCTL = SYS_SYSCTL
|
||||||
|
|
||||||
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
|
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
|
||||||
//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
|
//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
|
||||||
//sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
|
//sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
|
||||||
|
9
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.1_11.go
generated
vendored
Normal file
9
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.1_11.go
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,amd64,!go1.12
|
||||||
|
|
||||||
|
package unix
|
||||||
|
|
||||||
|
//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
|
15
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
generated
vendored
15
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
generated
vendored
@ -20,6 +20,17 @@ func setTimeval(sec, usec int64) Timeval {
|
|||||||
return Timeval{Sec: sec, Usec: int32(usec)}
|
return Timeval{Sec: sec, Usec: int32(usec)}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error)
|
||||||
|
func Gettimeofday(tv *Timeval) (err error) {
|
||||||
|
// The tv passed to gettimeofday must be non-nil
|
||||||
|
// but is otherwise unused. The answers come back
|
||||||
|
// in the two registers.
|
||||||
|
sec, usec, err := gettimeofday(tv)
|
||||||
|
tv.Sec = sec
|
||||||
|
tv.Usec = usec
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func SetKevent(k *Kevent_t, fd, mode, flags int) {
|
func SetKevent(k *Kevent_t, fd, mode, flags int) {
|
||||||
k.Ident = uint64(fd)
|
k.Ident = uint64(fd)
|
||||||
k.Filter = int16(mode)
|
k.Filter = int16(mode)
|
||||||
@ -44,6 +55,10 @@ func (cmsg *Cmsghdr) SetLen(length int) {
|
|||||||
|
|
||||||
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||||
|
|
||||||
|
// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
|
||||||
|
// of darwin/amd64 the syscall is called sysctl instead of __sysctl.
|
||||||
|
const SYS___SYSCTL = SYS_SYSCTL
|
||||||
|
|
||||||
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
|
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
|
||||||
//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
|
//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
|
||||||
//sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
|
//sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user