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 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
70 Version string = "UNKNOWN"
72 root = flag.String("root", "./packages", "Path to packages directory")
73 bind = flag.String("bind", "[::]:8080", "Address to bind to")
74 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
75 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
76 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
77 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
78 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
79 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
80 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
81 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
82 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
83 version = flag.Bool("version", false, "Print version information")
84 warranty = flag.Bool("warranty", false, "Print warranty information")
89 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
90 path := filepath.Join(*root, dir)
91 if _, err := os.Stat(path); os.IsNotExist(err) {
92 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
93 http.Error(w, err.Error(), http.StatusInternalServerError)
96 log.Println(r.RemoteAddr, "mkdir", dir)
101 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
102 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
105 resp, err := http.Get(*pypiURL + dir + "/")
107 http.Error(w, err.Error(), http.StatusBadGateway)
110 body, err := ioutil.ReadAll(resp.Body)
113 http.Error(w, err.Error(), http.StatusBadGateway)
116 if !mkdirForPkg(w, r, dir) {
119 var submatches []string
125 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
126 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
127 if len(submatches) == 0 {
131 filename = submatches[2]
132 if pkgURL, err = url.Parse(uri); err != nil {
133 http.Error(w, err.Error(), http.StatusInternalServerError)
136 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
138 http.Error(w, err.Error(), http.StatusBadGateway)
141 if filename == filenameGet {
143 // Skip heavy remote call, when shutting down
144 http.Error(w, "shutting down", http.StatusInternalServerError)
147 log.Println(r.RemoteAddr, "pypi download", filename)
148 path = filepath.Join(*root, dir, filename)
149 resp, err = http.Get(uri)
151 http.Error(w, err.Error(), http.StatusBadGateway)
154 defer resp.Body.Close()
155 hasher := sha256.New()
156 dst, err := TempFile(filepath.Join(*root, dir))
158 http.Error(w, err.Error(), http.StatusInternalServerError)
161 wr := io.MultiWriter(hasher, dst)
162 if _, err = io.Copy(wr, resp.Body); err != nil {
163 os.Remove(dst.Name())
165 http.Error(w, err.Error(), http.StatusInternalServerError)
168 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
169 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
170 os.Remove(dst.Name())
172 http.Error(w, err.Error(), http.StatusBadGateway)
175 if err = dst.Sync(); err != nil {
176 os.Remove(dst.Name())
178 http.Error(w, err.Error(), http.StatusInternalServerError)
182 if err = os.Rename(dst.Name(), path); err != nil {
183 http.Error(w, err.Error(), http.StatusInternalServerError)
187 path = filepath.Join(*root, dir, filename+SHA256Ext)
188 _, err = os.Stat(path)
192 if !os.IsNotExist(err) {
193 http.Error(w, err.Error(), http.StatusInternalServerError)
196 log.Println(r.RemoteAddr, "pypi touch", filename)
197 if err = ioutil.WriteFile(path, digest, os.FileMode(0666)); err != nil {
198 http.Error(w, err.Error(), http.StatusInternalServerError)
205 func listRoot(w http.ResponseWriter, r *http.Request) {
206 files, err := ioutil.ReadDir(*root)
208 http.Error(w, err.Error(), http.StatusInternalServerError)
211 var result bytes.Buffer
212 result.WriteString(fmt.Sprintf(HTMLBegin, "root", "root"))
213 for _, file := range files {
214 if file.Mode().IsDir() {
215 result.WriteString(fmt.Sprintf(
217 *refreshURLPath+file.Name()+"/",
222 result.WriteString(HTMLEnd)
223 w.Write(result.Bytes())
226 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
227 dirPath := filepath.Join(*root, dir)
229 if !refreshDir(w, r, dir, "") {
232 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
235 files, err := ioutil.ReadDir(dirPath)
237 http.Error(w, err.Error(), http.StatusInternalServerError)
240 var result bytes.Buffer
241 result.WriteString(fmt.Sprintf(HTMLBegin, dir, dir))
243 var filenameClean string
244 for _, file := range files {
245 if !strings.HasSuffix(file.Name(), SHA256Ext) {
249 // Skip expensive I/O when shutting down
250 http.Error(w, "shutting down", http.StatusInternalServerError)
253 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
255 http.Error(w, err.Error(), http.StatusInternalServerError)
258 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
259 result.WriteString(fmt.Sprintf(
261 strings.Join([]string{
262 *refreshURLPath, dir, "/",
263 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
268 result.WriteString(HTMLEnd)
269 w.Write(result.Bytes())
272 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
273 log.Println(r.RemoteAddr, "get", filename)
274 path := filepath.Join(*root, dir, filename)
275 if _, err := os.Stat(path); os.IsNotExist(err) {
276 if !refreshDir(w, r, dir, filename) {
280 http.ServeFile(w, r, path)
283 func serveUpload(w http.ResponseWriter, r *http.Request) {
284 username, password, ok := r.BasicAuth()
286 log.Println(r.RemoteAddr, "unauthenticated", username)
287 http.Error(w, "unauthenticated", http.StatusUnauthorized)
290 auther, ok := passwords[username]
291 if !ok || !auther.Auth(password) {
292 log.Println(r.RemoteAddr, "unauthenticated", username)
293 http.Error(w, "unauthenticated", http.StatusUnauthorized)
297 if err = r.ParseMultipartForm(1 << 20); err != nil {
298 http.Error(w, err.Error(), http.StatusBadRequest)
301 for _, file := range r.MultipartForm.File["content"] {
302 filename := file.Filename
303 log.Println(r.RemoteAddr, "put", filename, "by", username)
304 dir := filename[:strings.LastIndex(filename, "-")]
305 dirPath := filepath.Join(*root, dir)
306 path := filepath.Join(dirPath, filename)
307 if _, err = os.Stat(path); err == nil {
308 log.Println(r.RemoteAddr, "already exists", filename)
309 http.Error(w, "Already exists", http.StatusBadRequest)
312 if !mkdirForPkg(w, r, dir) {
315 internalPath := filepath.Join(dirPath, InternalFlag)
317 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
318 if dst, err = os.Create(internalPath); err != nil {
319 http.Error(w, err.Error(), http.StatusInternalServerError)
324 src, err := file.Open()
327 http.Error(w, err.Error(), http.StatusInternalServerError)
330 dst, err = TempFile(dirPath)
332 http.Error(w, err.Error(), http.StatusInternalServerError)
335 hasher := sha256.New()
336 wr := io.MultiWriter(hasher, dst)
337 if _, err = io.Copy(wr, src); err != nil {
338 os.Remove(dst.Name())
340 http.Error(w, err.Error(), http.StatusInternalServerError)
343 if err = dst.Sync(); err != nil {
344 os.Remove(dst.Name())
346 http.Error(w, err.Error(), http.StatusInternalServerError)
350 if err = os.Rename(dst.Name(), path); err != nil {
351 http.Error(w, err.Error(), http.StatusInternalServerError)
354 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
355 http.Error(w, err.Error(), http.StatusInternalServerError)
361 func handler(w http.ResponseWriter, r *http.Request) {
362 if r.Method == "GET" {
365 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
366 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
369 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
372 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
374 http.Error(w, "invalid path", http.StatusBadRequest)
381 listDir(w, r, parts[0], autorefresh)
384 servePkg(w, r, parts[0], parts[1])
386 } else if r.Method == "POST" {
391 func goodIntegrity() bool {
392 dirs, err := ioutil.ReadDir(*root)
396 hasher := sha256.New()
397 digest := make([]byte, sha256.Size)
401 for _, dir := range dirs {
402 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
406 for _, file := range files {
407 if !strings.HasSuffix(file.Name(), SHA256Ext) {
410 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
411 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
413 if os.IsNotExist(err) {
419 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
423 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
424 log.Println(pkgName, "GOOD")
427 log.Println(pkgName, "BAD")
438 fmt.Println(Warranty)
442 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
446 if !goodIntegrity() {
455 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
456 log.Fatalln("Both -tls-cert and -tls-key are required")
459 log.Println("root:", *root, "bind:", *bind)
461 ln, err := net.Listen("tcp", *bind)
465 ln = netutil.LimitListener(ln, *maxClients)
466 server := &http.Server{
467 ReadTimeout: time.Minute,
468 WriteTimeout: time.Minute,
470 http.HandleFunc(*norefreshURLPath, handler)
471 http.HandleFunc(*refreshURLPath, handler)
473 needsRefreshPasswd := make(chan os.Signal, 0)
474 needsShutdown := make(chan os.Signal, 0)
475 exitErr := make(chan error, 0)
476 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
477 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
479 for range needsRefreshPasswd {
480 log.Println("Refreshing passwords")
484 go func(s *http.Server) {
487 log.Println("Shutting down")
488 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
489 exitErr <- s.Shutdown(ctx)
494 err = server.Serve(ln)
496 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
498 if err != http.ErrServerClosed {
501 if err := <-exitErr; err != nil {