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