server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package server
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "os"
  10. "runtime"
  11. "strings"
  12. "github.com/gorilla/mux"
  13. "github.com/Sirupsen/logrus"
  14. "github.com/docker/distribution/registry/api/errcode"
  15. "github.com/docker/docker/api"
  16. "github.com/docker/docker/autogen/dockerversion"
  17. "github.com/docker/docker/daemon"
  18. "github.com/docker/docker/pkg/sockets"
  19. "github.com/docker/docker/pkg/version"
  20. )
  21. // Config provides the configuration for the API server
  22. type Config struct {
  23. Logging bool
  24. EnableCors bool
  25. CorsHeaders string
  26. Version string
  27. SocketGroup string
  28. TLSConfig *tls.Config
  29. }
  30. // Server contains instance details for the server
  31. type Server struct {
  32. daemon *daemon.Daemon
  33. cfg *Config
  34. router *mux.Router
  35. start chan struct{}
  36. servers []serverCloser
  37. }
  38. // New returns a new instance of the server based on the specified configuration.
  39. func New(cfg *Config) *Server {
  40. srv := &Server{
  41. cfg: cfg,
  42. start: make(chan struct{}),
  43. }
  44. r := createRouter(srv)
  45. srv.router = r
  46. return srv
  47. }
  48. // Close closes servers and thus stop receiving requests
  49. func (s *Server) Close() {
  50. for _, srv := range s.servers {
  51. if err := srv.Close(); err != nil {
  52. logrus.Error(err)
  53. }
  54. }
  55. }
  56. type serverCloser interface {
  57. Serve() error
  58. Close() error
  59. }
  60. // ServeAPI loops through all of the protocols sent in to docker and spawns
  61. // off a go routine to setup a serving http.Server for each.
  62. func (s *Server) ServeAPI(protoAddrs []string) error {
  63. var chErrors = make(chan error, len(protoAddrs))
  64. for _, protoAddr := range protoAddrs {
  65. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  66. if len(protoAddrParts) != 2 {
  67. return fmt.Errorf("bad format, expected PROTO://ADDR")
  68. }
  69. srv, err := s.newServer(protoAddrParts[0], protoAddrParts[1])
  70. if err != nil {
  71. return err
  72. }
  73. s.servers = append(s.servers, srv...)
  74. for _, s := range srv {
  75. logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
  76. go func(s serverCloser) {
  77. if err := s.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  78. err = nil
  79. }
  80. chErrors <- err
  81. }(s)
  82. }
  83. }
  84. for i := 0; i < len(protoAddrs); i++ {
  85. err := <-chErrors
  86. if err != nil {
  87. return err
  88. }
  89. }
  90. return nil
  91. }
  92. // HTTPServer contains an instance of http server and the listener.
  93. // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
  94. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  95. type HTTPServer struct {
  96. srv *http.Server
  97. l net.Listener
  98. }
  99. // Serve starts listening for inbound requests.
  100. func (s *HTTPServer) Serve() error {
  101. return s.srv.Serve(s.l)
  102. }
  103. // Close closes the HTTPServer from listening for the inbound requests.
  104. func (s *HTTPServer) Close() error {
  105. return s.l.Close()
  106. }
  107. // HTTPAPIFunc is an adapter to allow the use of ordinary functions as Docker API endpoints.
  108. // Any function that has the appropriate signature can be register as a API endpoint (e.g. getVersion).
  109. type HTTPAPIFunc func(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error
  110. func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
  111. conn, _, err := w.(http.Hijacker).Hijack()
  112. if err != nil {
  113. return nil, nil, err
  114. }
  115. // Flush the options to make sure the client sets the raw mode
  116. conn.Write([]byte{})
  117. return conn, conn, nil
  118. }
  119. func closeStreams(streams ...interface{}) {
  120. for _, stream := range streams {
  121. if tcpc, ok := stream.(interface {
  122. CloseWrite() error
  123. }); ok {
  124. tcpc.CloseWrite()
  125. } else if closer, ok := stream.(io.Closer); ok {
  126. closer.Close()
  127. }
  128. }
  129. }
  130. // checkForJSON makes sure that the request's Content-Type is application/json.
  131. func checkForJSON(r *http.Request) error {
  132. ct := r.Header.Get("Content-Type")
  133. // No Content-Type header is ok as long as there's no Body
  134. if ct == "" {
  135. if r.Body == nil || r.ContentLength == 0 {
  136. return nil
  137. }
  138. }
  139. // Otherwise it better be json
  140. if api.MatchesContentType(ct, "application/json") {
  141. return nil
  142. }
  143. return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
  144. }
  145. //If we don't do this, POST method without Content-type (even with empty body) will fail
  146. func parseForm(r *http.Request) error {
  147. if r == nil {
  148. return nil
  149. }
  150. if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  151. return err
  152. }
  153. return nil
  154. }
  155. func parseMultipartForm(r *http.Request) error {
  156. if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  157. return err
  158. }
  159. return nil
  160. }
  161. func httpError(w http.ResponseWriter, err error) {
  162. if err == nil || w == nil {
  163. logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling")
  164. return
  165. }
  166. statusCode := http.StatusInternalServerError
  167. errMsg := err.Error()
  168. // Based on the type of error we get we need to process things
  169. // slightly differently to extract the error message.
  170. // In the 'errcode.*' cases there are two different type of
  171. // error that could be returned. errocode.ErrorCode is the base
  172. // type of error object - it is just an 'int' that can then be
  173. // used as the look-up key to find the message. errorcode.Error
  174. // extends errorcode.Error by adding error-instance specific
  175. // data, like 'details' or variable strings to be inserted into
  176. // the message.
  177. //
  178. // Ideally, we should just be able to call err.Error() for all
  179. // cases but the errcode package doesn't support that yet.
  180. //
  181. // Additionally, in both errcode cases, there might be an http
  182. // status code associated with it, and if so use it.
  183. switch err.(type) {
  184. case errcode.ErrorCode:
  185. daError, _ := err.(errcode.ErrorCode)
  186. statusCode = daError.Descriptor().HTTPStatusCode
  187. errMsg = daError.Message()
  188. case errcode.Error:
  189. // For reference, if you're looking for a particular error
  190. // then you can do something like :
  191. // import ( derr "github.com/docker/docker/api/errors" )
  192. // if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
  193. daError, _ := err.(errcode.Error)
  194. statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
  195. errMsg = daError.Message
  196. default:
  197. // This part of will be removed once we've
  198. // converted everything over to use the errcode package
  199. // FIXME: this is brittle and should not be necessary.
  200. // If we need to differentiate between different possible error types,
  201. // we should create appropriate error types with clearly defined meaning
  202. errStr := strings.ToLower(err.Error())
  203. for keyword, status := range map[string]int{
  204. "not found": http.StatusNotFound,
  205. "no such": http.StatusNotFound,
  206. "bad parameter": http.StatusBadRequest,
  207. "conflict": http.StatusConflict,
  208. "impossible": http.StatusNotAcceptable,
  209. "wrong login/password": http.StatusUnauthorized,
  210. "hasn't been activated": http.StatusForbidden,
  211. } {
  212. if strings.Contains(errStr, keyword) {
  213. statusCode = status
  214. break
  215. }
  216. }
  217. }
  218. if statusCode == 0 {
  219. statusCode = http.StatusInternalServerError
  220. }
  221. logrus.WithFields(logrus.Fields{"statusCode": statusCode, "err": err}).Error("HTTP Error")
  222. http.Error(w, errMsg, statusCode)
  223. }
  224. // writeJSON writes the value v to the http response stream as json with standard
  225. // json encoding.
  226. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  227. w.Header().Set("Content-Type", "application/json")
  228. w.WriteHeader(code)
  229. return json.NewEncoder(w).Encode(v)
  230. }
  231. func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  232. w.WriteHeader(http.StatusOK)
  233. return nil
  234. }
  235. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  236. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  237. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  238. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  239. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  240. }
  241. func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  242. _, err := w.Write([]byte{'O', 'K'})
  243. return err
  244. }
  245. func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
  246. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  247. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  248. }
  249. if l, err = sockets.NewTCPSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
  250. return nil, err
  251. }
  252. if err := allocateDaemonPort(addr); err != nil {
  253. return nil, err
  254. }
  255. return
  256. }
  257. func makeHTTPHandler(logging bool, localMethod string, localRoute string, handlerFunc HTTPAPIFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  258. return func(w http.ResponseWriter, r *http.Request) {
  259. // log the request
  260. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  261. if logging {
  262. logrus.Infof("%s %s", r.Method, r.RequestURI)
  263. }
  264. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  265. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  266. // v1.20 onwards includes the GOOS of the client after the version
  267. // such as Docker/1.7.0 (linux)
  268. if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
  269. userAgent[1] = strings.Split(userAgent[1], " ")[0]
  270. }
  271. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  272. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  273. }
  274. }
  275. version := version.Version(mux.Vars(r)["version"])
  276. if version == "" {
  277. version = api.Version
  278. }
  279. if corsHeaders != "" {
  280. writeCorsHeaders(w, r, corsHeaders)
  281. }
  282. if version.GreaterThan(api.Version) {
  283. http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", version, api.Version).Error(), http.StatusBadRequest)
  284. return
  285. }
  286. if version.LessThan(api.MinVersion) {
  287. http.Error(w, fmt.Errorf("client is too old, minimum supported API version is %s, please upgrade your client to a newer version", api.MinVersion).Error(), http.StatusBadRequest)
  288. return
  289. }
  290. w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
  291. if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil {
  292. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
  293. httpError(w, err)
  294. }
  295. }
  296. }
  297. // we keep enableCors just for legacy usage, need to be removed in the future
  298. func createRouter(s *Server) *mux.Router {
  299. r := mux.NewRouter()
  300. if os.Getenv("DEBUG") != "" {
  301. profilerSetup(r, "/debug/")
  302. }
  303. m := map[string]map[string]HTTPAPIFunc{
  304. "HEAD": {
  305. "/containers/{name:.*}/archive": s.headContainersArchive,
  306. },
  307. "GET": {
  308. "/_ping": s.ping,
  309. "/events": s.getEvents,
  310. "/info": s.getInfo,
  311. "/version": s.getVersion,
  312. "/images/json": s.getImagesJSON,
  313. "/images/search": s.getImagesSearch,
  314. "/images/get": s.getImagesGet,
  315. "/images/{name:.*}/get": s.getImagesGet,
  316. "/images/{name:.*}/history": s.getImagesHistory,
  317. "/images/{name:.*}/json": s.getImagesByName,
  318. "/containers/ps": s.getContainersJSON,
  319. "/containers/json": s.getContainersJSON,
  320. "/containers/{name:.*}/export": s.getContainersExport,
  321. "/containers/{name:.*}/changes": s.getContainersChanges,
  322. "/containers/{name:.*}/json": s.getContainersByName,
  323. "/containers/{name:.*}/top": s.getContainersTop,
  324. "/containers/{name:.*}/logs": s.getContainersLogs,
  325. "/containers/{name:.*}/stats": s.getContainersStats,
  326. "/containers/{name:.*}/attach/ws": s.wsContainersAttach,
  327. "/exec/{id:.*}/json": s.getExecByID,
  328. "/containers/{name:.*}/archive": s.getContainersArchive,
  329. },
  330. "POST": {
  331. "/auth": s.postAuth,
  332. "/commit": s.postCommit,
  333. "/build": s.postBuild,
  334. "/images/create": s.postImagesCreate,
  335. "/images/load": s.postImagesLoad,
  336. "/images/{name:.*}/push": s.postImagesPush,
  337. "/images/{name:.*}/tag": s.postImagesTag,
  338. "/containers/create": s.postContainersCreate,
  339. "/containers/{name:.*}/kill": s.postContainersKill,
  340. "/containers/{name:.*}/pause": s.postContainersPause,
  341. "/containers/{name:.*}/unpause": s.postContainersUnpause,
  342. "/containers/{name:.*}/restart": s.postContainersRestart,
  343. "/containers/{name:.*}/start": s.postContainersStart,
  344. "/containers/{name:.*}/stop": s.postContainersStop,
  345. "/containers/{name:.*}/wait": s.postContainersWait,
  346. "/containers/{name:.*}/resize": s.postContainersResize,
  347. "/containers/{name:.*}/attach": s.postContainersAttach,
  348. "/containers/{name:.*}/copy": s.postContainersCopy,
  349. "/containers/{name:.*}/exec": s.postContainerExecCreate,
  350. "/exec/{name:.*}/start": s.postContainerExecStart,
  351. "/exec/{name:.*}/resize": s.postContainerExecResize,
  352. "/containers/{name:.*}/rename": s.postContainerRename,
  353. },
  354. "PUT": {
  355. "/containers/{name:.*}/archive": s.putContainersArchive,
  356. },
  357. "DELETE": {
  358. "/containers/{name:.*}": s.deleteContainers,
  359. "/images/{name:.*}": s.deleteImages,
  360. },
  361. "OPTIONS": {
  362. "": s.optionsHandler,
  363. },
  364. }
  365. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  366. // otherwise, all head values will be passed to HTTP handler
  367. corsHeaders := s.cfg.CorsHeaders
  368. if corsHeaders == "" && s.cfg.EnableCors {
  369. corsHeaders = "*"
  370. }
  371. for method, routes := range m {
  372. for route, fct := range routes {
  373. logrus.Debugf("Registering %s, %s", method, route)
  374. // NOTE: scope issue, make sure the variables are local and won't be changed
  375. localRoute := route
  376. localFct := fct
  377. localMethod := method
  378. // build the handler function
  379. f := makeHTTPHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
  380. // add the new route
  381. if localRoute == "" {
  382. r.Methods(localMethod).HandlerFunc(f)
  383. } else {
  384. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  385. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  386. }
  387. }
  388. }
  389. return r
  390. }