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
43 HTMLBegin = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
44 HTMLEnd = "</body></html>"
45 HTMLElement = "<a href='%s'>%s</a><br/>\n"
46 SHA256Prefix = "sha256="
48 InternalFlag = ".internal"
50 Warranty = `This program is free software: you can redistribute it and/or modify
51 it under the terms of the GNU General Public License as published by
52 the Free Software Foundation, version 3 of the License.
54 This program is distributed in the hope that it will be useful,
55 but WITHOUT ANY WARRANTY; without even the implied warranty of
56 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
57 GNU General Public License for more details.
59 You should have received a copy of the GNU General Public License
60 along with this program. If not, see <http://www.gnu.org/licenses/>.`
64 root = flag.String("root", "./packages", "Path to packages directory")
65 bind = flag.String("bind", "[::]:8080", "Address to bind to")
66 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
67 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
68 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
69 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
70 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
71 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
72 version = flag.Bool("version", false, "Print version information")
73 warranty = flag.Bool("warranty", false, "Print warranty information")
75 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
76 Version string = "UNKNOWN"
78 passwords map[string]Auther = make(map[string]Auther)
81 type Auther interface {
82 Auth(password string) bool
85 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
86 path := filepath.Join(*root, dir)
87 if _, err := os.Stat(path); os.IsNotExist(err) {
88 if err = os.Mkdir(path, 0700); err != nil {
89 http.Error(w, err.Error(), http.StatusInternalServerError)
92 log.Println(r.RemoteAddr, "mkdir", dir)
97 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
98 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
99 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
102 log.Println(r.RemoteAddr, "pypi refresh", dir)
103 resp, err := http.Get(*pypiURL + dir + "/")
105 http.Error(w, err.Error(), http.StatusBadGateway)
108 defer resp.Body.Close()
109 body, err := ioutil.ReadAll(resp.Body)
111 http.Error(w, err.Error(), http.StatusBadGateway)
114 if !mkdirForPkg(w, r, dir) {
117 var submatches []string
123 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
124 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
125 if len(submatches) == 0 {
129 filename = submatches[2]
130 if pkgURL, err = url.Parse(uri); err != nil {
131 http.Error(w, err.Error(), http.StatusInternalServerError)
134 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
136 http.Error(w, err.Error(), http.StatusBadGateway)
139 if filename == filenameGet {
140 log.Println(r.RemoteAddr, "pypi download", filename)
141 path = filepath.Join(*root, dir, filename)
142 resp, err = http.Get(uri)
144 http.Error(w, err.Error(), http.StatusBadGateway)
147 defer resp.Body.Close()
148 hasher := sha256.New()
149 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
151 http.Error(w, err.Error(), http.StatusInternalServerError)
154 wr := io.MultiWriter(hasher, dst)
155 if _, err = io.Copy(wr, resp.Body); err != nil {
156 os.Remove(dst.Name())
158 http.Error(w, err.Error(), http.StatusInternalServerError)
161 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
162 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
163 os.Remove(dst.Name())
165 http.Error(w, err.Error(), http.StatusBadGateway)
168 if err = dst.Sync(); err != nil {
169 os.Remove(dst.Name())
171 http.Error(w, err.Error(), http.StatusInternalServerError)
175 if err = os.Rename(dst.Name(), path); err != nil {
176 http.Error(w, err.Error(), http.StatusInternalServerError)
180 path = filepath.Join(*root, dir, filename+SHA256Ext)
181 _, err = os.Stat(path)
185 if !os.IsNotExist(err) {
186 http.Error(w, err.Error(), http.StatusInternalServerError)
190 log.Println(r.RemoteAddr, "pypi touch", filename)
191 if err = ioutil.WriteFile(path, digest, os.FileMode(0600)); err != nil {
192 http.Error(w, err.Error(), http.StatusInternalServerError)
199 func listRoot(w http.ResponseWriter, r *http.Request) {
200 log.Println(r.RemoteAddr, "root")
201 files, err := ioutil.ReadDir(*root)
203 http.Error(w, err.Error(), http.StatusInternalServerError)
206 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
207 for _, file := range files {
208 if file.Mode().IsDir() {
209 w.Write([]byte(fmt.Sprintf(
211 *refreshURLPath+file.Name()+"/",
216 w.Write([]byte(HTMLEnd))
219 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
220 log.Println(r.RemoteAddr, "dir", dir)
221 dirPath := filepath.Join(*root, dir)
223 if !refreshDir(w, r, dir, "") {
226 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
229 files, err := ioutil.ReadDir(dirPath)
231 http.Error(w, err.Error(), http.StatusInternalServerError)
234 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
236 var filenameClean string
237 for _, file := range files {
238 if !strings.HasSuffix(file.Name(), SHA256Ext) {
241 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
243 http.Error(w, err.Error(), http.StatusInternalServerError)
246 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
247 w.Write([]byte(fmt.Sprintf(
249 strings.Join([]string{
250 *refreshURLPath, dir, "/",
251 filenameClean, "#", SHA256Prefix, string(data),
256 w.Write([]byte(HTMLEnd))
259 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
260 log.Println(r.RemoteAddr, "pkg", filename)
261 path := filepath.Join(*root, dir, filename)
262 if _, err := os.Stat(path); os.IsNotExist(err) {
263 if !refreshDir(w, r, dir, filename) {
267 http.ServeFile(w, r, path)
270 func strToAuther(verifier string) (string, Auther, error) {
271 st := strings.SplitN(verifier, "$", 3)
272 if len(st) != 3 || st[0] != "" {
273 return "", nil, errors.New("invalid verifier structure")
280 auther, err = parseArgon2i(st[2])
282 auther, err = parseSHA256(st[2])
284 err = errors.New("unknown hashing algorithm")
286 return algorithm, auther, err
289 func serveUpload(w http.ResponseWriter, r *http.Request) {
290 username, password, ok := r.BasicAuth()
292 log.Println(r.RemoteAddr, "unauthenticated", username)
293 http.Error(w, "unauthenticated", http.StatusUnauthorized)
296 auther, ok := passwords[username]
297 if !ok || !auther.Auth(password) {
298 log.Println(r.RemoteAddr, "unauthenticated", username)
299 http.Error(w, "unauthenticated", http.StatusUnauthorized)
303 if err = r.ParseMultipartForm(1 << 20); err != nil {
304 http.Error(w, err.Error(), http.StatusBadRequest)
307 for _, file := range r.MultipartForm.File["content"] {
308 filename := file.Filename
309 log.Println(r.RemoteAddr, "upload", filename, "by", username)
310 dir := filename[:strings.LastIndex(filename, "-")]
311 dirPath := filepath.Join(*root, dir)
312 path := filepath.Join(dirPath, filename)
313 if _, err = os.Stat(path); err == nil {
314 log.Println(r.RemoteAddr, "already exists", filename)
315 http.Error(w, "Already exists", http.StatusBadRequest)
318 if !mkdirForPkg(w, r, dir) {
321 internalPath := filepath.Join(dirPath, InternalFlag)
323 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
324 if dst, err = os.Create(internalPath); err != nil {
325 http.Error(w, err.Error(), http.StatusInternalServerError)
330 src, err := file.Open()
333 http.Error(w, err.Error(), http.StatusInternalServerError)
336 dst, err = ioutil.TempFile(dirPath, "")
338 http.Error(w, err.Error(), http.StatusInternalServerError)
341 hasher := sha256.New()
342 wr := io.MultiWriter(hasher, dst)
343 if _, err = io.Copy(wr, src); err != nil {
344 os.Remove(dst.Name())
346 http.Error(w, err.Error(), http.StatusInternalServerError)
349 if err = dst.Sync(); err != nil {
350 os.Remove(dst.Name())
352 http.Error(w, err.Error(), http.StatusInternalServerError)
356 if err = os.Rename(dst.Name(), path); err != nil {
357 http.Error(w, err.Error(), http.StatusInternalServerError)
360 if err = ioutil.WriteFile(
365 http.Error(w, err.Error(), http.StatusInternalServerError)
371 func handler(w http.ResponseWriter, r *http.Request) {
372 if r.Method == "GET" {
375 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
376 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
379 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
382 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
384 http.Error(w, "invalid path", http.StatusBadRequest)
391 listDir(w, r, parts[0], autorefresh)
394 servePkg(w, r, parts[0], parts[1])
396 } else if r.Method == "POST" {
401 func goodIntegrity() bool {
402 dirs, err := ioutil.ReadDir(*root)
406 hasher := sha256.New()
407 digest := make([]byte, sha256.Size)
411 for _, dir := range dirs {
412 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
416 for _, file := range files {
417 if !strings.HasSuffix(file.Name(), SHA256Ext) {
420 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
421 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
423 if os.IsNotExist(err) {
429 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
433 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
434 log.Println(pkgName, "GOOD")
437 log.Println(pkgName, "BAD")
448 fmt.Println(Warranty)
452 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
456 if !goodIntegrity() {
466 log.Println("root:", *root, "bind:", *bind)
467 needsRefreshPasswd := make(chan os.Signal, 0)
468 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
470 for range needsRefreshPasswd {
474 http.HandleFunc(*norefreshURLPath, handler)
475 http.HandleFunc(*refreshURLPath, handler)
476 log.Fatal(http.ListenAndServe(*bind, nil))