]> Cypherpunks.ru repositories - gocheese.git/blob - gocheese.go
FIFO-based password management
[gocheese.git] / gocheese.go
1 /*
2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019-2021 Sergey Matveev <stargrave@stargrave.org>
4               2019-2021 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         "crypto/tls"
27         "encoding/hex"
28         "errors"
29         "flag"
30         "fmt"
31         "io/ioutil"
32         "log"
33         "net"
34         "net/http"
35         "net/url"
36         "os"
37         "os/signal"
38         "path/filepath"
39         "regexp"
40         "runtime"
41         "strings"
42         "syscall"
43         "time"
44
45         "golang.org/x/net/netutil"
46 )
47
48 const (
49         Version   = "3.0.0"
50         HTMLBegin = `<!DOCTYPE html>
51 <html>
52   <head>
53     <title>Links for %s</title>
54   </head>
55   <body>
56 `
57         HTMLEnd      = "  </body>\n</html>\n"
58         HTMLElement  = "    <a href=\"%s\"%s>%s</a><br/>\n"
59         InternalFlag = ".internal"
60         GPGSigExt    = ".asc"
61
62         Warranty = `This program is free software: you can redistribute it and/or modify
63 it under the terms of the GNU General Public License as published by
64 the Free Software Foundation, version 3 of the License.
65
66 This program is distributed in the hope that it will be useful,
67 but WITHOUT ANY WARRANTY; without even the implied warranty of
68 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
69 GNU General Public License for more details.
70
71 You should have received a copy of the GNU General Public License
72 along with this program.  If not, see <http://www.gnu.org/licenses/>.`
73 )
74
75 const (
76         HashAlgoSHA256     = "sha256"
77         HashAlgoBLAKE2b256 = "blake2_256"
78         HashAlgoSHA512     = "sha512"
79         HashAlgoMD5        = "md5"
80 )
81
82 var (
83         pkgPyPI         = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
84         normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
85
86         knownHashAlgos []string = []string{
87                 HashAlgoSHA256,
88                 HashAlgoBLAKE2b256,
89                 HashAlgoSHA512,
90                 HashAlgoMD5,
91         }
92
93         root             = flag.String("root", "./packages", "Path to packages directory")
94         bind             = flag.String("bind", "[::]:8080", "Address to bind to")
95         tlsCert          = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
96         tlsKey           = flag.String("tls-key", "", "Path to TLS X.509 private key")
97         norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
98         refreshURLPath   = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
99         gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
100         pypiURL          = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
101         pypiCertHash     = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
102         logTimestamped   = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
103         passwdPath       = flag.String("passwd", "", "Path to FIFO for upload authentication")
104         passwdCheck      = flag.Bool("passwd-check", false, "Run password checker")
105         fsck             = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
106         maxClients       = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
107         version          = flag.Bool("version", false, "Print version information")
108         warranty         = flag.Bool("warranty", false, "Print warranty information")
109
110         killed        bool
111         pypiURLParsed *url.URL
112 )
113
114 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
115         path := filepath.Join(*root, pkgName)
116         if _, err := os.Stat(path); os.IsNotExist(err) {
117                 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
118                         log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
119                         http.Error(w, err.Error(), http.StatusInternalServerError)
120                         return false
121                 }
122                 log.Println(r.RemoteAddr, "mkdir", pkgName)
123         }
124         return true
125 }
126
127 func listRoot(w http.ResponseWriter, r *http.Request) {
128         files, err := ioutil.ReadDir(*root)
129         if err != nil {
130                 log.Println("error", r.RemoteAddr, "root", err)
131                 http.Error(w, err.Error(), http.StatusInternalServerError)
132                 return
133         }
134         var result bytes.Buffer
135         result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
136         for _, file := range files {
137                 if file.Mode().IsDir() {
138                         result.WriteString(fmt.Sprintf(
139                                 HTMLElement,
140                                 *refreshURLPath+file.Name()+"/",
141                                 "", file.Name(),
142                         ))
143                 }
144         }
145         result.WriteString(HTMLEnd)
146         w.Write(result.Bytes())
147 }
148
149 func listDir(
150         w http.ResponseWriter,
151         r *http.Request,
152         pkgName string,
153         autorefresh, gpgUpdate bool,
154 ) {
155         dirPath := filepath.Join(*root, pkgName)
156         if autorefresh {
157                 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
158                         return
159                 }
160         } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
161                 return
162         }
163         fis, err := ioutil.ReadDir(dirPath)
164         if err != nil {
165                 log.Println("error", r.RemoteAddr, "list", pkgName, err)
166                 http.Error(w, err.Error(), http.StatusInternalServerError)
167                 return
168         }
169         files := make(map[string]struct{}, len(fis)/2)
170         for _, fi := range fis {
171                 files[fi.Name()] = struct{}{}
172         }
173         var result bytes.Buffer
174         result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
175         for _, algo := range knownHashAlgos {
176                 for fn := range files {
177                         if killed {
178                                 // Skip expensive I/O when shutting down
179                                 http.Error(w, "shutting down", http.StatusInternalServerError)
180                                 return
181                         }
182                         if !strings.HasSuffix(fn, "."+algo) {
183                                 continue
184                         }
185                         delete(files, fn)
186                         digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
187                         if err != nil {
188                                 log.Println("error", r.RemoteAddr, "list", fn, err)
189                                 http.Error(w, err.Error(), http.StatusInternalServerError)
190                                 return
191                         }
192                         fnClean := strings.TrimSuffix(fn, "."+algo)
193                         delete(files, fnClean)
194                         gpgSigAttr := ""
195                         if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
196                                 gpgSigAttr = " data-gpg-sig=true"
197                                 delete(files, fnClean+GPGSigExt)
198                         }
199                         result.WriteString(fmt.Sprintf(
200                                 HTMLElement,
201                                 strings.Join([]string{
202                                         *refreshURLPath, pkgName, "/", fnClean,
203                                         "#", algo, "=", hex.EncodeToString(digest),
204                                 }, ""),
205                                 gpgSigAttr,
206                                 fnClean,
207                         ))
208                 }
209         }
210         result.WriteString(HTMLEnd)
211         w.Write(result.Bytes())
212 }
213
214 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
215         log.Println(r.RemoteAddr, "get", filename)
216         path := filepath.Join(*root, pkgName, filename)
217         if _, err := os.Stat(path); os.IsNotExist(err) {
218                 if !refreshDir(w, r, pkgName, filename, false) {
219                         return
220                 }
221         }
222         http.ServeFile(w, r, path)
223 }
224
225 func handler(w http.ResponseWriter, r *http.Request) {
226         switch r.Method {
227         case "GET":
228                 var path string
229                 var autorefresh bool
230                 var gpgUpdate bool
231                 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
232                         path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
233                 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
234                         path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
235                         autorefresh = true
236                 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
237                         path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
238                         autorefresh = true
239                         gpgUpdate = true
240                 } else {
241                         http.Error(w, "unknown action", http.StatusBadRequest)
242                         return
243                 }
244                 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
245                 if len(parts) > 2 {
246                         http.Error(w, "invalid path", http.StatusBadRequest)
247                         return
248                 }
249                 if len(parts) == 1 {
250                         if parts[0] == "" {
251                                 listRoot(w, r)
252                         } else {
253                                 listDir(w, r, parts[0], autorefresh, gpgUpdate)
254                         }
255                 } else {
256                         servePkg(w, r, parts[0], parts[1])
257                 }
258         case "POST":
259                 serveUpload(w, r)
260         default:
261                 http.Error(w, "unknown action", http.StatusBadRequest)
262         }
263 }
264
265 func main() {
266         flag.Parse()
267         if *warranty {
268                 fmt.Println(Warranty)
269                 return
270         }
271         if *version {
272                 fmt.Println("GoCheese", Version, "built with", runtime.Version())
273                 return
274         }
275
276         if *logTimestamped {
277                 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
278         } else {
279                 log.SetFlags(log.Lshortfile)
280         }
281         log.SetOutput(os.Stdout)
282
283         if *fsck {
284                 if !goodIntegrity() {
285                         os.Exit(1)
286                 }
287                 return
288         }
289
290         if *passwdCheck {
291                 if passwdReader(os.Stdin) {
292                         os.Exit(0)
293                 } else {
294                         os.Exit(1)
295                 }
296         }
297
298         if *passwdPath != "" {
299                 go func() {
300                         for {
301                                 fd, err := os.OpenFile(*passwdPath, os.O_RDONLY, os.FileMode(0666))
302                                 if err != nil {
303                                         log.Fatalln(err)
304                                 }
305                                 passwdReader(fd)
306                                 fd.Close()
307                         }
308                 }()
309         }
310
311         if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
312                 log.Fatalln("Both -tls-cert and -tls-key are required")
313         }
314
315         var err error
316         pypiURLParsed, err = url.Parse(*pypiURL)
317         if err != nil {
318                 log.Fatalln(err)
319         }
320         tlsConfig := tls.Config{
321                 ClientSessionCache: tls.NewLRUClientSessionCache(16),
322                 NextProtos:         []string{"h2", "http/1.1"},
323         }
324         pypiHTTPTransport = http.Transport{
325                 ForceAttemptHTTP2: true,
326                 TLSClientConfig:   &tlsConfig,
327         }
328         if *pypiCertHash != "" {
329                 ourDgst, err := hex.DecodeString(*pypiCertHash)
330                 if err != nil {
331                         log.Fatalln(err)
332                 }
333                 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
334                         spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
335                         theirDgst := sha256.Sum256(spki)
336                         if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
337                                 return errors.New("certificate's SPKI digest mismatch")
338                         }
339                         return nil
340                 }
341         }
342
343         ln, err := net.Listen("tcp", *bind)
344         if err != nil {
345                 log.Fatal(err)
346         }
347         ln = netutil.LimitListener(ln, *maxClients)
348         server := &http.Server{
349                 ReadTimeout:  time.Minute,
350                 WriteTimeout: time.Minute,
351         }
352         http.HandleFunc(*norefreshURLPath, handler)
353         http.HandleFunc(*refreshURLPath, handler)
354         if *gpgUpdateURLPath != "" {
355                 http.HandleFunc(*gpgUpdateURLPath, handler)
356         }
357
358         needsShutdown := make(chan os.Signal, 0)
359         exitErr := make(chan error, 0)
360         signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
361         go func(s *http.Server) {
362                 <-needsShutdown
363                 killed = true
364                 log.Println("shutting down")
365                 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
366                 exitErr <- s.Shutdown(ctx)
367                 cancel()
368         }(server)
369
370         log.Println(
371                 "GoCheese", Version, "listens:",
372                 "root:", *root,
373                 "bind:", *bind,
374                 "pypi:", *pypiURL,
375         )
376         if *tlsCert == "" {
377                 err = server.Serve(ln)
378         } else {
379                 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
380         }
381         if err != http.ErrServerClosed {
382                 log.Fatal(err)
383         }
384         if err := <-exitErr; err != nil {
385                 log.Fatal(err)
386         }
387 }