2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 // Python private package repository and caching proxy
44 HTMLBegin = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
45 HTMLEnd = "</body></html>"
46 HTMLElement = "<a href='%s'>%s</a><br/>\n"
47 SHA256Prefix = "sha256="
49 InternalFlag = ".internal"
51 Warranty = `This program is free software: you can redistribute it and/or modify
52 it under the terms of the GNU General Public License as published by
53 the Free Software Foundation, version 3 of the License.
55 This program is distributed in the hope that it will be useful,
56 but WITHOUT ANY WARRANTY; without even the implied warranty of
57 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58 GNU General Public License for more details.
60 You should have received a copy of the GNU General Public License
61 along with this program. If not, see <http://www.gnu.org/licenses/>.`
65 root = flag.String("root", "./packages", "Path to packages directory")
66 bind = flag.String("bind", "[::]:8080", "Address to bind to")
67 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
68 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
69 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
70 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
71 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
72 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
73 version = flag.Bool("version", false, "Print version information")
74 warranty = flag.Bool("warranty", false, "Print warranty information")
76 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
77 Version string = "UNKNOWN"
79 passwords map[string]Auther = make(map[string]Auther)
82 type Auther interface {
83 Auth(password string) bool
86 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
87 path := filepath.Join(*root, dir)
88 if _, err := os.Stat(path); os.IsNotExist(err) {
89 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
90 http.Error(w, err.Error(), http.StatusInternalServerError)
93 log.Println(r.RemoteAddr, "mkdir", dir)
98 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
99 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
100 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
103 log.Println(r.RemoteAddr, "pypi refresh", dir)
104 resp, err := http.Get(*pypiURL + dir + "/")
106 http.Error(w, err.Error(), http.StatusBadGateway)
109 defer resp.Body.Close()
110 body, err := ioutil.ReadAll(resp.Body)
112 http.Error(w, err.Error(), http.StatusBadGateway)
115 if !mkdirForPkg(w, r, dir) {
118 var submatches []string
124 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
125 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
126 if len(submatches) == 0 {
130 filename = submatches[2]
131 if pkgURL, err = url.Parse(uri); err != nil {
132 http.Error(w, err.Error(), http.StatusInternalServerError)
135 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
137 http.Error(w, err.Error(), http.StatusBadGateway)
140 if filename == filenameGet {
141 log.Println(r.RemoteAddr, "pypi download", filename)
142 path = filepath.Join(*root, dir, filename)
143 resp, err = http.Get(uri)
145 http.Error(w, err.Error(), http.StatusBadGateway)
148 defer resp.Body.Close()
149 hasher := sha256.New()
150 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
152 http.Error(w, err.Error(), http.StatusInternalServerError)
155 wr := io.MultiWriter(hasher, dst)
156 if _, err = io.Copy(wr, resp.Body); err != nil {
157 os.Remove(dst.Name())
159 http.Error(w, err.Error(), http.StatusInternalServerError)
162 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
163 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
164 os.Remove(dst.Name())
166 http.Error(w, err.Error(), http.StatusBadGateway)
169 if err = dst.Sync(); err != nil {
170 os.Remove(dst.Name())
172 http.Error(w, err.Error(), http.StatusInternalServerError)
176 if err = os.Rename(dst.Name(), path); err != nil {
177 http.Error(w, err.Error(), http.StatusInternalServerError)
181 path = filepath.Join(*root, dir, filename+SHA256Ext)
182 _, err = os.Stat(path)
186 if !os.IsNotExist(err) {
187 http.Error(w, err.Error(), http.StatusInternalServerError)
191 log.Println(r.RemoteAddr, "pypi touch", filename)
192 if err = ioutil.WriteFile(path, digest, os.FileMode(0666)); err != nil {
193 http.Error(w, err.Error(), http.StatusInternalServerError)
200 func listRoot(w http.ResponseWriter, r *http.Request) {
201 log.Println(r.RemoteAddr, "root")
202 files, err := ioutil.ReadDir(*root)
204 http.Error(w, err.Error(), http.StatusInternalServerError)
207 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
208 for _, file := range files {
209 if file.Mode().IsDir() {
210 w.Write([]byte(fmt.Sprintf(
212 *refreshURLPath+file.Name()+"/",
217 w.Write([]byte(HTMLEnd))
220 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
221 log.Println(r.RemoteAddr, "dir", dir)
222 dirPath := filepath.Join(*root, dir)
224 if !refreshDir(w, r, dir, "") {
227 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
230 files, err := ioutil.ReadDir(dirPath)
232 http.Error(w, err.Error(), http.StatusInternalServerError)
235 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
237 var filenameClean string
238 for _, file := range files {
239 if !strings.HasSuffix(file.Name(), SHA256Ext) {
242 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
244 http.Error(w, err.Error(), http.StatusInternalServerError)
247 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
248 w.Write([]byte(fmt.Sprintf(
250 strings.Join([]string{
251 *refreshURLPath, dir, "/",
252 filenameClean, "#", SHA256Prefix, string(data),
257 w.Write([]byte(HTMLEnd))
260 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
261 log.Println(r.RemoteAddr, "pkg", filename)
262 path := filepath.Join(*root, dir, filename)
263 if _, err := os.Stat(path); os.IsNotExist(err) {
264 if !refreshDir(w, r, dir, filename) {
268 http.ServeFile(w, r, path)
271 func serveUpload(w http.ResponseWriter, r *http.Request) {
272 username, password, ok := r.BasicAuth()
274 log.Println(r.RemoteAddr, "unauthenticated", username)
275 http.Error(w, "unauthenticated", http.StatusUnauthorized)
278 auther, ok := passwords[username]
279 if !ok || !auther.Auth(password) {
280 log.Println(r.RemoteAddr, "unauthenticated", username)
281 http.Error(w, "unauthenticated", http.StatusUnauthorized)
285 if err = r.ParseMultipartForm(1 << 20); err != nil {
286 http.Error(w, err.Error(), http.StatusBadRequest)
289 for _, file := range r.MultipartForm.File["content"] {
290 filename := file.Filename
291 log.Println(r.RemoteAddr, "upload", filename, "by", username)
292 dir := filename[:strings.LastIndex(filename, "-")]
293 dirPath := filepath.Join(*root, dir)
294 path := filepath.Join(dirPath, filename)
295 if _, err = os.Stat(path); err == nil {
296 log.Println(r.RemoteAddr, "already exists", filename)
297 http.Error(w, "Already exists", http.StatusBadRequest)
300 if !mkdirForPkg(w, r, dir) {
303 internalPath := filepath.Join(dirPath, InternalFlag)
305 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
306 if dst, err = os.Create(internalPath); err != nil {
307 http.Error(w, err.Error(), http.StatusInternalServerError)
312 src, err := file.Open()
315 http.Error(w, err.Error(), http.StatusInternalServerError)
318 dst, err = ioutil.TempFile(dirPath, "")
320 http.Error(w, err.Error(), http.StatusInternalServerError)
323 hasher := sha256.New()
324 wr := io.MultiWriter(hasher, dst)
325 if _, err = io.Copy(wr, src); err != nil {
326 os.Remove(dst.Name())
328 http.Error(w, err.Error(), http.StatusInternalServerError)
331 if err = dst.Sync(); err != nil {
332 os.Remove(dst.Name())
334 http.Error(w, err.Error(), http.StatusInternalServerError)
338 if err = os.Rename(dst.Name(), path); err != nil {
339 http.Error(w, err.Error(), http.StatusInternalServerError)
342 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
343 http.Error(w, err.Error(), http.StatusInternalServerError)
349 func handler(w http.ResponseWriter, r *http.Request) {
350 if r.Method == "GET" {
353 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
354 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
357 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
360 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
362 http.Error(w, "invalid path", http.StatusBadRequest)
369 listDir(w, r, parts[0], autorefresh)
372 servePkg(w, r, parts[0], parts[1])
374 } else if r.Method == "POST" {
379 func goodIntegrity() bool {
380 dirs, err := ioutil.ReadDir(*root)
384 hasher := sha256.New()
385 digest := make([]byte, sha256.Size)
389 for _, dir := range dirs {
390 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
394 for _, file := range files {
395 if !strings.HasSuffix(file.Name(), SHA256Ext) {
398 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
399 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
401 if os.IsNotExist(err) {
407 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
411 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
412 log.Println(pkgName, "GOOD")
415 log.Println(pkgName, "BAD")
426 fmt.Println(Warranty)
430 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
434 if !goodIntegrity() {
444 log.Println("root:", *root, "bind:", *bind)
445 needsRefreshPasswd := make(chan os.Signal, 0)
446 needsShutdown := make(chan os.Signal, 0)
447 killed := make(chan error, 0)
448 http.HandleFunc(*norefreshURLPath, handler)
449 http.HandleFunc(*refreshURLPath, handler)
452 ReadTimeout: time.Minute,
453 WriteTimeout: time.Minute,
455 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
456 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
458 for range needsRefreshPasswd {
459 log.Println("Refreshing passwords")
463 go func(s *http.Server) {
465 log.Println("Shutting down")
466 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
467 killed <- s.Shutdown(ctx)
470 if err := s.ListenAndServe(); err != http.ErrServerClosed {
473 if err := <-killed; err != nil {