]> Cypherpunks.ru repositories - gocheese.git/blob - main.go
Passwords listing ability
[gocheese.git] / main.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         maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
96         doUCSPI    = flag.Bool("ucspi", false, "Work as UCSPI-TCP service")
97
98         tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
99         tlsKey  = flag.String("tls-key", "", "Path to TLS X.509 private key")
100
101         norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
102         refreshURLPath   = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
103         gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
104
105         pypiURL      = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
106         pypiCertHash = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
107
108         passwdPath     = flag.String("passwd", "", "Path to FIFO for upload authentication")
109         passwdListPath = flag.String("passwd-list", "", "Path to FIFO for login listing")
110         passwdCheck    = flag.Bool("passwd-check", false, "Run password checker")
111
112         logTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
113         fsck           = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
114         version        = flag.Bool("version", false, "Print version information")
115         warranty       = flag.Bool("warranty", false, "Print warranty information")
116
117         killed        bool
118         pypiURLParsed *url.URL
119 )
120
121 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
122         path := filepath.Join(*root, pkgName)
123         if _, err := os.Stat(path); os.IsNotExist(err) {
124                 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
125                         log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
126                         http.Error(w, err.Error(), http.StatusInternalServerError)
127                         return false
128                 }
129                 log.Println(r.RemoteAddr, "mkdir", pkgName)
130         }
131         return true
132 }
133
134 func listRoot(w http.ResponseWriter, r *http.Request) {
135         files, err := ioutil.ReadDir(*root)
136         if err != nil {
137                 log.Println("error", r.RemoteAddr, "root", err)
138                 http.Error(w, err.Error(), http.StatusInternalServerError)
139                 return
140         }
141         var result bytes.Buffer
142         result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
143         for _, file := range files {
144                 if file.Mode().IsDir() {
145                         result.WriteString(fmt.Sprintf(
146                                 HTMLElement,
147                                 *refreshURLPath+file.Name()+"/",
148                                 "", file.Name(),
149                         ))
150                 }
151         }
152         result.WriteString(HTMLEnd)
153         w.Write(result.Bytes())
154 }
155
156 func listDir(
157         w http.ResponseWriter,
158         r *http.Request,
159         pkgName string,
160         autorefresh, gpgUpdate bool,
161 ) {
162         dirPath := filepath.Join(*root, pkgName)
163         if autorefresh {
164                 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
165                         return
166                 }
167         } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
168                 return
169         }
170         fis, err := ioutil.ReadDir(dirPath)
171         if err != nil {
172                 log.Println("error", r.RemoteAddr, "list", pkgName, err)
173                 http.Error(w, err.Error(), http.StatusInternalServerError)
174                 return
175         }
176         files := make(map[string]struct{}, len(fis)/2)
177         for _, fi := range fis {
178                 files[fi.Name()] = struct{}{}
179         }
180         var result bytes.Buffer
181         result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
182         for _, algo := range knownHashAlgos {
183                 for fn := range files {
184                         if killed {
185                                 // Skip expensive I/O when shutting down
186                                 http.Error(w, "shutting down", http.StatusInternalServerError)
187                                 return
188                         }
189                         if !strings.HasSuffix(fn, "."+algo) {
190                                 continue
191                         }
192                         delete(files, fn)
193                         digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
194                         if err != nil {
195                                 log.Println("error", r.RemoteAddr, "list", fn, err)
196                                 http.Error(w, err.Error(), http.StatusInternalServerError)
197                                 return
198                         }
199                         fnClean := strings.TrimSuffix(fn, "."+algo)
200                         delete(files, fnClean)
201                         gpgSigAttr := ""
202                         if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
203                                 gpgSigAttr = " data-gpg-sig=true"
204                                 delete(files, fnClean+GPGSigExt)
205                         }
206                         result.WriteString(fmt.Sprintf(
207                                 HTMLElement,
208                                 strings.Join([]string{
209                                         *refreshURLPath, pkgName, "/", fnClean,
210                                         "#", algo, "=", hex.EncodeToString(digest),
211                                 }, ""),
212                                 gpgSigAttr,
213                                 fnClean,
214                         ))
215                 }
216         }
217         result.WriteString(HTMLEnd)
218         w.Write(result.Bytes())
219 }
220
221 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
222         log.Println(r.RemoteAddr, "get", filename)
223         path := filepath.Join(*root, pkgName, filename)
224         if _, err := os.Stat(path); os.IsNotExist(err) {
225                 if !refreshDir(w, r, pkgName, filename, false) {
226                         return
227                 }
228         }
229         http.ServeFile(w, r, path)
230 }
231
232 func handler(w http.ResponseWriter, r *http.Request) {
233         switch r.Method {
234         case "GET":
235                 var path string
236                 var autorefresh bool
237                 var gpgUpdate bool
238                 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
239                         path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
240                 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
241                         path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
242                         autorefresh = true
243                 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
244                         path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
245                         autorefresh = true
246                         gpgUpdate = true
247                 } else {
248                         http.Error(w, "unknown action", http.StatusBadRequest)
249                         return
250                 }
251                 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
252                 if len(parts) > 2 {
253                         http.Error(w, "invalid path", http.StatusBadRequest)
254                         return
255                 }
256                 if len(parts) == 1 {
257                         if parts[0] == "" {
258                                 listRoot(w, r)
259                         } else {
260                                 listDir(w, r, parts[0], autorefresh, gpgUpdate)
261                         }
262                 } else {
263                         servePkg(w, r, parts[0], parts[1])
264                 }
265         case "POST":
266                 serveUpload(w, r)
267         default:
268                 http.Error(w, "unknown action", http.StatusBadRequest)
269         }
270 }
271
272 func main() {
273         flag.Parse()
274         if *warranty {
275                 fmt.Println(Warranty)
276                 return
277         }
278         if *version {
279                 fmt.Println("GoCheese", Version, "built with", runtime.Version())
280                 return
281         }
282
283         if *logTimestamped {
284                 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
285         } else {
286                 log.SetFlags(log.Lshortfile)
287         }
288         if !*doUCSPI {
289                 log.SetOutput(os.Stdout)
290         }
291
292         if *fsck {
293                 if !goodIntegrity() {
294                         os.Exit(1)
295                 }
296                 return
297         }
298
299         if *passwdCheck {
300                 if passwdReader(os.Stdin) {
301                         os.Exit(0)
302                 } else {
303                         os.Exit(1)
304                 }
305         }
306
307         if *passwdPath != "" {
308                 go func() {
309                         for {
310                                 fd, err := os.OpenFile(
311                                         *passwdPath,
312                                         os.O_RDONLY,
313                                         os.FileMode(0666),
314                                 )
315                                 if err != nil {
316                                         log.Fatalln(err)
317                                 }
318                                 passwdReader(fd)
319                                 fd.Close()
320                         }
321                 }()
322         }
323         if *passwdListPath != "" {
324                 go func() {
325                         for {
326                                 fd, err := os.OpenFile(
327                                         *passwdListPath,
328                                         os.O_WRONLY|os.O_APPEND,
329                                         os.FileMode(0666),
330                                 )
331                                 if err != nil {
332                                         log.Fatalln(err)
333                                 }
334                                 passwdLister(fd)
335                                 fd.Close()
336                         }
337                 }()
338         }
339
340         if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
341                 log.Fatalln("Both -tls-cert and -tls-key are required")
342         }
343
344         var err error
345         pypiURLParsed, err = url.Parse(*pypiURL)
346         if err != nil {
347                 log.Fatalln(err)
348         }
349         tlsConfig := tls.Config{
350                 ClientSessionCache: tls.NewLRUClientSessionCache(16),
351                 NextProtos:         []string{"h2", "http/1.1"},
352         }
353         pypiHTTPTransport = http.Transport{
354                 ForceAttemptHTTP2: true,
355                 TLSClientConfig:   &tlsConfig,
356         }
357         if *pypiCertHash != "" {
358                 ourDgst, err := hex.DecodeString(*pypiCertHash)
359                 if err != nil {
360                         log.Fatalln(err)
361                 }
362                 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
363                         spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
364                         theirDgst := sha256.Sum256(spki)
365                         if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
366                                 return errors.New("certificate's SPKI digest mismatch")
367                         }
368                         return nil
369                 }
370         }
371
372         server := &http.Server{
373                 ReadTimeout:  time.Minute,
374                 WriteTimeout: time.Minute,
375         }
376         http.HandleFunc(*norefreshURLPath, handler)
377         http.HandleFunc(*refreshURLPath, handler)
378         if *gpgUpdateURLPath != "" {
379                 http.HandleFunc(*gpgUpdateURLPath, handler)
380         }
381
382         if *doUCSPI {
383                 server.SetKeepAlivesEnabled(false)
384                 ln := &UCSPI{}
385                 server.ConnState = connStater
386                 err := server.Serve(ln)
387                 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
388                         log.Fatalln(err)
389                 }
390                 UCSPIJob.Wait()
391                 return
392         }
393
394         ln, err := net.Listen("tcp", *bind)
395         if err != nil {
396                 log.Fatal(err)
397         }
398         ln = netutil.LimitListener(ln, *maxClients)
399
400         needsShutdown := make(chan os.Signal, 0)
401         exitErr := make(chan error, 0)
402         signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
403         go func(s *http.Server) {
404                 <-needsShutdown
405                 killed = true
406                 log.Println("shutting down")
407                 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
408                 exitErr <- s.Shutdown(ctx)
409                 cancel()
410         }(server)
411
412         log.Println(
413                 "GoCheese", Version, "listens:",
414                 "root:", *root,
415                 "bind:", *bind,
416                 "pypi:", *pypiURL,
417         )
418         if *tlsCert == "" {
419                 err = server.Serve(ln)
420         } else {
421                 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
422         }
423         if err != http.ErrServerClosed {
424                 log.Fatal(err)
425         }
426         if err := <-exitErr; err != nil {
427                 log.Fatal(err)
428         }
429 }