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 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
69 version = flag.Bool("version", false, "Print version information")
70 warranty = flag.Bool("warranty", false, "Print warranty information")
72 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
73 Version string = "UNKNOWN"
75 passwords map[string]Auther = make(map[string]Auther)
78 type Auther interface {
79 Auth(password string) bool
82 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
83 path := filepath.Join(*root, dir)
84 if _, err := os.Stat(path); os.IsNotExist(err) {
85 if err = os.Mkdir(path, 0700); err != nil {
86 http.Error(w, err.Error(), http.StatusInternalServerError)
89 log.Println(r.RemoteAddr, "mkdir", dir)
94 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
95 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
96 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
99 log.Println(r.RemoteAddr, "pypi refresh", dir)
100 resp, err := http.Get(*pypiURL + dir + "/")
102 http.Error(w, err.Error(), http.StatusBadGateway)
105 defer resp.Body.Close()
106 body, err := ioutil.ReadAll(resp.Body)
108 http.Error(w, err.Error(), http.StatusBadGateway)
111 if !mkdirForPkg(w, r, dir) {
114 var submatches []string
120 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
121 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
122 if len(submatches) == 0 {
126 filename = submatches[2]
127 if pkgURL, err = url.Parse(uri); err != nil {
128 http.Error(w, err.Error(), http.StatusInternalServerError)
131 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
133 http.Error(w, err.Error(), http.StatusBadGateway)
136 if filename == filenameGet {
137 log.Println(r.RemoteAddr, "pypi download", filename)
138 path = filepath.Join(*root, dir, filename)
139 resp, err = http.Get(uri)
141 http.Error(w, err.Error(), http.StatusBadGateway)
144 defer resp.Body.Close()
145 hasher := sha256.New()
146 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
148 http.Error(w, err.Error(), http.StatusInternalServerError)
151 wr := io.MultiWriter(hasher, dst)
152 if _, err = io.Copy(wr, resp.Body); err != nil {
153 os.Remove(dst.Name())
155 http.Error(w, err.Error(), http.StatusInternalServerError)
158 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
159 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
160 os.Remove(dst.Name())
162 http.Error(w, err.Error(), http.StatusBadGateway)
165 if err = dst.Sync(); err != nil {
166 os.Remove(dst.Name())
168 http.Error(w, err.Error(), http.StatusInternalServerError)
172 if err = os.Rename(dst.Name(), path); err != nil {
173 http.Error(w, err.Error(), http.StatusInternalServerError)
177 path = filepath.Join(*root, dir, filename+SHA256Ext)
178 _, err = os.Stat(path)
182 if !os.IsNotExist(err) {
183 http.Error(w, err.Error(), http.StatusInternalServerError)
187 log.Println(r.RemoteAddr, "pypi touch", filename)
188 if err = ioutil.WriteFile(path, digest, os.FileMode(0600)); err != nil {
189 http.Error(w, err.Error(), http.StatusInternalServerError)
196 func listRoot(w http.ResponseWriter, r *http.Request) {
197 log.Println(r.RemoteAddr, "root")
198 files, err := ioutil.ReadDir(*root)
200 http.Error(w, err.Error(), http.StatusInternalServerError)
203 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
204 for _, file := range files {
205 if file.Mode().IsDir() {
206 w.Write([]byte(fmt.Sprintf(
208 *refreshURLPath+file.Name()+"/",
213 w.Write([]byte(HTMLEnd))
216 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
217 log.Println(r.RemoteAddr, "dir", dir)
218 dirPath := filepath.Join(*root, dir)
220 if !refreshDir(w, r, dir, "") {
223 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
226 files, err := ioutil.ReadDir(dirPath)
228 http.Error(w, err.Error(), http.StatusInternalServerError)
231 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
233 var filenameClean string
234 for _, file := range files {
235 if !strings.HasSuffix(file.Name(), SHA256Ext) {
238 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
240 http.Error(w, err.Error(), http.StatusInternalServerError)
243 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
244 w.Write([]byte(fmt.Sprintf(
246 strings.Join([]string{
247 *refreshURLPath, dir, "/",
248 filenameClean, "#", SHA256Prefix, string(data),
253 w.Write([]byte(HTMLEnd))
256 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
257 log.Println(r.RemoteAddr, "pkg", filename)
258 path := filepath.Join(*root, dir, filename)
259 if _, err := os.Stat(path); os.IsNotExist(err) {
260 if !refreshDir(w, r, dir, filename) {
264 http.ServeFile(w, r, path)
267 func strToAuther(verifier string) (string, Auther, error) {
268 st := strings.SplitN(verifier, "$", 3)
269 if len(st) != 3 || st[0] != "" {
270 return "", nil, errors.New("invalid verifier structure")
277 auther, err = parseArgon2i(st[2])
279 auther, err = parseSHA256(st[2])
281 err = errors.New("unknown hashing algorithm")
283 return algorithm, auther, err
286 func serveUpload(w http.ResponseWriter, r *http.Request) {
287 username, password, ok := r.BasicAuth()
289 log.Println(r.RemoteAddr, "unauthenticated", username)
290 http.Error(w, "unauthenticated", http.StatusUnauthorized)
293 auther, ok := passwords[username]
294 if !ok || !auther.Auth(password) {
295 log.Println(r.RemoteAddr, "unauthenticated", username)
296 http.Error(w, "unauthenticated", http.StatusUnauthorized)
300 if err = r.ParseMultipartForm(1 << 20); err != nil {
301 http.Error(w, err.Error(), http.StatusBadRequest)
304 for _, file := range r.MultipartForm.File["content"] {
305 filename := file.Filename
306 log.Println(r.RemoteAddr, "upload", filename, "by", username)
307 dir := filename[:strings.LastIndex(filename, "-")]
308 dirPath := filepath.Join(*root, dir)
309 path := filepath.Join(dirPath, filename)
310 if _, err = os.Stat(path); err == nil {
311 log.Println(r.RemoteAddr, "already exists", filename)
312 http.Error(w, "Already exists", http.StatusBadRequest)
315 if !mkdirForPkg(w, r, dir) {
318 internalPath := filepath.Join(dirPath, InternalFlag)
320 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
321 if dst, err = os.Create(internalPath); err != nil {
322 http.Error(w, err.Error(), http.StatusInternalServerError)
327 src, err := file.Open()
330 http.Error(w, err.Error(), http.StatusInternalServerError)
333 dst, err = ioutil.TempFile(dirPath, "")
335 http.Error(w, err.Error(), http.StatusInternalServerError)
338 hasher := sha256.New()
339 wr := io.MultiWriter(hasher, dst)
340 if _, err = io.Copy(wr, src); err != nil {
341 os.Remove(dst.Name())
343 http.Error(w, err.Error(), http.StatusInternalServerError)
346 if err = dst.Sync(); err != nil {
347 os.Remove(dst.Name())
349 http.Error(w, err.Error(), http.StatusInternalServerError)
353 if err = os.Rename(dst.Name(), path); err != nil {
354 http.Error(w, err.Error(), http.StatusInternalServerError)
357 if err = ioutil.WriteFile(
362 http.Error(w, err.Error(), http.StatusInternalServerError)
368 func handler(w http.ResponseWriter, r *http.Request) {
369 if r.Method == "GET" {
372 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
373 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
376 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
379 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
381 http.Error(w, "invalid path", http.StatusBadRequest)
388 listDir(w, r, parts[0], autorefresh)
391 servePkg(w, r, parts[0], parts[1])
393 } else if r.Method == "POST" {
398 func goodIntegrity() bool {
399 dirs, err := ioutil.ReadDir(*root)
403 hasher := sha256.New()
404 digest := make([]byte, sha256.Size)
408 for _, dir := range dirs {
409 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
413 for _, file := range files {
414 if !strings.HasSuffix(file.Name(), SHA256Ext) {
417 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
418 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
420 if os.IsNotExist(err) {
426 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
430 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
431 log.Println(pkgName, "GOOD")
434 log.Println(pkgName, "BAD")
445 fmt.Println(Warranty)
449 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
453 if !goodIntegrity() {
459 log.Println("root:", *root, "bind:", *bind)
460 http.HandleFunc(*norefreshURLPath, handler)
461 http.HandleFunc(*refreshURLPath, handler)
462 log.Fatal(http.ListenAndServe(*bind, nil))