]> Cypherpunks.ru repositories - gocheese.git/blob - gocheese.go
3c6d1521a754d06edbce07a85fd72cb5f14f23b0
[gocheese.git] / gocheese.go
1 /*
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>
5
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.
9
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.
14
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/>.
17 */
18
19 // Python private package repository and caching proxy
20 package main
21
22 import (
23         "bytes"
24         "context"
25         "crypto/sha256"
26         "encoding/hex"
27         "flag"
28         "fmt"
29         "io"
30         "io/ioutil"
31         "log"
32         "net"
33         "net/http"
34         "net/url"
35         "os"
36         "os/signal"
37         "path/filepath"
38         "regexp"
39         "runtime"
40         "strings"
41         "syscall"
42         "time"
43
44         "golang.org/x/net/netutil"
45 )
46
47 const (
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="
52         SHA256Ext    = ".sha256"
53         InternalFlag = ".internal"
54
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.
58
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.
63
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/>.`
66 )
67
68 var (
69         pkgPyPI        = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
70         Version string = "UNKNOWN"
71
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")
85
86         killed bool
87 )
88
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)
94                         return false
95                 }
96                 log.Println(r.RemoteAddr, "mkdir", dir)
97         }
98         return true
99 }
100
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 {
103                 return true
104         }
105         resp, err := http.Get(*pypiURL + dir + "/")
106         if err != nil {
107                 http.Error(w, err.Error(), http.StatusBadGateway)
108                 return false
109         }
110         body, err := ioutil.ReadAll(resp.Body)
111         resp.Body.Close()
112         if err != nil {
113                 http.Error(w, err.Error(), http.StatusBadGateway)
114                 return false
115         }
116         if !mkdirForPkg(w, r, dir) {
117                 return false
118         }
119         var submatches []string
120         var uri string
121         var filename string
122         var path string
123         var pkgURL *url.URL
124         var digest []byte
125         for _, lineRaw := range bytes.Split(body, []byte("\n")) {
126                 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
127                 if len(submatches) == 0 {
128                         continue
129                 }
130                 uri = submatches[1]
131                 filename = submatches[2]
132                 if pkgURL, err = url.Parse(uri); err != nil {
133                         http.Error(w, err.Error(), http.StatusInternalServerError)
134                         return false
135                 }
136                 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
137                 if err != nil {
138                         http.Error(w, err.Error(), http.StatusBadGateway)
139                         return false
140                 }
141                 if filename == filenameGet {
142                         if killed {
143                                 // Skip heavy remote call, when shutting down
144                                 http.Error(w, "shutting down", http.StatusInternalServerError)
145                                 return false
146                         }
147                         log.Println(r.RemoteAddr, "pypi download", filename)
148                         path = filepath.Join(*root, dir, filename)
149                         resp, err = http.Get(uri)
150                         if err != nil {
151                                 http.Error(w, err.Error(), http.StatusBadGateway)
152                                 return false
153                         }
154                         defer resp.Body.Close()
155                         hasher := sha256.New()
156                         dst, err := TempFile(filepath.Join(*root, dir))
157                         if err != nil {
158                                 http.Error(w, err.Error(), http.StatusInternalServerError)
159                                 return false
160                         }
161                         wr := io.MultiWriter(hasher, dst)
162                         if _, err = io.Copy(wr, resp.Body); err != nil {
163                                 os.Remove(dst.Name())
164                                 dst.Close()
165                                 http.Error(w, err.Error(), http.StatusInternalServerError)
166                                 return false
167                         }
168                         if bytes.Compare(hasher.Sum(nil), digest) != 0 {
169                                 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
170                                 os.Remove(dst.Name())
171                                 dst.Close()
172                                 http.Error(w, err.Error(), http.StatusBadGateway)
173                                 return false
174                         }
175                         if err = dst.Sync(); err != nil {
176                                 os.Remove(dst.Name())
177                                 dst.Close()
178                                 http.Error(w, err.Error(), http.StatusInternalServerError)
179                                 return false
180                         }
181                         dst.Close()
182                         if err = os.Rename(dst.Name(), path); err != nil {
183                                 http.Error(w, err.Error(), http.StatusInternalServerError)
184                                 return false
185                         }
186                 }
187                 path = filepath.Join(*root, dir, filename+SHA256Ext)
188                 _, err = os.Stat(path)
189                 if err == nil {
190                         continue
191                 }
192                 if !os.IsNotExist(err) {
193                         http.Error(w, err.Error(), http.StatusInternalServerError)
194                         return false
195                 }
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)
199                         return false
200                 }
201         }
202         return true
203 }
204
205 func listRoot(w http.ResponseWriter, r *http.Request) {
206         files, err := ioutil.ReadDir(*root)
207         if err != nil {
208                 http.Error(w, err.Error(), http.StatusInternalServerError)
209                 return
210         }
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(
216                                 HTMLElement,
217                                 *refreshURLPath+file.Name()+"/",
218                                 file.Name(),
219                         ))
220                 }
221         }
222         result.WriteString(HTMLEnd)
223         w.Write(result.Bytes())
224 }
225
226 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
227         dirPath := filepath.Join(*root, dir)
228         if autorefresh {
229                 if !refreshDir(w, r, dir, "") {
230                         return
231                 }
232         } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
233                 return
234         }
235         files, err := ioutil.ReadDir(dirPath)
236         if err != nil {
237                 http.Error(w, err.Error(), http.StatusInternalServerError)
238                 return
239         }
240         var result bytes.Buffer
241         result.WriteString(fmt.Sprintf(HTMLBegin, dir, dir))
242         var data []byte
243         var filenameClean string
244         for _, file := range files {
245                 if !strings.HasSuffix(file.Name(), SHA256Ext) {
246                         continue
247                 }
248                 if killed {
249                         // Skip expensive I/O when shutting down
250                         http.Error(w, "shutting down", http.StatusInternalServerError)
251                         return
252                 }
253                 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
254                 if err != nil {
255                         http.Error(w, err.Error(), http.StatusInternalServerError)
256                         return
257                 }
258                 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
259                 result.WriteString(fmt.Sprintf(
260                         HTMLElement,
261                         strings.Join([]string{
262                                 *refreshURLPath, dir, "/",
263                                 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
264                         }, ""),
265                         filenameClean,
266                 ))
267         }
268         result.WriteString(HTMLEnd)
269         w.Write(result.Bytes())
270 }
271
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) {
277                         return
278                 }
279         }
280         http.ServeFile(w, r, path)
281 }
282
283 func serveUpload(w http.ResponseWriter, r *http.Request) {
284         username, password, ok := r.BasicAuth()
285         if !ok {
286                 log.Println(r.RemoteAddr, "unauthenticated", username)
287                 http.Error(w, "unauthenticated", http.StatusUnauthorized)
288                 return
289         }
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)
294                 return
295         }
296         var err error
297         if err = r.ParseMultipartForm(1 << 20); err != nil {
298                 http.Error(w, err.Error(), http.StatusBadRequest)
299                 return
300         }
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)
310                         return
311                 }
312                 if !mkdirForPkg(w, r, dir) {
313                         return
314                 }
315                 internalPath := filepath.Join(dirPath, InternalFlag)
316                 var dst *os.File
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)
320                                 return
321                         }
322                         dst.Close()
323                 }
324                 src, err := file.Open()
325                 defer src.Close()
326                 if err != nil {
327                         http.Error(w, err.Error(), http.StatusInternalServerError)
328                         return
329                 }
330                 dst, err = TempFile(dirPath)
331                 if err != nil {
332                         http.Error(w, err.Error(), http.StatusInternalServerError)
333                         return
334                 }
335                 hasher := sha256.New()
336                 wr := io.MultiWriter(hasher, dst)
337                 if _, err = io.Copy(wr, src); err != nil {
338                         os.Remove(dst.Name())
339                         dst.Close()
340                         http.Error(w, err.Error(), http.StatusInternalServerError)
341                         return
342                 }
343                 if err = dst.Sync(); err != nil {
344                         os.Remove(dst.Name())
345                         dst.Close()
346                         http.Error(w, err.Error(), http.StatusInternalServerError)
347                         return
348                 }
349                 dst.Close()
350                 if err = os.Rename(dst.Name(), path); err != nil {
351                         http.Error(w, err.Error(), http.StatusInternalServerError)
352                         return
353                 }
354                 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
355                         http.Error(w, err.Error(), http.StatusInternalServerError)
356                         return
357                 }
358         }
359 }
360
361 func handler(w http.ResponseWriter, r *http.Request) {
362         if r.Method == "GET" {
363                 var path string
364                 var autorefresh bool
365                 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
366                         path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
367                         autorefresh = false
368                 } else {
369                         path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
370                         autorefresh = true
371                 }
372                 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
373                 if len(parts) > 2 {
374                         http.Error(w, "invalid path", http.StatusBadRequest)
375                         return
376                 }
377                 if len(parts) == 1 {
378                         if parts[0] == "" {
379                                 listRoot(w, r)
380                         } else {
381                                 listDir(w, r, parts[0], autorefresh)
382                         }
383                 } else {
384                         servePkg(w, r, parts[0], parts[1])
385                 }
386         } else if r.Method == "POST" {
387                 serveUpload(w, r)
388         }
389 }
390
391 func goodIntegrity() bool {
392         dirs, err := ioutil.ReadDir(*root)
393         if err != nil {
394                 log.Fatal(err)
395         }
396         hasher := sha256.New()
397         digest := make([]byte, sha256.Size)
398         isGood := true
399         var data []byte
400         var pkgName string
401         for _, dir := range dirs {
402                 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
403                 if err != nil {
404                         log.Fatal(err)
405                 }
406                 for _, file := range files {
407                         if !strings.HasSuffix(file.Name(), SHA256Ext) {
408                                 continue
409                         }
410                         pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
411                         data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
412                         if err != nil {
413                                 if os.IsNotExist(err) {
414                                         continue
415                                 }
416                                 log.Fatal(err)
417                         }
418                         hasher.Write(data)
419                         data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
420                         if err != nil {
421                                 log.Fatal(err)
422                         }
423                         if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
424                                 log.Println(pkgName, "GOOD")
425                         } else {
426                                 isGood = false
427                                 log.Println(pkgName, "BAD")
428                         }
429                         hasher.Reset()
430                 }
431         }
432         return isGood
433 }
434
435 func main() {
436         flag.Parse()
437         if *warranty {
438                 fmt.Println(Warranty)
439                 return
440         }
441         if *version {
442                 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
443                 return
444         }
445         if *fsck {
446                 if !goodIntegrity() {
447                         os.Exit(1)
448                 }
449                 return
450         }
451         if *passwdCheck {
452                 refreshPasswd()
453                 return
454         }
455         if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
456                 log.Fatalln("Both -tls-cert and -tls-key are required")
457         }
458         refreshPasswd()
459         log.Println("root:", *root, "bind:", *bind)
460
461         ln, err := net.Listen("tcp", *bind)
462         if err != nil {
463                 log.Fatal(err)
464         }
465         ln = netutil.LimitListener(ln, *maxClients)
466         server := &http.Server{
467                 ReadTimeout:  time.Minute,
468                 WriteTimeout: time.Minute,
469         }
470         http.HandleFunc(*norefreshURLPath, handler)
471         http.HandleFunc(*refreshURLPath, handler)
472
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)
478         go func() {
479                 for range needsRefreshPasswd {
480                         log.Println("Refreshing passwords")
481                         refreshPasswd()
482                 }
483         }()
484         go func(s *http.Server) {
485                 <-needsShutdown
486                 killed = true
487                 log.Println("Shutting down")
488                 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
489                 exitErr <- s.Shutdown(ctx)
490                 cancel()
491         }(server)
492
493         if *tlsCert == "" {
494                 err = server.Serve(ln)
495         } else {
496                 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
497         }
498         if err != http.ErrServerClosed {
499                 log.Fatal(err)
500         }
501         if err := <-exitErr; err != nil {
502                 log.Fatal(err)
503         }
504 }