2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019 Sergey Matveev <stargrave@stargrave.org>
4 2019 Elena Balakhonova <balakhonova_e@riseup.net>
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, version 3 of the License.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 // Python private package repository and caching proxy
44 "golang.org/x/net/netutil"
48 HTMLBegin = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
49 HTMLEnd = "</body></html>"
50 HTMLElement = "<a href='%s'>%s</a><br/>\n"
51 SHA256Prefix = "sha256="
53 InternalFlag = ".internal"
55 Warranty = `This program is free software: you can redistribute it and/or modify
56 it under the terms of the GNU General Public License as published by
57 the Free Software Foundation, version 3 of the License.
59 This program is distributed in the hope that it will be useful,
60 but WITHOUT ANY WARRANTY; without even the implied warranty of
61 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
62 GNU General Public License for more details.
64 You should have received a copy of the GNU General Public License
65 along with this program. If not, see <http://www.gnu.org/licenses/>.`
69 root = flag.String("root", "./packages", "Path to packages directory")
70 bind = flag.String("bind", "[::]:8080", "Address to bind to")
71 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
72 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
73 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
74 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
75 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
76 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
77 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
78 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
79 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
80 version = flag.Bool("version", false, "Print version information")
81 warranty = flag.Bool("warranty", false, "Print warranty information")
83 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
84 Version string = "UNKNOWN"
86 passwords map[string]Auther = make(map[string]Auther)
89 type Auther interface {
90 Auth(password string) bool
93 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
94 path := filepath.Join(*root, dir)
95 if _, err := os.Stat(path); os.IsNotExist(err) {
96 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
97 http.Error(w, err.Error(), http.StatusInternalServerError)
100 log.Println(r.RemoteAddr, "mkdir", dir)
105 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
106 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
107 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
110 log.Println(r.RemoteAddr, "pypi refresh", dir)
111 resp, err := http.Get(*pypiURL + dir + "/")
113 http.Error(w, err.Error(), http.StatusBadGateway)
116 defer resp.Body.Close()
117 body, err := ioutil.ReadAll(resp.Body)
119 http.Error(w, err.Error(), http.StatusBadGateway)
122 if !mkdirForPkg(w, r, dir) {
125 var submatches []string
131 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
132 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
133 if len(submatches) == 0 {
137 filename = submatches[2]
138 if pkgURL, err = url.Parse(uri); err != nil {
139 http.Error(w, err.Error(), http.StatusInternalServerError)
142 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
144 http.Error(w, err.Error(), http.StatusBadGateway)
147 if filename == filenameGet {
148 log.Println(r.RemoteAddr, "pypi download", filename)
149 path = filepath.Join(*root, dir, filename)
150 resp, err = http.Get(uri)
152 http.Error(w, err.Error(), http.StatusBadGateway)
155 defer resp.Body.Close()
156 hasher := sha256.New()
157 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
159 http.Error(w, err.Error(), http.StatusInternalServerError)
162 wr := io.MultiWriter(hasher, dst)
163 if _, err = io.Copy(wr, resp.Body); err != nil {
164 os.Remove(dst.Name())
166 http.Error(w, err.Error(), http.StatusInternalServerError)
169 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
170 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
171 os.Remove(dst.Name())
173 http.Error(w, err.Error(), http.StatusBadGateway)
176 if err = dst.Sync(); err != nil {
177 os.Remove(dst.Name())
179 http.Error(w, err.Error(), http.StatusInternalServerError)
183 if err = os.Rename(dst.Name(), path); err != nil {
184 http.Error(w, err.Error(), http.StatusInternalServerError)
188 path = filepath.Join(*root, dir, filename+SHA256Ext)
189 _, err = os.Stat(path)
193 if !os.IsNotExist(err) {
194 http.Error(w, err.Error(), http.StatusInternalServerError)
198 log.Println(r.RemoteAddr, "pypi touch", filename)
199 if err = ioutil.WriteFile(path, digest, os.FileMode(0666)); err != nil {
200 http.Error(w, err.Error(), http.StatusInternalServerError)
207 func listRoot(w http.ResponseWriter, r *http.Request) {
208 log.Println(r.RemoteAddr, "root")
209 files, err := ioutil.ReadDir(*root)
211 http.Error(w, err.Error(), http.StatusInternalServerError)
214 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
215 for _, file := range files {
216 if file.Mode().IsDir() {
217 w.Write([]byte(fmt.Sprintf(
219 *refreshURLPath+file.Name()+"/",
224 w.Write([]byte(HTMLEnd))
227 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
228 log.Println(r.RemoteAddr, "dir", dir)
229 dirPath := filepath.Join(*root, dir)
231 if !refreshDir(w, r, dir, "") {
234 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
237 files, err := ioutil.ReadDir(dirPath)
239 http.Error(w, err.Error(), http.StatusInternalServerError)
242 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
244 var filenameClean string
245 for _, file := range files {
246 if !strings.HasSuffix(file.Name(), SHA256Ext) {
249 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
251 http.Error(w, err.Error(), http.StatusInternalServerError)
254 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
255 w.Write([]byte(fmt.Sprintf(
257 strings.Join([]string{
258 *refreshURLPath, dir, "/",
259 filenameClean, "#", SHA256Prefix, string(data),
264 w.Write([]byte(HTMLEnd))
267 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
268 log.Println(r.RemoteAddr, "pkg", filename)
269 path := filepath.Join(*root, dir, filename)
270 if _, err := os.Stat(path); os.IsNotExist(err) {
271 if !refreshDir(w, r, dir, filename) {
275 http.ServeFile(w, r, path)
278 func serveUpload(w http.ResponseWriter, r *http.Request) {
279 username, password, ok := r.BasicAuth()
281 log.Println(r.RemoteAddr, "unauthenticated", username)
282 http.Error(w, "unauthenticated", http.StatusUnauthorized)
285 auther, ok := passwords[username]
286 if !ok || !auther.Auth(password) {
287 log.Println(r.RemoteAddr, "unauthenticated", username)
288 http.Error(w, "unauthenticated", http.StatusUnauthorized)
292 if err = r.ParseMultipartForm(1 << 20); err != nil {
293 http.Error(w, err.Error(), http.StatusBadRequest)
296 for _, file := range r.MultipartForm.File["content"] {
297 filename := file.Filename
298 log.Println(r.RemoteAddr, "upload", filename, "by", username)
299 dir := filename[:strings.LastIndex(filename, "-")]
300 dirPath := filepath.Join(*root, dir)
301 path := filepath.Join(dirPath, filename)
302 if _, err = os.Stat(path); err == nil {
303 log.Println(r.RemoteAddr, "already exists", filename)
304 http.Error(w, "Already exists", http.StatusBadRequest)
307 if !mkdirForPkg(w, r, dir) {
310 internalPath := filepath.Join(dirPath, InternalFlag)
312 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
313 if dst, err = os.Create(internalPath); err != nil {
314 http.Error(w, err.Error(), http.StatusInternalServerError)
319 src, err := file.Open()
322 http.Error(w, err.Error(), http.StatusInternalServerError)
325 dst, err = ioutil.TempFile(dirPath, "")
327 http.Error(w, err.Error(), http.StatusInternalServerError)
330 hasher := sha256.New()
331 wr := io.MultiWriter(hasher, dst)
332 if _, err = io.Copy(wr, src); err != nil {
333 os.Remove(dst.Name())
335 http.Error(w, err.Error(), http.StatusInternalServerError)
338 if err = dst.Sync(); err != nil {
339 os.Remove(dst.Name())
341 http.Error(w, err.Error(), http.StatusInternalServerError)
345 if err = os.Rename(dst.Name(), path); err != nil {
346 http.Error(w, err.Error(), http.StatusInternalServerError)
349 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
350 http.Error(w, err.Error(), http.StatusInternalServerError)
356 func handler(w http.ResponseWriter, r *http.Request) {
357 if r.Method == "GET" {
360 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
361 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
364 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
367 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
369 http.Error(w, "invalid path", http.StatusBadRequest)
376 listDir(w, r, parts[0], autorefresh)
379 servePkg(w, r, parts[0], parts[1])
381 } else if r.Method == "POST" {
386 func goodIntegrity() bool {
387 dirs, err := ioutil.ReadDir(*root)
391 hasher := sha256.New()
392 digest := make([]byte, sha256.Size)
396 for _, dir := range dirs {
397 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
401 for _, file := range files {
402 if !strings.HasSuffix(file.Name(), SHA256Ext) {
405 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
406 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
408 if os.IsNotExist(err) {
414 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
418 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
419 log.Println(pkgName, "GOOD")
422 log.Println(pkgName, "BAD")
433 fmt.Println(Warranty)
437 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
441 if !goodIntegrity() {
450 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
451 log.Fatalln("Both -tls-cert and -tls-key are required")
454 log.Println("root:", *root, "bind:", *bind)
456 ln, err := net.Listen("tcp", *bind)
460 ln = netutil.LimitListener(ln, *maxClients)
461 server := &http.Server{
462 ReadTimeout: time.Minute,
463 WriteTimeout: time.Minute,
465 http.HandleFunc(*norefreshURLPath, handler)
466 http.HandleFunc(*refreshURLPath, handler)
468 needsRefreshPasswd := make(chan os.Signal, 0)
469 needsShutdown := make(chan os.Signal, 0)
470 killed := make(chan error, 0)
471 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
472 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
474 for range needsRefreshPasswd {
475 log.Println("Refreshing passwords")
479 go func(s *http.Server) {
481 log.Println("Shutting down")
482 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
483 killed <- s.Shutdown(ctx)
488 err = server.Serve(ln)
490 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
492 if err != http.ErrServerClosed {
495 if err := <-killed; err != nil {