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, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 // Python private package repository and caching proxy
41 HTMLBegin = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
42 HTMLEnd = "</body></html>"
43 HTMLElement = "<a href='%s'>%s</a><br/>\n"
44 SHA256Prefix = "sha256="
46 InternalFlag = ".internal"
48 Warranty = `This program is free software: you can redistribute it and/or modify
49 it under the terms of the GNU General Public License as published by
50 the Free Software Foundation, either version 3 of the License, or
51 (at your option) any later version.
53 This program is distributed in the hope that it will be useful,
54 but WITHOUT ANY WARRANTY; without even the implied warranty of
55 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
56 GNU General Public License for more details.
58 You should have received a copy of the GNU General Public License
59 along with this program. If not, see <http://www.gnu.org/licenses/>.`
63 root = flag.String("root", "./packages", "Path to packages directory")
64 bind = flag.String("bind", "[::]:8080", "Address to bind to")
65 simpleURLPath = flag.String("simple", "/simple/", "/simple/ URL path")
66 refreshURLPath = flag.String("refresh", "/refresh/", "Auto-refreshing URL path")
67 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
68 auth = flag.String("auth", "spam:foo", "login:password,...")
69 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
70 version = flag.Bool("version", false, "Print version information")
71 warranty = flag.Bool("warranty", false, "Print warranty information")
73 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
74 Version string = "UNKNOWN"
76 passwords map[string]string = make(map[string]string)
79 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
80 path := filepath.Join(*root, dir)
81 if _, err := os.Stat(path); os.IsNotExist(err) {
82 if err = os.Mkdir(path, 0700); err != nil {
83 http.Error(w, err.Error(), http.StatusInternalServerError)
86 log.Println(r.RemoteAddr, "mkdir", dir)
91 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
92 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
93 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
96 log.Println(r.RemoteAddr, "pypi refresh", dir)
97 resp, err := http.Get(*pypiURL + dir + "/")
99 http.Error(w, err.Error(), http.StatusBadGateway)
102 defer resp.Body.Close()
103 body, err := ioutil.ReadAll(resp.Body)
105 http.Error(w, err.Error(), http.StatusBadGateway)
108 if !mkdirForPkg(w, r, dir) {
111 var submatches []string
117 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
118 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
119 if len(submatches) == 0 {
123 filename = submatches[2]
124 if pkgURL, err = url.Parse(uri); err != nil {
125 http.Error(w, err.Error(), http.StatusInternalServerError)
128 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
130 http.Error(w, err.Error(), http.StatusBadGateway)
133 if filename == filenameGet {
134 log.Println(r.RemoteAddr, "pypi download", filename)
135 path = filepath.Join(*root, dir, filename)
136 resp, err = http.Get(uri)
138 http.Error(w, err.Error(), http.StatusBadGateway)
141 defer resp.Body.Close()
142 hasher := sha256.New()
143 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
145 http.Error(w, err.Error(), http.StatusInternalServerError)
148 wr := io.MultiWriter(hasher, dst)
149 if _, err = io.Copy(wr, resp.Body); err != nil {
150 os.Remove(dst.Name())
152 http.Error(w, err.Error(), http.StatusInternalServerError)
155 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
156 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
157 os.Remove(dst.Name())
159 http.Error(w, err.Error(), http.StatusBadGateway)
162 if err = dst.Sync(); err != nil {
163 os.Remove(dst.Name())
165 http.Error(w, err.Error(), http.StatusInternalServerError)
169 if err = os.Rename(dst.Name(), path); err != nil {
170 http.Error(w, err.Error(), http.StatusInternalServerError)
174 path = filepath.Join(*root, dir, filename+SHA256Ext)
175 _, err = os.Stat(path)
179 if !os.IsNotExist(err) {
180 http.Error(w, err.Error(), http.StatusInternalServerError)
184 log.Println(r.RemoteAddr, "pypi touch", filename)
185 if err = ioutil.WriteFile(path, digest, os.FileMode(0600)); err != nil {
186 http.Error(w, err.Error(), http.StatusInternalServerError)
193 func listRoot(w http.ResponseWriter, r *http.Request) {
194 log.Println(r.RemoteAddr, "root")
195 files, err := ioutil.ReadDir(*root)
197 http.Error(w, err.Error(), http.StatusInternalServerError)
200 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
201 for _, file := range files {
202 if file.Mode().IsDir() {
203 w.Write([]byte(fmt.Sprintf(
205 *simpleURLPath+file.Name()+"/",
210 w.Write([]byte(HTMLEnd))
213 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
214 log.Println(r.RemoteAddr, "dir", dir)
215 dirPath := filepath.Join(*root, dir)
217 if !refreshDir(w, r, dir, "") {
220 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
223 files, err := ioutil.ReadDir(dirPath)
225 http.Error(w, err.Error(), http.StatusInternalServerError)
228 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
230 var filenameClean string
231 for _, file := range files {
232 if !strings.HasSuffix(file.Name(), SHA256Ext) {
235 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
237 http.Error(w, err.Error(), http.StatusInternalServerError)
240 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
241 w.Write([]byte(fmt.Sprintf(
243 strings.Join([]string{
244 *simpleURLPath, dir, "/",
245 filenameClean, "#", SHA256Prefix, string(data),
250 w.Write([]byte(HTMLEnd))
253 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
254 log.Println(r.RemoteAddr, "pkg", filename)
255 path := filepath.Join(*root, dir, filename)
256 if _, err := os.Stat(path); os.IsNotExist(err) {
257 if !refreshDir(w, r, dir, filename) {
261 http.ServeFile(w, r, path)
264 func serveUpload(w http.ResponseWriter, r *http.Request) {
265 username, password, ok := r.BasicAuth()
266 if !ok || passwords[username] != password {
267 log.Println(r.RemoteAddr, "unauthenticated", username)
268 http.Error(w, "unauthenticated", http.StatusUnauthorized)
272 if err = r.ParseMultipartForm(1 << 20); err != nil {
273 http.Error(w, err.Error(), http.StatusBadRequest)
276 for _, file := range r.MultipartForm.File["content"] {
277 filename := file.Filename
278 log.Println(r.RemoteAddr, "upload", filename, "by", username)
279 dir := filename[:strings.LastIndex(filename, "-")]
280 dirPath := filepath.Join(*root, dir)
281 path := filepath.Join(dirPath, filename)
282 if _, err = os.Stat(path); err == nil {
283 log.Println(r.RemoteAddr, "already exists", filename)
284 http.Error(w, "Already exists", http.StatusBadRequest)
287 if !mkdirForPkg(w, r, dir) {
290 internalPath := filepath.Join(dirPath, InternalFlag)
292 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
293 if dst, err = os.Create(internalPath); err != nil {
294 http.Error(w, err.Error(), http.StatusInternalServerError)
299 src, err := file.Open()
302 http.Error(w, err.Error(), http.StatusInternalServerError)
305 dst, err = ioutil.TempFile(dirPath, "")
307 http.Error(w, err.Error(), http.StatusInternalServerError)
310 hasher := sha256.New()
311 wr := io.MultiWriter(hasher, dst)
312 if _, err = io.Copy(wr, src); err != nil {
313 os.Remove(dst.Name())
315 http.Error(w, err.Error(), http.StatusInternalServerError)
318 if err = dst.Sync(); err != nil {
319 os.Remove(dst.Name())
321 http.Error(w, err.Error(), http.StatusInternalServerError)
325 if err = os.Rename(dst.Name(), path); err != nil {
326 http.Error(w, err.Error(), http.StatusInternalServerError)
329 if err = ioutil.WriteFile(
334 http.Error(w, err.Error(), http.StatusInternalServerError)
340 func handler(w http.ResponseWriter, r *http.Request) {
341 if r.Method == "GET" {
344 if strings.HasPrefix(r.URL.Path, *simpleURLPath) {
345 path = strings.TrimPrefix(r.URL.Path, *simpleURLPath)
348 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
351 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
353 http.Error(w, "invalid path", http.StatusBadRequest)
360 listDir(w, r, parts[0], autorefresh)
363 servePkg(w, r, parts[0], parts[1])
365 } else if r.Method == "POST" {
370 func goodIntegrity() bool {
371 dirs, err := ioutil.ReadDir(*root)
375 hasher := sha256.New()
376 digest := make([]byte, sha256.Size)
380 for _, dir := range dirs {
381 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
385 for _, file := range files {
386 if !strings.HasSuffix(file.Name(), SHA256Ext) {
389 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
390 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
392 if os.IsNotExist(err) {
398 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
402 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
403 log.Println(pkgName, "GOOD")
406 log.Println(pkgName, "BAD")
417 fmt.Println(Warranty)
421 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
425 if !goodIntegrity() {
430 for _, credentials := range strings.Split(*auth, ",") {
431 splitted := strings.Split(credentials, ":")
432 if len(splitted) != 2 {
433 log.Fatal("Wrong auth format")
435 passwords[splitted[0]] = splitted[1]
437 log.Println("root:", *root, "bind:", *bind)
438 http.HandleFunc(*simpleURLPath, handler)
439 http.HandleFunc(*refreshURLPath, handler)
440 log.Fatal(http.ListenAndServe(*bind, nil))