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