]> Cypherpunks.ru repositories - gocheese.git/blob - gocheese.go
Wheel friendliness
[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>
49 <html>
50   <head>
51     <title>Links for %s</title>
52   </head>
53   <body>
54 `
55         HTMLEnd      = "  </body>\n</html>\n"
56         HTMLElement  = "    <a href=\"%s\"%s>%s</a><br/>\n"
57         SHA256Prefix = "sha256="
58         SHA256Ext    = ".sha256"
59         InternalFlag = ".internal"
60         GPGSigExt    = ".asc"
61         GPGSigAttr   = " data-gpg-sig=true"
62
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.
66
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.
71
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/>.`
74 )
75
76 var (
77         pkgPyPI        = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
78         Version string = "UNKNOWN"
79
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")
94
95         killed bool
96
97         normalizationRe *regexp.Regexp = regexp.MustCompilePOSIX("[-_.]+")
98 )
99
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)
105                         return false
106                 }
107                 log.Println(r.RemoteAddr, "mkdir", dir)
108         }
109         return true
110 }
111
112 func refreshDir(
113         w http.ResponseWriter,
114         r *http.Request,
115         dir,
116         filenameGet string,
117         gpgUpdate bool,
118 ) bool {
119         if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
120                 return true
121         }
122         resp, err := http.Get(*pypiURL + dir + "/")
123         if err != nil {
124                 http.Error(w, err.Error(), http.StatusBadGateway)
125                 return false
126         }
127         body, err := ioutil.ReadAll(resp.Body)
128         resp.Body.Close()
129         if err != nil {
130                 http.Error(w, err.Error(), http.StatusBadGateway)
131                 return false
132         }
133         if !mkdirForPkg(w, r, dir) {
134                 return false
135         }
136         dirPath := filepath.Join(*root, dir)
137         var submatches []string
138         var uri string
139         var filename string
140         var path string
141         var pkgURL *url.URL
142         var digest []byte
143         for _, lineRaw := range bytes.Split(body, []byte("\n")) {
144                 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
145                 if len(submatches) == 0 {
146                         continue
147                 }
148                 uri = submatches[1]
149                 filename = submatches[2]
150                 if pkgURL, err = url.Parse(uri); err != nil {
151                         http.Error(w, err.Error(), http.StatusInternalServerError)
152                         return false
153                 }
154                 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
155                 if err != nil {
156                         http.Error(w, err.Error(), http.StatusBadGateway)
157                         return false
158                 }
159                 pkgURL.Fragment = ""
160                 path = filepath.Join(dirPath, filename)
161                 if filename == filenameGet {
162                         if killed {
163                                 // Skip heavy remote call, when shutting down
164                                 http.Error(w, "shutting down", http.StatusInternalServerError)
165                                 return false
166                         }
167                         log.Println(r.RemoteAddr, "pypi download", filename)
168                         resp, err = http.Get(pkgURL.String())
169                         if err != nil {
170                                 http.Error(w, err.Error(), http.StatusBadGateway)
171                                 return false
172                         }
173                         defer resp.Body.Close()
174                         hasher := sha256.New()
175                         dst, err := TempFile(dirPath)
176                         if err != nil {
177                                 http.Error(w, err.Error(), http.StatusInternalServerError)
178                                 return false
179                         }
180                         wr := io.MultiWriter(hasher, dst)
181                         if _, err = io.Copy(wr, resp.Body); err != nil {
182                                 os.Remove(dst.Name())
183                                 dst.Close()
184                                 http.Error(w, err.Error(), http.StatusInternalServerError)
185                                 return false
186                         }
187                         if bytes.Compare(hasher.Sum(nil), digest) != 0 {
188                                 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
189                                 os.Remove(dst.Name())
190                                 dst.Close()
191                                 http.Error(w, err.Error(), http.StatusBadGateway)
192                                 return false
193                         }
194                         if err = dst.Sync(); err != nil {
195                                 os.Remove(dst.Name())
196                                 dst.Close()
197                                 http.Error(w, err.Error(), http.StatusInternalServerError)
198                                 return false
199                         }
200                         dst.Close()
201                         if err = os.Rename(dst.Name(), path); err != nil {
202                                 http.Error(w, err.Error(), http.StatusInternalServerError)
203                                 return false
204                         }
205                 }
206                 if filename == filenameGet || gpgUpdate {
207                         if _, err = os.Stat(path); err == nil {
208                                 if resp, err := http.Get(pkgURL.String() + GPGSigExt); err == nil {
209                                         sig, err := ioutil.ReadAll(resp.Body)
210                                         resp.Body.Close()
211                                         if err == nil {
212                                                 if err = WriteFileSync(dirPath, path+GPGSigExt, sig); err != nil {
213                                                         http.Error(w, err.Error(), http.StatusInternalServerError)
214                                                         return false
215                                                 }
216                                                 log.Println(r.RemoteAddr, "pypi downloaded signature", filename)
217                                         }
218                                 }
219                         }
220                 }
221                 path = path + SHA256Ext
222                 _, err = os.Stat(path)
223                 if err == nil {
224                         continue
225                 }
226                 if !os.IsNotExist(err) {
227                         http.Error(w, err.Error(), http.StatusInternalServerError)
228                         return false
229                 }
230                 log.Println(r.RemoteAddr, "pypi touch", filename)
231                 if err = WriteFileSync(dirPath, path, digest); err != nil {
232                         http.Error(w, err.Error(), http.StatusInternalServerError)
233                         return false
234                 }
235         }
236         return true
237 }
238
239 func listRoot(w http.ResponseWriter, r *http.Request) {
240         files, err := ioutil.ReadDir(*root)
241         if err != nil {
242                 http.Error(w, err.Error(), http.StatusInternalServerError)
243                 return
244         }
245         var result bytes.Buffer
246         result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
247         for _, file := range files {
248                 if file.Mode().IsDir() {
249                         result.WriteString(fmt.Sprintf(
250                                 HTMLElement,
251                                 *refreshURLPath+file.Name()+"/",
252                                 file.Name(),
253                         ))
254                 }
255         }
256         result.WriteString(HTMLEnd)
257         w.Write(result.Bytes())
258 }
259
260 func listDir(
261         w http.ResponseWriter,
262         r *http.Request,
263         dir string,
264         autorefresh,
265         gpgUpdate bool,
266 ) {
267         dirPath := filepath.Join(*root, dir)
268         if autorefresh {
269                 if !refreshDir(w, r, dir, "", gpgUpdate) {
270                         return
271                 }
272         } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "", false) {
273                 return
274         }
275         files, err := ioutil.ReadDir(dirPath)
276         if err != nil {
277                 http.Error(w, err.Error(), http.StatusInternalServerError)
278                 return
279         }
280         var result bytes.Buffer
281         result.WriteString(fmt.Sprintf(HTMLBegin, dir))
282         var data []byte
283         var gpgSigAttr string
284         var filenameClean string
285         for _, file := range files {
286                 if !strings.HasSuffix(file.Name(), SHA256Ext) {
287                         continue
288                 }
289                 if killed {
290                         // Skip expensive I/O when shutting down
291                         http.Error(w, "shutting down", http.StatusInternalServerError)
292                         return
293                 }
294                 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
295                 if err != nil {
296                         http.Error(w, err.Error(), http.StatusInternalServerError)
297                         return
298                 }
299                 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
300                 if _, err = os.Stat(filepath.Join(dirPath, filenameClean+GPGSigExt)); os.IsNotExist(err) {
301                         gpgSigAttr = ""
302                 } else {
303                         gpgSigAttr = GPGSigAttr
304                 }
305                 result.WriteString(fmt.Sprintf(
306                         HTMLElement,
307                         strings.Join([]string{
308                                 *refreshURLPath, dir, "/",
309                                 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
310                         }, ""),
311                         gpgSigAttr,
312                         filenameClean,
313                 ))
314         }
315         result.WriteString(HTMLEnd)
316         w.Write(result.Bytes())
317 }
318
319 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
320         log.Println(r.RemoteAddr, "get", filename)
321         path := filepath.Join(*root, dir, filename)
322         if _, err := os.Stat(path); os.IsNotExist(err) {
323                 if !refreshDir(w, r, dir, filename, false) {
324                         return
325                 }
326         }
327         http.ServeFile(w, r, path)
328 }
329
330 func serveUpload(w http.ResponseWriter, r *http.Request) {
331         username, password, ok := r.BasicAuth()
332         if !ok {
333                 log.Println(r.RemoteAddr, "unauthenticated", username)
334                 http.Error(w, "unauthenticated", http.StatusUnauthorized)
335                 return
336         }
337         auther, ok := passwords[username]
338         if !ok || !auther.Auth(password) {
339                 log.Println(r.RemoteAddr, "unauthenticated", username)
340                 http.Error(w, "unauthenticated", http.StatusUnauthorized)
341                 return
342         }
343         var err error
344         if err = r.ParseMultipartForm(1 << 20); err != nil {
345                 http.Error(w, err.Error(), http.StatusBadRequest)
346                 return
347         }
348         pkgNames, exists := r.MultipartForm.Value["name"]
349         if !exists || len(pkgNames) != 1 {
350                 http.Error(w, "name is expected in request", http.StatusBadRequest)
351                 return
352         }
353         dir := normalizationRe.ReplaceAllString(pkgNames[0], "-")
354         dirPath := filepath.Join(*root, dir)
355         var digestExpected []byte
356         if digestExpectedHex, exists := r.MultipartForm.Value["sha256_digest"]; exists {
357                 digestExpected, err = hex.DecodeString(digestExpectedHex[0])
358                 if err != nil {
359                         http.Error(w, "bad sha256_digest: "+err.Error(), http.StatusBadRequest)
360                         return
361                 }
362         }
363         gpgSigsExpected := make(map[string]struct{})
364         for _, file := range r.MultipartForm.File["content"] {
365                 filename := file.Filename
366                 gpgSigsExpected[filename+GPGSigExt] = struct{}{}
367                 log.Println(r.RemoteAddr, "put", filename, "by", username)
368                 path := filepath.Join(dirPath, filename)
369                 if _, err = os.Stat(path); err == nil {
370                         log.Println(r.RemoteAddr, "already exists", filename)
371                         http.Error(w, "Already exists", http.StatusBadRequest)
372                         return
373                 }
374                 if !mkdirForPkg(w, r, dir) {
375                         return
376                 }
377                 internalPath := filepath.Join(dirPath, InternalFlag)
378                 var dst *os.File
379                 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
380                         if dst, err = os.Create(internalPath); err != nil {
381                                 http.Error(w, err.Error(), http.StatusInternalServerError)
382                                 return
383                         }
384                         dst.Close()
385                 }
386                 src, err := file.Open()
387                 defer src.Close()
388                 if err != nil {
389                         http.Error(w, err.Error(), http.StatusInternalServerError)
390                         return
391                 }
392                 dst, err = TempFile(dirPath)
393                 if err != nil {
394                         http.Error(w, err.Error(), http.StatusInternalServerError)
395                         return
396                 }
397                 hasher := sha256.New()
398                 wr := io.MultiWriter(hasher, dst)
399                 if _, err = io.Copy(wr, src); err != nil {
400                         os.Remove(dst.Name())
401                         dst.Close()
402                         http.Error(w, err.Error(), http.StatusInternalServerError)
403                         return
404                 }
405                 if err = dst.Sync(); err != nil {
406                         os.Remove(dst.Name())
407                         dst.Close()
408                         http.Error(w, err.Error(), http.StatusInternalServerError)
409                         return
410                 }
411                 dst.Close()
412                 digest := hasher.Sum(nil)
413                 if digestExpected != nil {
414                         if bytes.Compare(digestExpected, digest) == 0 {
415                                 log.Println(r.RemoteAddr, filename, "good checksum received")
416                         } else {
417                                 log.Println(r.RemoteAddr, filename, "bad checksum received")
418                                 http.Error(w, "bad checksum", http.StatusBadRequest)
419                                 os.Remove(dst.Name())
420                                 return
421                         }
422                 }
423                 if err = os.Rename(dst.Name(), path); err != nil {
424                         http.Error(w, err.Error(), http.StatusInternalServerError)
425                         return
426                 }
427                 if err = WriteFileSync(dirPath, path+SHA256Ext, digest); err != nil {
428                         http.Error(w, err.Error(), http.StatusInternalServerError)
429                         return
430                 }
431         }
432         for _, file := range r.MultipartForm.File["gpg_signature"] {
433                 filename := file.Filename
434                 if _, exists := gpgSigsExpected[filename]; !exists {
435                         http.Error(w, "unexpected GPG signature filename", http.StatusBadRequest)
436                         return
437                 }
438                 delete(gpgSigsExpected, filename)
439                 log.Println(r.RemoteAddr, "put", filename, "by", username)
440                 path := filepath.Join(dirPath, filename)
441                 if _, err = os.Stat(path); err == nil {
442                         log.Println(r.RemoteAddr, "already exists", filename)
443                         http.Error(w, "Already exists", http.StatusBadRequest)
444                         return
445                 }
446                 src, err := file.Open()
447                 if err != nil {
448                         http.Error(w, err.Error(), http.StatusInternalServerError)
449                         return
450                 }
451                 sig, err := ioutil.ReadAll(src)
452                 src.Close()
453                 if err != nil {
454                         http.Error(w, err.Error(), http.StatusInternalServerError)
455                         return
456                 }
457                 if err = WriteFileSync(dirPath, path, sig); err != nil {
458                         http.Error(w, err.Error(), http.StatusInternalServerError)
459                         return
460                 }
461         }
462 }
463
464 func handler(w http.ResponseWriter, r *http.Request) {
465         switch r.Method {
466         case "GET":
467                 var path string
468                 var autorefresh bool
469                 var gpgUpdate bool
470                 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
471                         path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
472                 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
473                         path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
474                         autorefresh = true
475                 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
476                         path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
477                         autorefresh = true
478                         gpgUpdate = true
479                 } else {
480                         http.Error(w, "unknown action", http.StatusBadRequest)
481                         return
482                 }
483                 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
484                 if len(parts) > 2 {
485                         http.Error(w, "invalid path", http.StatusBadRequest)
486                         return
487                 }
488                 if len(parts) == 1 {
489                         if parts[0] == "" {
490                                 listRoot(w, r)
491                         } else {
492                                 listDir(w, r, parts[0], autorefresh, gpgUpdate)
493                         }
494                 } else {
495                         servePkg(w, r, parts[0], parts[1])
496                 }
497         case "POST":
498                 serveUpload(w, r)
499         default:
500                 http.Error(w, "unknown action", http.StatusBadRequest)
501         }
502 }
503
504 func goodIntegrity() bool {
505         dirs, err := ioutil.ReadDir(*root)
506         if err != nil {
507                 log.Fatal(err)
508         }
509         hasher := sha256.New()
510         digest := make([]byte, sha256.Size)
511         isGood := true
512         var data []byte
513         var pkgName string
514         for _, dir := range dirs {
515                 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
516                 if err != nil {
517                         log.Fatal(err)
518                 }
519                 for _, file := range files {
520                         if !strings.HasSuffix(file.Name(), SHA256Ext) {
521                                 continue
522                         }
523                         pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
524                         data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
525                         if err != nil {
526                                 if os.IsNotExist(err) {
527                                         continue
528                                 }
529                                 log.Fatal(err)
530                         }
531                         hasher.Write(data)
532                         data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
533                         if err != nil {
534                                 log.Fatal(err)
535                         }
536                         if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
537                                 log.Println(pkgName, "GOOD")
538                         } else {
539                                 isGood = false
540                                 log.Println(pkgName, "BAD")
541                         }
542                         hasher.Reset()
543                 }
544         }
545         return isGood
546 }
547
548 func main() {
549         flag.Parse()
550         if *warranty {
551                 fmt.Println(Warranty)
552                 return
553         }
554         if *version {
555                 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
556                 return
557         }
558         if *fsck {
559                 if !goodIntegrity() {
560                         os.Exit(1)
561                 }
562                 return
563         }
564         if *passwdCheck {
565                 refreshPasswd()
566                 return
567         }
568         if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
569                 log.Fatalln("Both -tls-cert and -tls-key are required")
570         }
571         refreshPasswd()
572         log.Println("root:", *root, "bind:", *bind)
573
574         ln, err := net.Listen("tcp", *bind)
575         if err != nil {
576                 log.Fatal(err)
577         }
578         ln = netutil.LimitListener(ln, *maxClients)
579         server := &http.Server{
580                 ReadTimeout:  time.Minute,
581                 WriteTimeout: time.Minute,
582         }
583         http.HandleFunc(*norefreshURLPath, handler)
584         http.HandleFunc(*refreshURLPath, handler)
585         http.HandleFunc(*gpgUpdateURLPath, handler)
586
587         needsRefreshPasswd := make(chan os.Signal, 0)
588         needsShutdown := make(chan os.Signal, 0)
589         exitErr := make(chan error, 0)
590         signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
591         signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
592         go func() {
593                 for range needsRefreshPasswd {
594                         log.Println("Refreshing passwords")
595                         refreshPasswd()
596                 }
597         }()
598         go func(s *http.Server) {
599                 <-needsShutdown
600                 killed = true
601                 log.Println("Shutting down")
602                 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
603                 exitErr <- s.Shutdown(ctx)
604                 cancel()
605         }(server)
606
607         if *tlsCert == "" {
608                 err = server.Serve(ln)
609         } else {
610                 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
611         }
612         if err != http.ErrServerClosed {
613                 log.Fatal(err)
614         }
615         if err := <-exitErr; err != nil {
616                 log.Fatal(err)
617         }
618 }