k8s.io/kubernetes@v1.29.3/pkg/routes/logs.go (about) 1 /* 2 Copyright 2014 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package routes 18 19 import ( 20 "net/http" 21 "os" 22 "path" 23 24 "github.com/emicklei/go-restful/v3" 25 ) 26 27 // Logs adds handlers for the /logs path serving log files from /var/log. 28 type Logs struct{} 29 30 // Install func registers the logs handler. 31 func (l Logs) Install(c *restful.Container) { 32 // use restful: ws.Route(ws.GET("/logs/{logpath:*}").To(fileHandler)) 33 // See github.com/emicklei/go-restful/blob/master/examples/static/restful-serve-static.go 34 ws := new(restful.WebService) 35 ws.Path("/logs") 36 ws.Doc("get log files") 37 ws.Route(ws.GET("/{logpath:*}").To(logFileHandler).Param(ws.PathParameter("logpath", "path to the log").DataType("string"))) 38 ws.Route(ws.GET("/").To(logFileListHandler)) 39 40 c.Add(ws) 41 } 42 43 func logFileHandler(req *restful.Request, resp *restful.Response) { 44 logdir := "/var/log" 45 actual := path.Join(logdir, req.PathParameter("logpath")) 46 47 // check filename length first, return 404 if it's oversize. 48 if logFileNameIsTooLong(actual) { 49 http.Error(resp, "file not found", http.StatusNotFound) 50 return 51 } 52 http.ServeFile(resp.ResponseWriter, req.Request, actual) 53 } 54 55 func logFileListHandler(req *restful.Request, resp *restful.Response) { 56 logdir := "/var/log" 57 http.ServeFile(resp.ResponseWriter, req.Request, logdir) 58 } 59 60 // logFileNameIsTooLong checks filename length, returns true if it's longer than 255. 61 // cause http.ServeFile returns default error code 500 except for NotExist and Forbidden, but we need to separate the real 500 from oversize filename here. 62 func logFileNameIsTooLong(filePath string) bool { 63 _, err := os.Stat(filePath) 64 if err != nil { 65 if e, ok := err.(*os.PathError); ok && e.Err == fileNameTooLong { 66 return true 67 } 68 } 69 return false 70 }