-
Notifications
You must be signed in to change notification settings - Fork 13
/
pastedown.go
369 lines (339 loc) · 10.1 KB
/
pastedown.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package main
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"regexp"
"time"
"github.com/cespare/hutil/apachelog"
"github.com/gorilla/pat"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday/v2"
"github.com/cespare/pastedown/lru"
)
const (
staticDir = "public"
pygmentize = "./thirdparty/pygments/pygmentize"
viewFile = "view.html"
expirationCheckPeriodHours = 1
renderCacheSizeBytes = 20e6 // 20 MB
)
// User-configurable values
var (
listenAddr string
pastieDir string
mainPastie string
markdownRefPastie string
expirationTimeHours int
useTls bool
tlsCertFile string
tlsKeyFile string
)
var (
validLanguages = make(map[string]struct{})
bluemondayPolicy = bluemonday.UGCPolicy()
viewHTML []byte
filenameRegex = regexp.MustCompile(`^[\w\-]{27}\.\w+$`)
renderCache = lru.New(renderCacheSizeBytes)
)
func syntaxHighlight(out io.Writer, in io.Reader, language string) {
_, ok := validLanguages[language]
if !ok || language == "" {
language = "text"
}
pygmentsCommand := exec.Command(pygmentize, "-l", language, "-f", "html", "-P", "encoding=utf-8")
pygmentsCommand.Stdin = in
pygmentsCommand.Stdout = out
var stderr bytes.Buffer
pygmentsCommand.Stderr = &stderr
if err := pygmentsCommand.Run(); err != nil {
log.Println("Error with syntax highlighting:", err)
log.Println("Stderr:\n", stderr.String())
}
}
type Pastie struct {
Text string `json:"text"`
Format string `json:"format"`
}
func render(text []byte, format string) []byte {
var rendered []byte
switch format {
case "text":
rendered = text
case "markdown":
html := blackfriday.Run(text)
rendered = bluemondayPolicy.SanitizeBytes(html)
default:
var highlighted bytes.Buffer
in := bytes.NewBuffer(text)
syntaxHighlight(&highlighted, in, format)
rendered = highlighted.Bytes()
}
return rendered
}
func pastieHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get(":id")
if len(id) == 0 {
http.Error(w, "No such file.", http.StatusInternalServerError)
return
}
var filename string
// If the filename is one made by Pastedown, then look in the directory
// structure we expect; otherwise, just try to find such a file directly.
if filenameRegex.MatchString(id) {
filename = path.Join(pastieDir, id[:2], id[2:])
} else {
filename = path.Join(pastieDir, id)
}
// Render the proper format according to the extension if ?rendered=true.
if r.URL.Query().Get("rendered") == "true" {
// First try to find the rendered document in cache
rendered, ok := renderCache.Get(filename)
if ok {
w.Write(rendered)
return
}
// Wasn't in cache; render it from disk.
contents, err := ioutil.ReadFile(filename)
if err != nil {
http.Error(w, "No such file.", http.StatusNotFound)
return
}
extension := path.Ext(id)
if extension == "" {
extension = "text"
} else {
extension = extension[1:]
}
rendered = render(contents, extension)
renderCache.Insert(filename, rendered)
w.Write(rendered)
return
}
// Return the raw contents if ?rendered=true wasn't set.
contents, err := ioutil.ReadFile(filename)
if err != nil {
http.Error(w, "No such file.", http.StatusNotFound)
return
}
// Fetch the value to mark it as recently used.
_, _ = renderCache.Get(filename)
w.Write(contents)
}
func decodePastie(r *http.Request) (*Pastie, error) {
text, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
pastie := &Pastie{}
err = json.Unmarshal(text, pastie)
if err != nil {
return nil, err
}
return pastie, nil
}
func previewHandler(w http.ResponseWriter, r *http.Request) {
preview, err := decodePastie(r)
if err != nil {
http.Error(w, "Could not render preview text.", http.StatusInternalServerError)
return
}
w.Write(render([]byte(preview.Text), preview.Format))
}
func saveHandler(w http.ResponseWriter, r *http.Request) {
preview, err := decodePastie(r)
bytes := []byte(preview.Text)
if err != nil {
log.Println("Error decoding pastie for saving: " + err.Error())
http.Error(w, "Could not save text.", http.StatusInternalServerError)
return
}
sha := sha1.New()
sha.Write(bytes)
hash := base64.URLEncoding.EncodeToString(sha.Sum(nil))
// The filename is constructed in the following manner:
//
// - Chop off the last '=' (padding character) of the hash -- all the
// shas are the same length anyway so we might as well get rid of the
// character that they all have in common.
// - Chop the first two characters off the front of the hash and use
// this as the directory to limit the number of files in a single
// directory (git uses this trick for its object store).
// - The full file format name is used as the extension.
//
// So for example:
// { sha: jBEtyBOnX_M2rp7DNp3mQskWqwg=, filetype: markdown } => jB/EtyBOnX_M2rp7DNp3mQskWqwg.markdown
directory := path.Join(pastieDir, hash[0:2])
logicalName := hash[:len(hash)-1] + "." + preview.Format
filename := path.Join(directory, hash[2:len(hash)-1]+"."+preview.Format)
err = os.MkdirAll(directory, 0771)
if err != nil {
log.Println("Error creating new directory: " + err.Error())
http.Error(w, "Could not save text.", http.StatusInternalServerError)
return
}
_, err = os.Stat(filename)
if err == nil {
log.Println("Request for existing pastie: " + filename)
} else {
log.Println("Saving new pastie: " + filename)
err = ioutil.WriteFile(filename, bytes, 0666)
if err != nil {
log.Println("Error writing pastie file: " + err.Error())
http.Error(w, "Could not save text.", http.StatusInternalServerError)
return
}
}
// Otherwise file already exists.
w.Write([]byte(logicalName))
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Redirect(w, r, "/", http.StatusFound)
return
}
w.Write(viewHTML)
}
func expire() {
log.Println("Expiring files...")
dirs, err := ioutil.ReadDir(pastieDir)
if err != nil {
log.Println("Error reading file directory: " + err.Error())
return
}
expiredFiles := 0
expiredDirs := 0
for _, d := range dirs {
if !d.IsDir() {
continue
}
dirPath := path.Join(pastieDir, d.Name())
files, err := ioutil.ReadDir(dirPath)
if err != nil {
log.Println("Error reading file directory: " + err.Error())
continue
}
unexpired := false
for _, f := range files {
if time.Since(f.ModTime()).Hours() <= float64(expirationTimeHours) {
unexpired = true
continue
}
filepath := path.Join(dirPath, f.Name())
// Remove from cache
renderCache.Delete(filepath)
// Remove from disk
if err := os.Remove(filepath); err != nil {
log.Println("Error deleting file: " + err.Error())
continue
}
expiredFiles++
}
if !unexpired {
if err := os.Remove(dirPath); err != nil {
log.Println("Error deleting empty directory: " + err.Error())
continue
}
expiredDirs++
}
}
log.Printf("Removed %d expired files and %d empty directories.\n", expiredFiles, expiredDirs)
}
// Creates a string describing the expiry time.
func createExpiryMsg() string {
switch {
case expirationTimeHours == 0:
return "documents are not deleted"
case expirationTimeHours > 48:
return fmt.Sprintf("documents are deleted after %d days", expirationTimeHours/24)
}
return fmt.Sprintf("documents are deleted after %d hours", expirationTimeHours)
}
func main() {
flag.StringVar(&listenAddr, "listenaddr", "localhost:8389", "The server address on which to listen")
flag.StringVar(&pastieDir, "storagedir", "files", "The directory in which to store documents")
flag.StringVar(&mainPastie, "mainpage", "about.markdown", "The document to display on the front page")
flag.StringVar(&markdownRefPastie, "referencepage", "reference.markdown",
"The document to display at the 'markdown reference' link")
flag.IntVar(&expirationTimeHours, "expirationhours", 7*24,
"How long to keep documents before deleting them (0 for 'never delete')")
flag.BoolVar(&useTls, "tls", false, "Whether to serve over HTTPS.")
flag.StringVar(&tlsCertFile, "certfile", "cert.pem", "TLS certificate file to use")
flag.StringVar(&tlsKeyFile, "keyfile", "key.pem", "TLS private key file to use")
flag.Parse()
// Get the list of valid lexers from pygments.
rawLexerList, err := exec.Command(pygmentize, "-L", "lexers").Output()
if err != nil {
log.Fatalln("Failed to execute pygments:", err)
}
for _, line := range bytes.Split(rawLexerList, []byte("\n")) {
if len(line) == 0 || line[0] != '*' {
continue
}
for _, l := range bytes.Split(bytes.Trim(line, "* :"), []byte(",")) {
lexer := string(bytes.TrimSpace(l))
if len(lexer) != 0 {
validLanguages[lexer] = struct{}{}
}
}
}
// Check that the main info file exists.
_, err = os.Stat(pastieDir + "/" + mainPastie)
if err != nil {
log.Fatalln("Error with main info file: " + err.Error())
}
// Start the background file deleter going
if expirationTimeHours > 0 {
go func() {
ticker := time.NewTicker(expirationCheckPeriodHours * time.Hour)
for range ticker.C {
expire()
}
}()
}
// Load in the main view template
viewTemplate, err := template.ParseFiles(viewFile)
if err != nil {
log.Fatalln(err)
}
b := new(bytes.Buffer)
templateData := struct {
ExpiryMsg, MainId, MarkdownRefId string
}{createExpiryMsg(), mainPastie, markdownRefPastie}
err = viewTemplate.Execute(b, templateData)
if err != nil {
log.Fatalln(err)
}
viewHTML = b.Bytes()
// Set up the server
mux := pat.New()
mux.Add("GET", "/favicon.ico", http.FileServer(http.Dir(staticDir)))
staticPath := "/" + staticDir + "/"
mux.Add("GET", staticPath, http.StripPrefix(staticPath, http.FileServer(http.Dir("./"+staticDir))))
mux.Get(`/files/{id:[\w\.\-]+}`, pastieHandler)
mux.Post("/preview", previewHandler)
mux.Put("/file", saveHandler)
mux.Get("/", viewHandler)
handler := apachelog.NewDefaultHandler(mux)
server := &http.Server{
Addr: listenAddr,
Handler: handler,
}
log.Println("Now listening on", listenAddr, " TLS =", useTls)
if useTls {
log.Fatal(server.ListenAndServeTLS(tlsCertFile, tlsKeyFile))
} else {
log.Fatal(server.ListenAndServe())
}
}