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
40 HTMLBegin = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
41 HTMLEnd = "</body></html>"
42 HTMLElement = "<a href='%s'>%s</a><br/>\n"
43 SHA256Prefix = "sha256="
45 InternalFlag = ".internal"
47 Warranty = `This program is free software: you can redistribute it and/or modify
48 it under the terms of the GNU General Public License as published by
49 the Free Software Foundation, version 3 of the License.
51 This program is distributed in the hope that it will be useful,
52 but WITHOUT ANY WARRANTY; without even the implied warranty of
53 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
54 GNU General Public License for more details.
56 You should have received a copy of the GNU General Public License
57 along with this program. If not, see <http://www.gnu.org/licenses/>.`
61 root = flag.String("root", "./packages", "Path to packages directory")
62 bind = flag.String("bind", "[::]:8080", "Address to bind to")
63 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
64 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
65 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
66 auth = flag.String("auth", "passwd", "Path to file with login:passwd")
67 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
68 version = flag.Bool("version", false, "Print version information")
69 warranty = flag.Bool("warranty", false, "Print warranty information")
71 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
72 Version string = "UNKNOWN"
74 passwords map[string]string = make(map[string]string)
77 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
78 path := filepath.Join(*root, dir)
79 if _, err := os.Stat(path); os.IsNotExist(err) {
80 if err = os.Mkdir(path, 0700); err != nil {
81 http.Error(w, err.Error(), http.StatusInternalServerError)
84 log.Println(r.RemoteAddr, "mkdir", dir)
89 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
90 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
91 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
94 log.Println(r.RemoteAddr, "pypi refresh", dir)
95 resp, err := http.Get(*pypiURL + dir + "/")
97 http.Error(w, err.Error(), http.StatusBadGateway)
100 defer resp.Body.Close()
101 body, err := ioutil.ReadAll(resp.Body)
103 http.Error(w, err.Error(), http.StatusBadGateway)
106 if !mkdirForPkg(w, r, dir) {
109 var submatches []string
115 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
116 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
117 if len(submatches) == 0 {
121 filename = submatches[2]
122 if pkgURL, err = url.Parse(uri); err != nil {
123 http.Error(w, err.Error(), http.StatusInternalServerError)
126 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
128 http.Error(w, err.Error(), http.StatusBadGateway)
131 if filename == filenameGet {
132 log.Println(r.RemoteAddr, "pypi download", filename)
133 path = filepath.Join(*root, dir, filename)
134 resp, err = http.Get(uri)
136 http.Error(w, err.Error(), http.StatusBadGateway)
139 defer resp.Body.Close()
140 hasher := sha256.New()
141 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
143 http.Error(w, err.Error(), http.StatusInternalServerError)
146 wr := io.MultiWriter(hasher, dst)
147 if _, err = io.Copy(wr, resp.Body); err != nil {
148 os.Remove(dst.Name())
150 http.Error(w, err.Error(), http.StatusInternalServerError)
153 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
154 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
155 os.Remove(dst.Name())
157 http.Error(w, err.Error(), http.StatusBadGateway)
160 if err = dst.Sync(); err != nil {
161 os.Remove(dst.Name())
163 http.Error(w, err.Error(), http.StatusInternalServerError)
167 if err = os.Rename(dst.Name(), path); err != nil {
168 http.Error(w, err.Error(), http.StatusInternalServerError)
172 path = filepath.Join(*root, dir, filename+SHA256Ext)
173 _, err = os.Stat(path)
177 if !os.IsNotExist(err) {
178 http.Error(w, err.Error(), http.StatusInternalServerError)
182 log.Println(r.RemoteAddr, "pypi touch", filename)
183 if err = ioutil.WriteFile(path, digest, os.FileMode(0600)); err != nil {
184 http.Error(w, err.Error(), http.StatusInternalServerError)
191 func listRoot(w http.ResponseWriter, r *http.Request) {
192 log.Println(r.RemoteAddr, "root")
193 files, err := ioutil.ReadDir(*root)
195 http.Error(w, err.Error(), http.StatusInternalServerError)
198 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
199 for _, file := range files {
200 if file.Mode().IsDir() {
201 w.Write([]byte(fmt.Sprintf(
203 *refreshURLPath+file.Name()+"/",
208 w.Write([]byte(HTMLEnd))
211 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
212 log.Println(r.RemoteAddr, "dir", dir)
213 dirPath := filepath.Join(*root, dir)
215 if !refreshDir(w, r, dir, "") {
218 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
221 files, err := ioutil.ReadDir(dirPath)
223 http.Error(w, err.Error(), http.StatusInternalServerError)
226 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
228 var filenameClean string
229 for _, file := range files {
230 if !strings.HasSuffix(file.Name(), SHA256Ext) {
233 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
235 http.Error(w, err.Error(), http.StatusInternalServerError)
238 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
239 w.Write([]byte(fmt.Sprintf(
241 strings.Join([]string{
242 *refreshURLPath, dir, "/",
243 filenameClean, "#", SHA256Prefix, string(data),
248 w.Write([]byte(HTMLEnd))
251 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
252 log.Println(r.RemoteAddr, "pkg", filename)
253 path := filepath.Join(*root, dir, filename)
254 if _, err := os.Stat(path); os.IsNotExist(err) {
255 if !refreshDir(w, r, dir, filename) {
259 http.ServeFile(w, r, path)
262 func serveUpload(w http.ResponseWriter, r *http.Request) {
263 username, password, ok := r.BasicAuth()
264 if !ok || passwords[username] != password {
265 log.Println(r.RemoteAddr, "unauthenticated", username)
266 http.Error(w, "unauthenticated", http.StatusUnauthorized)
270 if err = r.ParseMultipartForm(1 << 20); err != nil {
271 http.Error(w, err.Error(), http.StatusBadRequest)
274 for _, file := range r.MultipartForm.File["content"] {
275 filename := file.Filename
276 log.Println(r.RemoteAddr, "upload", filename, "by", username)
277 dir := filename[:strings.LastIndex(filename, "-")]
278 dirPath := filepath.Join(*root, dir)
279 path := filepath.Join(dirPath, filename)
280 if _, err = os.Stat(path); err == nil {
281 log.Println(r.RemoteAddr, "already exists", filename)
282 http.Error(w, "Already exists", http.StatusBadRequest)
285 if !mkdirForPkg(w, r, dir) {
288 internalPath := filepath.Join(dirPath, InternalFlag)
290 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
291 if dst, err = os.Create(internalPath); err != nil {
292 http.Error(w, err.Error(), http.StatusInternalServerError)
297 src, err := file.Open()
300 http.Error(w, err.Error(), http.StatusInternalServerError)
303 dst, err = ioutil.TempFile(dirPath, "")
305 http.Error(w, err.Error(), http.StatusInternalServerError)
308 hasher := sha256.New()
309 wr := io.MultiWriter(hasher, dst)
310 if _, err = io.Copy(wr, src); err != nil {
311 os.Remove(dst.Name())
313 http.Error(w, err.Error(), http.StatusInternalServerError)
316 if err = dst.Sync(); err != nil {
317 os.Remove(dst.Name())
319 http.Error(w, err.Error(), http.StatusInternalServerError)
323 if err = os.Rename(dst.Name(), path); err != nil {
324 http.Error(w, err.Error(), http.StatusInternalServerError)
327 if err = ioutil.WriteFile(
332 http.Error(w, err.Error(), http.StatusInternalServerError)
338 func handler(w http.ResponseWriter, r *http.Request) {
339 if r.Method == "GET" {
342 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
343 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
346 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
349 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
351 http.Error(w, "invalid path", http.StatusBadRequest)
358 listDir(w, r, parts[0], autorefresh)
361 servePkg(w, r, parts[0], parts[1])
363 } else if r.Method == "POST" {
368 func goodIntegrity() bool {
369 dirs, err := ioutil.ReadDir(*root)
373 hasher := sha256.New()
374 digest := make([]byte, sha256.Size)
378 for _, dir := range dirs {
379 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
383 for _, file := range files {
384 if !strings.HasSuffix(file.Name(), SHA256Ext) {
387 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
388 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
390 if os.IsNotExist(err) {
396 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
400 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
401 log.Println(pkgName, "GOOD")
404 log.Println(pkgName, "BAD")
415 fmt.Println(Warranty)
419 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
423 if !goodIntegrity() {
428 auth, err := ioutil.ReadFile(*auth)
432 for _, credentials := range strings.Split(strings.TrimRight(string(auth), "\n"), "\n") {
433 splitted := strings.Split(credentials, ":")
434 if len(splitted) != 2 {
435 log.Fatal("Wrong auth format")
437 passwords[splitted[0]] = splitted[1]
439 log.Println("root:", *root, "bind:", *bind)
440 http.HandleFunc(*norefreshURLPath, handler)
441 http.HandleFunc(*refreshURLPath, handler)
442 log.Fatal(http.ListenAndServe(*bind, nil))