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 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
72 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
73 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
74 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
75 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
76 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
77 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
78 version = flag.Bool("version", false, "Print version information")
79 warranty = flag.Bool("warranty", false, "Print warranty information")
81 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
82 Version string = "UNKNOWN"
84 passwords map[string]Auther = make(map[string]Auther)
87 type Auther interface {
88 Auth(password string) bool
91 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
92 path := filepath.Join(*root, dir)
93 if _, err := os.Stat(path); os.IsNotExist(err) {
94 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
95 http.Error(w, err.Error(), http.StatusInternalServerError)
98 log.Println(r.RemoteAddr, "mkdir", dir)
103 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
104 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
105 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
108 log.Println(r.RemoteAddr, "pypi refresh", dir)
109 resp, err := http.Get(*pypiURL + dir + "/")
111 http.Error(w, err.Error(), http.StatusBadGateway)
114 defer resp.Body.Close()
115 body, err := ioutil.ReadAll(resp.Body)
117 http.Error(w, err.Error(), http.StatusBadGateway)
120 if !mkdirForPkg(w, r, dir) {
123 var submatches []string
129 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
130 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
131 if len(submatches) == 0 {
135 filename = submatches[2]
136 if pkgURL, err = url.Parse(uri); err != nil {
137 http.Error(w, err.Error(), http.StatusInternalServerError)
140 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
142 http.Error(w, err.Error(), http.StatusBadGateway)
145 if filename == filenameGet {
146 log.Println(r.RemoteAddr, "pypi download", filename)
147 path = filepath.Join(*root, dir, filename)
148 resp, err = http.Get(uri)
150 http.Error(w, err.Error(), http.StatusBadGateway)
153 defer resp.Body.Close()
154 hasher := sha256.New()
155 dst, err := ioutil.TempFile(filepath.Join(*root, dir), "")
157 http.Error(w, err.Error(), http.StatusInternalServerError)
160 wr := io.MultiWriter(hasher, dst)
161 if _, err = io.Copy(wr, resp.Body); err != nil {
162 os.Remove(dst.Name())
164 http.Error(w, err.Error(), http.StatusInternalServerError)
167 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
168 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
169 os.Remove(dst.Name())
171 http.Error(w, err.Error(), http.StatusBadGateway)
174 if err = dst.Sync(); err != nil {
175 os.Remove(dst.Name())
177 http.Error(w, err.Error(), http.StatusInternalServerError)
181 if err = os.Rename(dst.Name(), path); err != nil {
182 http.Error(w, err.Error(), http.StatusInternalServerError)
186 path = filepath.Join(*root, dir, filename+SHA256Ext)
187 _, err = os.Stat(path)
191 if !os.IsNotExist(err) {
192 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 log.Println(r.RemoteAddr, "root")
207 files, err := ioutil.ReadDir(*root)
209 http.Error(w, err.Error(), http.StatusInternalServerError)
212 w.Write([]byte(fmt.Sprintf(HTMLBegin, "root", "root")))
213 for _, file := range files {
214 if file.Mode().IsDir() {
215 w.Write([]byte(fmt.Sprintf(
217 *refreshURLPath+file.Name()+"/",
222 w.Write([]byte(HTMLEnd))
225 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
226 log.Println(r.RemoteAddr, "dir", dir)
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 w.Write([]byte(fmt.Sprintf(HTMLBegin, dir, dir)))
242 var filenameClean string
243 for _, file := range files {
244 if !strings.HasSuffix(file.Name(), SHA256Ext) {
247 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
249 http.Error(w, err.Error(), http.StatusInternalServerError)
252 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
253 w.Write([]byte(fmt.Sprintf(
255 strings.Join([]string{
256 *refreshURLPath, dir, "/",
257 filenameClean, "#", SHA256Prefix, string(data),
262 w.Write([]byte(HTMLEnd))
265 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
266 log.Println(r.RemoteAddr, "pkg", filename)
267 path := filepath.Join(*root, dir, filename)
268 if _, err := os.Stat(path); os.IsNotExist(err) {
269 if !refreshDir(w, r, dir, filename) {
273 http.ServeFile(w, r, path)
276 func serveUpload(w http.ResponseWriter, r *http.Request) {
277 username, password, ok := r.BasicAuth()
279 log.Println(r.RemoteAddr, "unauthenticated", username)
280 http.Error(w, "unauthenticated", http.StatusUnauthorized)
283 auther, ok := passwords[username]
284 if !ok || !auther.Auth(password) {
285 log.Println(r.RemoteAddr, "unauthenticated", username)
286 http.Error(w, "unauthenticated", http.StatusUnauthorized)
290 if err = r.ParseMultipartForm(1 << 20); err != nil {
291 http.Error(w, err.Error(), http.StatusBadRequest)
294 for _, file := range r.MultipartForm.File["content"] {
295 filename := file.Filename
296 log.Println(r.RemoteAddr, "upload", filename, "by", username)
297 dir := filename[:strings.LastIndex(filename, "-")]
298 dirPath := filepath.Join(*root, dir)
299 path := filepath.Join(dirPath, filename)
300 if _, err = os.Stat(path); err == nil {
301 log.Println(r.RemoteAddr, "already exists", filename)
302 http.Error(w, "Already exists", http.StatusBadRequest)
305 if !mkdirForPkg(w, r, dir) {
308 internalPath := filepath.Join(dirPath, InternalFlag)
310 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
311 if dst, err = os.Create(internalPath); err != nil {
312 http.Error(w, err.Error(), http.StatusInternalServerError)
317 src, err := file.Open()
320 http.Error(w, err.Error(), http.StatusInternalServerError)
323 dst, err = ioutil.TempFile(dirPath, "")
325 http.Error(w, err.Error(), http.StatusInternalServerError)
328 hasher := sha256.New()
329 wr := io.MultiWriter(hasher, dst)
330 if _, err = io.Copy(wr, src); err != nil {
331 os.Remove(dst.Name())
333 http.Error(w, err.Error(), http.StatusInternalServerError)
336 if err = dst.Sync(); err != nil {
337 os.Remove(dst.Name())
339 http.Error(w, err.Error(), http.StatusInternalServerError)
343 if err = os.Rename(dst.Name(), path); err != nil {
344 http.Error(w, err.Error(), http.StatusInternalServerError)
347 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
348 http.Error(w, err.Error(), http.StatusInternalServerError)
354 func handler(w http.ResponseWriter, r *http.Request) {
355 if r.Method == "GET" {
358 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
359 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
362 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
365 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
367 http.Error(w, "invalid path", http.StatusBadRequest)
374 listDir(w, r, parts[0], autorefresh)
377 servePkg(w, r, parts[0], parts[1])
379 } else if r.Method == "POST" {
384 func goodIntegrity() bool {
385 dirs, err := ioutil.ReadDir(*root)
389 hasher := sha256.New()
390 digest := make([]byte, sha256.Size)
394 for _, dir := range dirs {
395 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
399 for _, file := range files {
400 if !strings.HasSuffix(file.Name(), SHA256Ext) {
403 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
404 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
406 if os.IsNotExist(err) {
412 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
416 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
417 log.Println(pkgName, "GOOD")
420 log.Println(pkgName, "BAD")
431 fmt.Println(Warranty)
435 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
439 if !goodIntegrity() {
449 log.Println("root:", *root, "bind:", *bind)
450 needsRefreshPasswd := make(chan os.Signal, 0)
451 needsShutdown := make(chan os.Signal, 0)
452 killed := make(chan error, 0)
453 http.HandleFunc(*norefreshURLPath, handler)
454 http.HandleFunc(*refreshURLPath, handler)
455 ln, err := net.Listen("tcp", *bind)
460 ReadTimeout: time.Minute,
461 WriteTimeout: time.Minute,
463 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
464 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
466 for range needsRefreshPasswd {
467 log.Println("Refreshing passwords")
471 go func(s *http.Server) {
473 log.Println("Shutting down")
474 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
475 killed <- s.Shutdown(ctx)
478 if err := s.Serve(netutil.LimitListener(ln, *maxClients)); err != http.ErrServerClosed {
481 if err := <-killed; err != nil {