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")
97 normalizationRe *regexp.Regexp = regexp.MustCompilePOSIX("[-_.]+")
100 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
101 path := filepath.Join(*root, dir)
102 if _, err := os.Stat(path); os.IsNotExist(err) {
103 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
104 http.Error(w, err.Error(), http.StatusInternalServerError)
107 log.Println(r.RemoteAddr, "mkdir", dir)
113 w http.ResponseWriter,
119 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
122 resp, err := http.Get(*pypiURL + dir + "/")
124 http.Error(w, err.Error(), http.StatusBadGateway)
127 body, err := ioutil.ReadAll(resp.Body)
130 http.Error(w, err.Error(), http.StatusBadGateway)
133 if !mkdirForPkg(w, r, dir) {
136 dirPath := filepath.Join(*root, dir)
137 var submatches []string
143 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
144 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
145 if len(submatches) == 0 {
149 filename = submatches[2]
150 if pkgURL, err = url.Parse(uri); err != nil {
151 http.Error(w, err.Error(), http.StatusInternalServerError)
154 if !strings.HasPrefix(pkgURL.Fragment, SHA256Prefix) {
155 log.Println(r.RemoteAddr, "pypi", filename, "no SHA256 digest provided")
156 http.Error(w, "no SHA256 digest provided", http.StatusBadGateway)
159 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
161 http.Error(w, err.Error(), http.StatusBadGateway)
165 uri = pkgURL.String()
166 if pkgURL.Host == "" {
167 uri = *pypiURL + strings.TrimPrefix(uri, "/")
169 path = filepath.Join(dirPath, filename)
170 if filename == filenameGet {
172 // Skip heavy remote call, when shutting down
173 http.Error(w, "shutting down", http.StatusInternalServerError)
176 log.Println(r.RemoteAddr, "pypi download", filename)
177 resp, err = http.Get(uri)
179 http.Error(w, err.Error(), http.StatusBadGateway)
182 defer resp.Body.Close()
183 hasher := sha256.New()
184 dst, err := TempFile(dirPath)
186 http.Error(w, err.Error(), http.StatusInternalServerError)
189 wr := io.MultiWriter(hasher, dst)
190 if _, err = io.Copy(wr, resp.Body); err != nil {
191 os.Remove(dst.Name())
193 http.Error(w, err.Error(), http.StatusInternalServerError)
196 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
197 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
198 os.Remove(dst.Name())
200 http.Error(w, err.Error(), http.StatusBadGateway)
203 if err = dst.Sync(); err != nil {
204 os.Remove(dst.Name())
206 http.Error(w, err.Error(), http.StatusInternalServerError)
210 if err = os.Rename(dst.Name(), path); err != nil {
211 http.Error(w, err.Error(), http.StatusInternalServerError)
214 if err = DirSync(dirPath); err != nil {
215 http.Error(w, err.Error(), http.StatusInternalServerError)
219 if filename == filenameGet || gpgUpdate {
220 if _, err = os.Stat(path); err != nil {
223 resp, err := http.Get(uri + GPGSigExt)
227 if resp.StatusCode != http.StatusOK {
231 sig, err := ioutil.ReadAll(resp.Body)
236 if err = WriteFileSync(dirPath, path+GPGSigExt, sig); err != nil {
237 http.Error(w, err.Error(), http.StatusInternalServerError)
240 log.Println(r.RemoteAddr, "pypi downloaded signature", filename)
243 path = path + SHA256Ext
244 _, err = os.Stat(path)
248 if !os.IsNotExist(err) {
249 http.Error(w, err.Error(), http.StatusInternalServerError)
252 log.Println(r.RemoteAddr, "pypi touch", filename)
253 if err = WriteFileSync(dirPath, path, digest); err != nil {
254 http.Error(w, err.Error(), http.StatusInternalServerError)
261 func listRoot(w http.ResponseWriter, r *http.Request) {
262 files, err := ioutil.ReadDir(*root)
264 http.Error(w, err.Error(), http.StatusInternalServerError)
267 var result bytes.Buffer
268 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
269 for _, file := range files {
270 if file.Mode().IsDir() {
271 result.WriteString(fmt.Sprintf(
273 *refreshURLPath+file.Name()+"/",
278 result.WriteString(HTMLEnd)
279 w.Write(result.Bytes())
283 w http.ResponseWriter,
289 dirPath := filepath.Join(*root, dir)
291 if !refreshDir(w, r, dir, "", gpgUpdate) {
294 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "", false) {
297 files, err := ioutil.ReadDir(dirPath)
299 http.Error(w, err.Error(), http.StatusInternalServerError)
302 var result bytes.Buffer
303 result.WriteString(fmt.Sprintf(HTMLBegin, dir))
305 var gpgSigAttr string
306 var filenameClean string
307 for _, file := range files {
308 if !strings.HasSuffix(file.Name(), SHA256Ext) {
312 // Skip expensive I/O when shutting down
313 http.Error(w, "shutting down", http.StatusInternalServerError)
316 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
318 http.Error(w, err.Error(), http.StatusInternalServerError)
321 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
322 if _, err = os.Stat(filepath.Join(dirPath, filenameClean+GPGSigExt)); os.IsNotExist(err) {
325 gpgSigAttr = GPGSigAttr
327 result.WriteString(fmt.Sprintf(
329 strings.Join([]string{
330 *refreshURLPath, dir, "/",
331 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
337 result.WriteString(HTMLEnd)
338 w.Write(result.Bytes())
341 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
342 log.Println(r.RemoteAddr, "get", filename)
343 path := filepath.Join(*root, dir, filename)
344 if _, err := os.Stat(path); os.IsNotExist(err) {
345 if !refreshDir(w, r, dir, filename, false) {
349 http.ServeFile(w, r, path)
352 func serveUpload(w http.ResponseWriter, r *http.Request) {
354 username, password, ok := r.BasicAuth()
356 log.Println(r.RemoteAddr, "unauthenticated", username)
357 http.Error(w, "unauthenticated", http.StatusUnauthorized)
360 auther, ok := passwords[username]
361 if !ok || !auther.Auth(password) {
362 log.Println(r.RemoteAddr, "unauthenticated", username)
363 http.Error(w, "unauthenticated", http.StatusUnauthorized)
369 if err = r.ParseMultipartForm(1 << 20); err != nil {
370 http.Error(w, err.Error(), http.StatusBadRequest)
373 pkgNames, exists := r.MultipartForm.Value["name"]
374 if !exists || len(pkgNames) != 1 {
375 http.Error(w, "single name is expected in request", http.StatusBadRequest)
378 dir := normalizationRe.ReplaceAllString(pkgNames[0], "-")
379 dirPath := filepath.Join(*root, dir)
380 var digestExpected []byte
381 if digestExpectedHex, exists := r.MultipartForm.Value["sha256_digest"]; exists {
382 digestExpected, err = hex.DecodeString(digestExpectedHex[0])
384 http.Error(w, "bad sha256_digest: "+err.Error(), http.StatusBadRequest)
388 gpgSigsExpected := make(map[string]struct{})
390 // Checking is it internal package
391 if _, err = os.Stat(filepath.Join(dirPath, InternalFlag)); err != nil {
392 log.Println(r.RemoteAddr, "non-internal package", dir)
393 http.Error(w, "unknown internal package", http.StatusUnauthorized)
397 for _, file := range r.MultipartForm.File["content"] {
398 filename := file.Filename
399 gpgSigsExpected[filename+GPGSigExt] = struct{}{}
400 log.Println(r.RemoteAddr, "put", filename, "by", username)
401 path := filepath.Join(dirPath, filename)
402 if _, err = os.Stat(path); err == nil {
403 log.Println(r.RemoteAddr, "already exists", filename)
404 http.Error(w, "already exists", http.StatusBadRequest)
407 if !mkdirForPkg(w, r, dir) {
410 src, err := file.Open()
413 http.Error(w, err.Error(), http.StatusInternalServerError)
416 dst, err := TempFile(dirPath)
418 http.Error(w, err.Error(), http.StatusInternalServerError)
421 hasher := sha256.New()
422 wr := io.MultiWriter(hasher, dst)
423 if _, err = io.Copy(wr, src); err != nil {
424 os.Remove(dst.Name())
426 http.Error(w, err.Error(), http.StatusInternalServerError)
429 if err = dst.Sync(); err != nil {
430 os.Remove(dst.Name())
432 http.Error(w, err.Error(), http.StatusInternalServerError)
436 digest := hasher.Sum(nil)
437 if digestExpected != nil {
438 if bytes.Compare(digestExpected, digest) == 0 {
439 log.Println(r.RemoteAddr, filename, "good checksum received")
441 log.Println(r.RemoteAddr, filename, "bad checksum received")
442 http.Error(w, "bad checksum", http.StatusBadRequest)
443 os.Remove(dst.Name())
447 if err = os.Rename(dst.Name(), path); err != nil {
448 http.Error(w, err.Error(), http.StatusInternalServerError)
451 if err = DirSync(dirPath); err != nil {
452 http.Error(w, err.Error(), http.StatusInternalServerError)
455 if err = WriteFileSync(dirPath, path+SHA256Ext, digest); err != nil {
456 http.Error(w, err.Error(), http.StatusInternalServerError)
460 for _, file := range r.MultipartForm.File["gpg_signature"] {
461 filename := file.Filename
462 if _, exists := gpgSigsExpected[filename]; !exists {
463 http.Error(w, "unexpected GPG signature filename", http.StatusBadRequest)
466 delete(gpgSigsExpected, filename)
467 log.Println(r.RemoteAddr, "put", filename, "by", username)
468 path := filepath.Join(dirPath, filename)
469 if _, err = os.Stat(path); err == nil {
470 log.Println(r.RemoteAddr, "already exists", filename)
471 http.Error(w, "already exists", http.StatusBadRequest)
474 src, err := file.Open()
476 http.Error(w, err.Error(), http.StatusInternalServerError)
479 sig, err := ioutil.ReadAll(src)
482 http.Error(w, err.Error(), http.StatusInternalServerError)
485 if err = WriteFileSync(dirPath, path, sig); err != nil {
486 http.Error(w, err.Error(), http.StatusInternalServerError)
492 func handler(w http.ResponseWriter, r *http.Request) {
498 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
499 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
500 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
501 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
503 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
504 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
508 http.Error(w, "unknown action", http.StatusBadRequest)
511 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
513 http.Error(w, "invalid path", http.StatusBadRequest)
520 listDir(w, r, parts[0], autorefresh, gpgUpdate)
523 servePkg(w, r, parts[0], parts[1])
528 http.Error(w, "unknown action", http.StatusBadRequest)
532 func goodIntegrity() bool {
533 dirs, err := ioutil.ReadDir(*root)
537 hasher := sha256.New()
538 digest := make([]byte, sha256.Size)
542 for _, dir := range dirs {
543 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
547 for _, file := range files {
548 if !strings.HasSuffix(file.Name(), SHA256Ext) {
551 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
552 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
554 if os.IsNotExist(err) {
560 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
564 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
565 fmt.Println(pkgName, "GOOD")
568 fmt.Println(pkgName, "BAD")
579 fmt.Println(Warranty)
583 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
587 if !goodIntegrity() {
596 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
597 log.Fatalln("Both -tls-cert and -tls-key are required")
600 log.Println("root:", *root, "bind:", *bind)
602 ln, err := net.Listen("tcp", *bind)
606 ln = netutil.LimitListener(ln, *maxClients)
607 server := &http.Server{
608 ReadTimeout: time.Minute,
609 WriteTimeout: time.Minute,
611 http.HandleFunc(*norefreshURLPath, handler)
612 http.HandleFunc(*refreshURLPath, handler)
613 http.HandleFunc(*gpgUpdateURLPath, handler)
615 needsRefreshPasswd := make(chan os.Signal, 0)
616 needsShutdown := make(chan os.Signal, 0)
617 exitErr := make(chan error, 0)
618 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
619 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
621 for range needsRefreshPasswd {
622 log.Println("Refreshing passwords")
626 go func(s *http.Server) {
629 log.Println("Shutting down")
630 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
631 exitErr <- s.Shutdown(ctx)
636 err = server.Serve(ln)
638 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
640 if err != http.ErrServerClosed {
643 if err := <-exitErr; err != nil {