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
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, version 3 of the License.
52 This program is distributed in the hope that it will be useful,
53 but WITHOUT ANY WARRANTY; without even the implied warranty of
54 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55 GNU General Public License for more details.
57 You should have received a copy of the GNU General Public License
58 along with this program. If not, see <http://www.gnu.org/licenses/>.`
62 root = flag.String("root", "./packages", "Path to packages directory")
63 bind = flag.String("bind", "[::]:8080", "Address to bind to")
64 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
65 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
66 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
67 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
68 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
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]Auther = make(map[string]Auther)
79 type Auther interface {
80 Auth(password string) bool
83 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
84 path := filepath.Join(*root, dir)
85 if _, err := os.Stat(path); os.IsNotExist(err) {
86 if err = os.Mkdir(path, 0700); err != nil {
87 http.Error(w, err.Error(), http.StatusInternalServerError)
90 log.Println(r.RemoteAddr, "mkdir", dir)
95 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
96 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
97 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
100 log.Println(r.RemoteAddr, "pypi refresh", dir)
101 resp, err := http.Get(*pypiURL + dir + "/")
103 http.Error(w, err.Error(), http.StatusBadGateway)
106 defer resp.Body.Close()
107 body, err := ioutil.ReadAll(resp.Body)
109 http.Error(w, err.Error(), http.StatusBadGateway)
112 if !mkdirForPkg(w, r, dir) {
115 var submatches []string
121 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
122 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
123 if len(submatches) == 0 {
127 filename = submatches[2]
128 if pkgURL, err = url.Parse(uri); err != nil {
129 http.Error(w, err.Error(), http.StatusInternalServerError)
132 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
134 http.Error(w, err.Error(), http.StatusBadGateway)
137 if filename == filenameGet {
138 log.Println(r.RemoteAddr, "pypi download", filename)
139 path = filepath.Join(*root, dir, filename)
140 resp, err = http.Get(uri)
142 http.Error(w, err.Error(), http.StatusBadGateway)
145 defer resp.Body.Close()
146 hasher := sha256.New()
147 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
149 http.Error(w, err.Error(), http.StatusInternalServerError)
152 wr := io.MultiWriter(hasher, dst)
153 if _, err = io.Copy(wr, resp.Body); err != nil {
154 os.Remove(dst.Name())
156 http.Error(w, err.Error(), http.StatusInternalServerError)
159 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
160 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
161 os.Remove(dst.Name())
163 http.Error(w, err.Error(), http.StatusBadGateway)
166 if err = dst.Sync(); err != nil {
167 os.Remove(dst.Name())
169 http.Error(w, err.Error(), http.StatusInternalServerError)
173 if err = os.Rename(dst.Name(), path); err != nil {
174 http.Error(w, err.Error(), http.StatusInternalServerError)
178 path = filepath.Join(*root, dir, filename+SHA256Ext)
179 _, err = os.Stat(path)
183 if !os.IsNotExist(err) {
184 http.Error(w, err.Error(), http.StatusInternalServerError)
188 log.Println(r.RemoteAddr, "pypi touch", filename)
189 if err = ioutil.WriteFile(path, digest, os.FileMode(0600)); err != nil {
190 http.Error(w, err.Error(), http.StatusInternalServerError)
197 func listRoot(w http.ResponseWriter, r *http.Request) {
198 log.Println(r.RemoteAddr, "root")
199 files, err := ioutil.ReadDir(*root)
201 http.Error(w, err.Error(), http.StatusInternalServerError)
204 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
205 for _, file := range files {
206 if file.Mode().IsDir() {
207 w.Write([]byte(fmt.Sprintf(
209 *refreshURLPath+file.Name()+"/",
214 w.Write([]byte(HTMLEnd))
217 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
218 log.Println(r.RemoteAddr, "dir", dir)
219 dirPath := filepath.Join(*root, dir)
221 if !refreshDir(w, r, dir, "") {
224 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
227 files, err := ioutil.ReadDir(dirPath)
229 http.Error(w, err.Error(), http.StatusInternalServerError)
232 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
234 var filenameClean string
235 for _, file := range files {
236 if !strings.HasSuffix(file.Name(), SHA256Ext) {
239 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
241 http.Error(w, err.Error(), http.StatusInternalServerError)
244 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
245 w.Write([]byte(fmt.Sprintf(
247 strings.Join([]string{
248 *refreshURLPath, dir, "/",
249 filenameClean, "#", SHA256Prefix, string(data),
254 w.Write([]byte(HTMLEnd))
257 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
258 log.Println(r.RemoteAddr, "pkg", filename)
259 path := filepath.Join(*root, dir, filename)
260 if _, err := os.Stat(path); os.IsNotExist(err) {
261 if !refreshDir(w, r, dir, filename) {
265 http.ServeFile(w, r, path)
268 func strToAuther(verifier string) (string, Auther, error) {
269 st := strings.SplitN(verifier, "$", 3)
270 if len(st) != 3 || st[0] != "" {
271 return "", nil, errors.New("invalid verifier structure")
278 auther, err = parseArgon2i(st[2])
280 auther, err = parseSHA256(st[2])
282 err = errors.New("unknown hashing algorithm")
284 return algorithm, auther, err
287 func serveUpload(w http.ResponseWriter, r *http.Request) {
288 username, password, ok := r.BasicAuth()
290 log.Println(r.RemoteAddr, "unauthenticated", username)
291 http.Error(w, "unauthenticated", http.StatusUnauthorized)
294 auther, ok := passwords[username]
295 if !ok || !auther.Auth(password) {
296 log.Println(r.RemoteAddr, "unauthenticated", username)
297 http.Error(w, "unauthenticated", http.StatusUnauthorized)
301 if err = r.ParseMultipartForm(1 << 20); err != nil {
302 http.Error(w, err.Error(), http.StatusBadRequest)
305 for _, file := range r.MultipartForm.File["content"] {
306 filename := file.Filename
307 log.Println(r.RemoteAddr, "upload", filename, "by", username)
308 dir := filename[:strings.LastIndex(filename, "-")]
309 dirPath := filepath.Join(*root, dir)
310 path := filepath.Join(dirPath, filename)
311 if _, err = os.Stat(path); err == nil {
312 log.Println(r.RemoteAddr, "already exists", filename)
313 http.Error(w, "Already exists", http.StatusBadRequest)
316 if !mkdirForPkg(w, r, dir) {
319 internalPath := filepath.Join(dirPath, InternalFlag)
321 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
322 if dst, err = os.Create(internalPath); err != nil {
323 http.Error(w, err.Error(), http.StatusInternalServerError)
328 src, err := file.Open()
331 http.Error(w, err.Error(), http.StatusInternalServerError)
334 dst, err = ioutil.TempFile(dirPath, "")
336 http.Error(w, err.Error(), http.StatusInternalServerError)
339 hasher := sha256.New()
340 wr := io.MultiWriter(hasher, dst)
341 if _, err = io.Copy(wr, src); err != nil {
342 os.Remove(dst.Name())
344 http.Error(w, err.Error(), http.StatusInternalServerError)
347 if err = dst.Sync(); err != nil {
348 os.Remove(dst.Name())
350 http.Error(w, err.Error(), http.StatusInternalServerError)
354 if err = os.Rename(dst.Name(), path); err != nil {
355 http.Error(w, err.Error(), http.StatusInternalServerError)
358 if err = ioutil.WriteFile(
363 http.Error(w, err.Error(), http.StatusInternalServerError)
369 func handler(w http.ResponseWriter, r *http.Request) {
370 if r.Method == "GET" {
373 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
374 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
377 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
380 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
382 http.Error(w, "invalid path", http.StatusBadRequest)
389 listDir(w, r, parts[0], autorefresh)
392 servePkg(w, r, parts[0], parts[1])
394 } else if r.Method == "POST" {
399 func goodIntegrity() bool {
400 dirs, err := ioutil.ReadDir(*root)
404 hasher := sha256.New()
405 digest := make([]byte, sha256.Size)
409 for _, dir := range dirs {
410 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
414 for _, file := range files {
415 if !strings.HasSuffix(file.Name(), SHA256Ext) {
418 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
419 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
421 if os.IsNotExist(err) {
427 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
431 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
432 log.Println(pkgName, "GOOD")
435 log.Println(pkgName, "BAD")
446 fmt.Println(Warranty)
450 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
454 if !goodIntegrity() {
464 log.Println("root:", *root, "bind:", *bind)
465 http.HandleFunc(*norefreshURLPath, handler)
466 http.HandleFunc(*refreshURLPath, handler)
467 log.Fatal(http.ListenAndServe(*bind, nil))