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
42 HTMLBegin = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
43 HTMLEnd = "</body></html>"
44 HTMLElement = "<a href='%s'>%s</a><br/>\n"
45 SHA256Prefix = "sha256="
47 InternalFlag = ".internal"
49 Warranty = `This program is free software: you can redistribute it and/or modify
50 it under the terms of the GNU General Public License as published by
51 the Free Software Foundation, version 3 of the License.
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 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
66 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
67 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
68 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
69 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
70 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
71 version = flag.Bool("version", false, "Print version information")
72 warranty = flag.Bool("warranty", false, "Print warranty information")
74 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
75 Version string = "UNKNOWN"
77 passwords map[string]Auther = make(map[string]Auther)
80 type Auther interface {
81 Auth(password string) bool
84 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
85 path := filepath.Join(*root, dir)
86 if _, err := os.Stat(path); os.IsNotExist(err) {
87 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
88 http.Error(w, err.Error(), http.StatusInternalServerError)
91 log.Println(r.RemoteAddr, "mkdir", dir)
96 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
97 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
98 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
101 log.Println(r.RemoteAddr, "pypi refresh", dir)
102 resp, err := http.Get(*pypiURL + dir + "/")
104 http.Error(w, err.Error(), http.StatusBadGateway)
107 defer resp.Body.Close()
108 body, err := ioutil.ReadAll(resp.Body)
110 http.Error(w, err.Error(), http.StatusBadGateway)
113 if !mkdirForPkg(w, r, dir) {
116 var submatches []string
122 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
123 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
124 if len(submatches) == 0 {
128 filename = submatches[2]
129 if pkgURL, err = url.Parse(uri); err != nil {
130 http.Error(w, err.Error(), http.StatusInternalServerError)
133 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
135 http.Error(w, err.Error(), http.StatusBadGateway)
138 if filename == filenameGet {
139 log.Println(r.RemoteAddr, "pypi download", filename)
140 path = filepath.Join(*root, dir, filename)
141 resp, err = http.Get(uri)
143 http.Error(w, err.Error(), http.StatusBadGateway)
146 defer resp.Body.Close()
147 hasher := sha256.New()
148 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
150 http.Error(w, err.Error(), http.StatusInternalServerError)
153 wr := io.MultiWriter(hasher, dst)
154 if _, err = io.Copy(wr, resp.Body); err != nil {
155 os.Remove(dst.Name())
157 http.Error(w, err.Error(), http.StatusInternalServerError)
160 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
161 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
162 os.Remove(dst.Name())
164 http.Error(w, err.Error(), http.StatusBadGateway)
167 if err = dst.Sync(); err != nil {
168 os.Remove(dst.Name())
170 http.Error(w, err.Error(), http.StatusInternalServerError)
174 if err = os.Rename(dst.Name(), path); err != nil {
175 http.Error(w, err.Error(), http.StatusInternalServerError)
179 path = filepath.Join(*root, dir, filename+SHA256Ext)
180 _, err = os.Stat(path)
184 if !os.IsNotExist(err) {
185 http.Error(w, err.Error(), http.StatusInternalServerError)
189 log.Println(r.RemoteAddr, "pypi touch", filename)
190 if err = ioutil.WriteFile(path, digest, os.FileMode(0666)); err != nil {
191 http.Error(w, err.Error(), http.StatusInternalServerError)
198 func listRoot(w http.ResponseWriter, r *http.Request) {
199 log.Println(r.RemoteAddr, "root")
200 files, err := ioutil.ReadDir(*root)
202 http.Error(w, err.Error(), http.StatusInternalServerError)
205 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
206 for _, file := range files {
207 if file.Mode().IsDir() {
208 w.Write([]byte(fmt.Sprintf(
210 *refreshURLPath+file.Name()+"/",
215 w.Write([]byte(HTMLEnd))
218 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
219 log.Println(r.RemoteAddr, "dir", dir)
220 dirPath := filepath.Join(*root, dir)
222 if !refreshDir(w, r, dir, "") {
225 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
228 files, err := ioutil.ReadDir(dirPath)
230 http.Error(w, err.Error(), http.StatusInternalServerError)
233 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
235 var filenameClean string
236 for _, file := range files {
237 if !strings.HasSuffix(file.Name(), SHA256Ext) {
240 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
242 http.Error(w, err.Error(), http.StatusInternalServerError)
245 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
246 w.Write([]byte(fmt.Sprintf(
248 strings.Join([]string{
249 *refreshURLPath, dir, "/",
250 filenameClean, "#", SHA256Prefix, string(data),
255 w.Write([]byte(HTMLEnd))
258 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
259 log.Println(r.RemoteAddr, "pkg", filename)
260 path := filepath.Join(*root, dir, filename)
261 if _, err := os.Stat(path); os.IsNotExist(err) {
262 if !refreshDir(w, r, dir, filename) {
266 http.ServeFile(w, r, path)
269 func serveUpload(w http.ResponseWriter, r *http.Request) {
270 username, password, ok := r.BasicAuth()
272 log.Println(r.RemoteAddr, "unauthenticated", username)
273 http.Error(w, "unauthenticated", http.StatusUnauthorized)
276 auther, ok := passwords[username]
277 if !ok || !auther.Auth(password) {
278 log.Println(r.RemoteAddr, "unauthenticated", username)
279 http.Error(w, "unauthenticated", http.StatusUnauthorized)
283 if err = r.ParseMultipartForm(1 << 20); err != nil {
284 http.Error(w, err.Error(), http.StatusBadRequest)
287 for _, file := range r.MultipartForm.File["content"] {
288 filename := file.Filename
289 log.Println(r.RemoteAddr, "upload", filename, "by", username)
290 dir := filename[:strings.LastIndex(filename, "-")]
291 dirPath := filepath.Join(*root, dir)
292 path := filepath.Join(dirPath, filename)
293 if _, err = os.Stat(path); err == nil {
294 log.Println(r.RemoteAddr, "already exists", filename)
295 http.Error(w, "Already exists", http.StatusBadRequest)
298 if !mkdirForPkg(w, r, dir) {
301 internalPath := filepath.Join(dirPath, InternalFlag)
303 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
304 if dst, err = os.Create(internalPath); err != nil {
305 http.Error(w, err.Error(), http.StatusInternalServerError)
310 src, err := file.Open()
313 http.Error(w, err.Error(), http.StatusInternalServerError)
316 dst, err = ioutil.TempFile(dirPath, "")
318 http.Error(w, err.Error(), http.StatusInternalServerError)
321 hasher := sha256.New()
322 wr := io.MultiWriter(hasher, dst)
323 if _, err = io.Copy(wr, src); err != nil {
324 os.Remove(dst.Name())
326 http.Error(w, err.Error(), http.StatusInternalServerError)
329 if err = dst.Sync(); err != nil {
330 os.Remove(dst.Name())
332 http.Error(w, err.Error(), http.StatusInternalServerError)
336 if err = os.Rename(dst.Name(), path); err != nil {
337 http.Error(w, err.Error(), http.StatusInternalServerError)
340 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
341 http.Error(w, err.Error(), http.StatusInternalServerError)
347 func handler(w http.ResponseWriter, r *http.Request) {
348 if r.Method == "GET" {
351 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
352 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
355 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
358 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
360 http.Error(w, "invalid path", http.StatusBadRequest)
367 listDir(w, r, parts[0], autorefresh)
370 servePkg(w, r, parts[0], parts[1])
372 } else if r.Method == "POST" {
377 func goodIntegrity() bool {
378 dirs, err := ioutil.ReadDir(*root)
382 hasher := sha256.New()
383 digest := make([]byte, sha256.Size)
387 for _, dir := range dirs {
388 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
392 for _, file := range files {
393 if !strings.HasSuffix(file.Name(), SHA256Ext) {
396 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
397 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
399 if os.IsNotExist(err) {
405 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
409 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
410 log.Println(pkgName, "GOOD")
413 log.Println(pkgName, "BAD")
424 fmt.Println(Warranty)
428 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
432 if !goodIntegrity() {
442 log.Println("root:", *root, "bind:", *bind)
443 needsRefreshPasswd := make(chan os.Signal, 0)
444 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
446 for range needsRefreshPasswd {
447 log.Println("Refreshing passwords")
451 http.HandleFunc(*norefreshURLPath, handler)
452 http.HandleFunc(*refreshURLPath, handler)
453 log.Fatal(http.ListenAndServe(*bind, nil))