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>
51 <title>Links for %s</title>
55 HTMLEnd = " </body>\n</html>\n"
56 HTMLElement = " <a href=\"%s\"%s>%s</a><br/>\n"
57 SHA256Prefix = "sha256="
59 InternalFlag = ".internal"
61 GPGSigAttr = " data-gpg-sig=true"
63 Warranty = `This program is free software: you can redistribute it and/or modify
64 it under the terms of the GNU General Public License as published by
65 the Free Software Foundation, version 3 of the License.
67 This program is distributed in the hope that it will be useful,
68 but WITHOUT ANY WARRANTY; without even the implied warranty of
69 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70 GNU General Public License for more details.
72 You should have received a copy of the GNU General Public License
73 along with this program. If not, see <http://www.gnu.org/licenses/>.`
77 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
78 Version string = "UNKNOWN"
80 root = flag.String("root", "./packages", "Path to packages directory")
81 bind = flag.String("bind", "[::]:8080", "Address to bind to")
82 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
83 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
84 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
85 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
86 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
87 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
88 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
89 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
90 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
91 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
92 version = flag.Bool("version", false, "Print version information")
93 warranty = flag.Bool("warranty", false, "Print warranty information")
98 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
99 path := filepath.Join(*root, dir)
100 if _, err := os.Stat(path); os.IsNotExist(err) {
101 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
102 http.Error(w, err.Error(), http.StatusInternalServerError)
105 log.Println(r.RemoteAddr, "mkdir", dir)
111 w http.ResponseWriter,
117 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
120 resp, err := http.Get(*pypiURL + dir + "/")
122 http.Error(w, err.Error(), http.StatusBadGateway)
125 body, err := ioutil.ReadAll(resp.Body)
128 http.Error(w, err.Error(), http.StatusBadGateway)
131 if !mkdirForPkg(w, r, dir) {
134 dirPath := filepath.Join(*root, dir)
135 var submatches []string
141 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
142 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
143 if len(submatches) == 0 {
147 filename = submatches[2]
148 if pkgURL, err = url.Parse(uri); err != nil {
149 http.Error(w, err.Error(), http.StatusInternalServerError)
152 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
154 http.Error(w, err.Error(), http.StatusBadGateway)
158 path = filepath.Join(dirPath, filename)
159 if filename == filenameGet {
161 // Skip heavy remote call, when shutting down
162 http.Error(w, "shutting down", http.StatusInternalServerError)
165 log.Println(r.RemoteAddr, "pypi download", filename)
166 resp, err = http.Get(pkgURL.String())
168 http.Error(w, err.Error(), http.StatusBadGateway)
171 defer resp.Body.Close()
172 hasher := sha256.New()
173 dst, err := TempFile(dirPath)
175 http.Error(w, err.Error(), http.StatusInternalServerError)
178 wr := io.MultiWriter(hasher, dst)
179 if _, err = io.Copy(wr, resp.Body); err != nil {
180 os.Remove(dst.Name())
182 http.Error(w, err.Error(), http.StatusInternalServerError)
185 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
186 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
187 os.Remove(dst.Name())
189 http.Error(w, err.Error(), http.StatusBadGateway)
192 if err = dst.Sync(); err != nil {
193 os.Remove(dst.Name())
195 http.Error(w, err.Error(), http.StatusInternalServerError)
199 if err = os.Rename(dst.Name(), path); err != nil {
200 http.Error(w, err.Error(), http.StatusInternalServerError)
204 if filename == filenameGet || gpgUpdate {
205 if _, err = os.Stat(path); err == nil {
206 if resp, err := http.Get(pkgURL.String() + GPGSigExt); err == nil {
207 sig, err := ioutil.ReadAll(resp.Body)
210 if err = WriteFileSync(dirPath, path+GPGSigExt, sig); err != nil {
211 http.Error(w, err.Error(), http.StatusInternalServerError)
214 log.Println(r.RemoteAddr, "pypi downloaded signature", filename)
219 path = path + SHA256Ext
220 _, err = os.Stat(path)
224 if !os.IsNotExist(err) {
225 http.Error(w, err.Error(), http.StatusInternalServerError)
228 log.Println(r.RemoteAddr, "pypi touch", filename)
229 if err = WriteFileSync(dirPath, path, digest); err != nil {
230 http.Error(w, err.Error(), http.StatusInternalServerError)
237 func listRoot(w http.ResponseWriter, r *http.Request) {
238 files, err := ioutil.ReadDir(*root)
240 http.Error(w, err.Error(), http.StatusInternalServerError)
243 var result bytes.Buffer
244 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
245 for _, file := range files {
246 if file.Mode().IsDir() {
247 result.WriteString(fmt.Sprintf(
249 *refreshURLPath+file.Name()+"/",
254 result.WriteString(HTMLEnd)
255 w.Write(result.Bytes())
259 w http.ResponseWriter,
265 dirPath := filepath.Join(*root, dir)
267 if !refreshDir(w, r, dir, "", gpgUpdate) {
270 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "", false) {
273 files, err := ioutil.ReadDir(dirPath)
275 http.Error(w, err.Error(), http.StatusInternalServerError)
278 var result bytes.Buffer
279 result.WriteString(fmt.Sprintf(HTMLBegin, dir))
281 var gpgSigAttr string
282 var filenameClean string
283 for _, file := range files {
284 if !strings.HasSuffix(file.Name(), SHA256Ext) {
288 // Skip expensive I/O when shutting down
289 http.Error(w, "shutting down", http.StatusInternalServerError)
292 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
294 http.Error(w, err.Error(), http.StatusInternalServerError)
297 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
298 if _, err = os.Stat(filepath.Join(dirPath, filenameClean+GPGSigExt)); os.IsNotExist(err) {
301 gpgSigAttr = GPGSigAttr
303 result.WriteString(fmt.Sprintf(
305 strings.Join([]string{
306 *refreshURLPath, dir, "/",
307 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
313 result.WriteString(HTMLEnd)
314 w.Write(result.Bytes())
317 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
318 log.Println(r.RemoteAddr, "get", filename)
319 path := filepath.Join(*root, dir, filename)
320 if _, err := os.Stat(path); os.IsNotExist(err) {
321 if !refreshDir(w, r, dir, filename, false) {
325 http.ServeFile(w, r, path)
328 func serveUpload(w http.ResponseWriter, r *http.Request) {
329 username, password, ok := r.BasicAuth()
331 log.Println(r.RemoteAddr, "unauthenticated", username)
332 http.Error(w, "unauthenticated", http.StatusUnauthorized)
335 auther, ok := passwords[username]
336 if !ok || !auther.Auth(password) {
337 log.Println(r.RemoteAddr, "unauthenticated", username)
338 http.Error(w, "unauthenticated", http.StatusUnauthorized)
342 if err = r.ParseMultipartForm(1 << 20); err != nil {
343 http.Error(w, err.Error(), http.StatusBadRequest)
346 var digestExpected []byte
347 if digestExpectedHex, exists := r.MultipartForm.Value["sha256_digest"]; exists {
348 digestExpected, err = hex.DecodeString(digestExpectedHex[0])
350 http.Error(w, "bad sha256_digest: "+err.Error(), http.StatusBadRequest)
354 gpgSigsExpected := make(map[string]struct{})
355 for _, file := range r.MultipartForm.File["content"] {
356 filename := file.Filename
357 gpgSigsExpected[filename+GPGSigExt] = struct{}{}
358 log.Println(r.RemoteAddr, "put", filename, "by", username)
359 dir := filename[:strings.LastIndex(filename, "-")]
360 dirPath := filepath.Join(*root, dir)
361 path := filepath.Join(dirPath, filename)
362 if _, err = os.Stat(path); err == nil {
363 log.Println(r.RemoteAddr, "already exists", filename)
364 http.Error(w, "Already exists", http.StatusBadRequest)
367 if !mkdirForPkg(w, r, dir) {
370 internalPath := filepath.Join(dirPath, InternalFlag)
372 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
373 if dst, err = os.Create(internalPath); err != nil {
374 http.Error(w, err.Error(), http.StatusInternalServerError)
379 src, err := file.Open()
382 http.Error(w, err.Error(), http.StatusInternalServerError)
385 dst, err = TempFile(dirPath)
387 http.Error(w, err.Error(), http.StatusInternalServerError)
390 hasher := sha256.New()
391 wr := io.MultiWriter(hasher, dst)
392 if _, err = io.Copy(wr, src); err != nil {
393 os.Remove(dst.Name())
395 http.Error(w, err.Error(), http.StatusInternalServerError)
398 if err = dst.Sync(); err != nil {
399 os.Remove(dst.Name())
401 http.Error(w, err.Error(), http.StatusInternalServerError)
405 digest := hasher.Sum(nil)
406 if digestExpected != nil {
407 if bytes.Compare(digestExpected, digest) == 0 {
408 log.Println(r.RemoteAddr, filename, "good checksum received")
410 log.Println(r.RemoteAddr, filename, "bad checksum received")
411 http.Error(w, "bad checksum", http.StatusBadRequest)
412 os.Remove(dst.Name())
416 if err = os.Rename(dst.Name(), path); err != nil {
417 http.Error(w, err.Error(), http.StatusInternalServerError)
420 if err = WriteFileSync(dirPath, path+SHA256Ext, digest); err != nil {
421 http.Error(w, err.Error(), http.StatusInternalServerError)
425 for _, file := range r.MultipartForm.File["gpg_signature"] {
426 filename := file.Filename
427 if _, exists := gpgSigsExpected[filename]; !exists {
428 http.Error(w, "unexpected GPG signature filename", http.StatusBadRequest)
431 delete(gpgSigsExpected, filename)
432 log.Println(r.RemoteAddr, "put", filename, "by", username)
433 dir := filename[:strings.LastIndex(filename, "-")]
434 dirPath := filepath.Join(*root, dir)
435 path := filepath.Join(dirPath, filename)
436 if _, err = os.Stat(path); err == nil {
437 log.Println(r.RemoteAddr, "already exists", filename)
438 http.Error(w, "Already exists", http.StatusBadRequest)
441 src, err := file.Open()
443 http.Error(w, err.Error(), http.StatusInternalServerError)
446 sig, err := ioutil.ReadAll(src)
449 http.Error(w, err.Error(), http.StatusInternalServerError)
452 if err = WriteFileSync(dirPath, path, sig); err != nil {
453 http.Error(w, err.Error(), http.StatusInternalServerError)
459 func handler(w http.ResponseWriter, r *http.Request) {
465 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
466 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
467 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
468 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
470 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
471 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
475 http.Error(w, "unknown action", http.StatusBadRequest)
478 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
480 http.Error(w, "invalid path", http.StatusBadRequest)
487 listDir(w, r, parts[0], autorefresh, gpgUpdate)
490 servePkg(w, r, parts[0], parts[1])
495 http.Error(w, "unknown action", http.StatusBadRequest)
499 func goodIntegrity() bool {
500 dirs, err := ioutil.ReadDir(*root)
504 hasher := sha256.New()
505 digest := make([]byte, sha256.Size)
509 for _, dir := range dirs {
510 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
514 for _, file := range files {
515 if !strings.HasSuffix(file.Name(), SHA256Ext) {
518 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
519 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
521 if os.IsNotExist(err) {
527 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
531 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
532 log.Println(pkgName, "GOOD")
535 log.Println(pkgName, "BAD")
546 fmt.Println(Warranty)
550 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
554 if !goodIntegrity() {
563 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
564 log.Fatalln("Both -tls-cert and -tls-key are required")
567 log.Println("root:", *root, "bind:", *bind)
569 ln, err := net.Listen("tcp", *bind)
573 ln = netutil.LimitListener(ln, *maxClients)
574 server := &http.Server{
575 ReadTimeout: time.Minute,
576 WriteTimeout: time.Minute,
578 http.HandleFunc(*norefreshURLPath, handler)
579 http.HandleFunc(*refreshURLPath, handler)
580 http.HandleFunc(*gpgUpdateURLPath, handler)
582 needsRefreshPasswd := make(chan os.Signal, 0)
583 needsShutdown := make(chan os.Signal, 0)
584 exitErr := make(chan error, 0)
585 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
586 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
588 for range needsRefreshPasswd {
589 log.Println("Refreshing passwords")
593 go func(s *http.Server) {
596 log.Println("Shutting down")
597 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
598 exitErr <- s.Shutdown(ctx)
603 err = server.Serve(ln)
605 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
607 if err != http.ErrServerClosed {
610 if err := <-exitErr; err != nil {