fun.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "crypto/rand"
20 "crypto/rsa"
21 "fmt"
22 "html"
23 "html/template"
24 "log"
25 "net/http"
26 "os"
27 "regexp"
28 "strings"
29 "sync"
30
31 "humungus.tedunangst.com/r/webs/htfilter"
32)
33
34func reverbolate(honks []*Honk) {
35 filt := htfilter.New()
36 for _, h := range honks {
37 h.What += "ed"
38 if h.Whofore == 2 || h.Whofore == 3 {
39 h.URL = h.XID
40 h.Noise = mentionize(h.Noise)
41 } else {
42 idx := strings.LastIndexByte(h.Honker, '/')
43 if idx != -1 {
44 h.Username = honkerhandle(h.Honker)
45 } else {
46 h.Username = h.Honker
47 }
48 if h.URL == "" {
49 h.URL = h.XID
50 }
51 }
52 zap := make(map[*Donk]bool)
53 h.Noise = unpucker(h.Noise)
54 precis := h.Precis
55 if precis != "" {
56 precis = "<p>summary: " + precis + "<p>"
57 }
58 h.HTML, _ = filt.String(precis + h.Noise)
59 emuxifier := func(e string) string {
60 for _, d := range h.Donks {
61 if d.Name == e {
62 zap[d] = true
63 return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
64 }
65 }
66 return e
67 }
68 h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
69 j := 0
70 for i := 0; i < len(h.Donks); i++ {
71 if !zap[h.Donks[i]] {
72 h.Donks[j] = h.Donks[i]
73 j++
74 }
75 }
76 h.Donks = h.Donks[:j]
77 }
78}
79
80func osmosis(honks []*Honk, userid int64) []*Honk {
81 zwords := getzwords(userid)
82 j := 0
83outer:
84 for _, h := range honks {
85 for _, z := range zwords {
86 if z.MatchString(h.Precis) || z.MatchString(h.Noise) {
87 continue outer
88 }
89 }
90 honks[j] = h
91 j++
92 }
93 return honks[0:j]
94}
95
96func shortxid(xid string) string {
97 idx := strings.LastIndexByte(xid, '/')
98 if idx == -1 {
99 return xid
100 }
101 return xid[idx+1:]
102}
103
104func xfiltrate() string {
105 letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
106 for {
107 var b [18]byte
108 rand.Read(b[:])
109 for i, c := range b {
110 b[i] = letters[c&63]
111 }
112 s := string(b[:])
113 return s
114 }
115}
116
117type Mention struct {
118 who string
119 where string
120}
121
122var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]+`)
123var re_urltions = regexp.MustCompile(`@https://\S+`)
124
125func grapevine(s string) []string {
126 var mentions []string
127 m := re_mentions.FindAllString(s, -1)
128 for i := range m {
129 where := gofish(m[i])
130 if where != "" {
131 mentions = append(mentions, where)
132 }
133 }
134 m = re_urltions.FindAllString(s, -1)
135 for i := range m {
136 mentions = append(mentions, m[i][1:])
137 }
138 return mentions
139}
140
141func bunchofgrapes(s string) []Mention {
142 m := re_mentions.FindAllString(s, -1)
143 var mentions []Mention
144 for i := range m {
145 where := gofish(m[i])
146 if where != "" {
147 mentions = append(mentions, Mention{who: m[i], where: where})
148 }
149 }
150 m = re_urltions.FindAllString(s, -1)
151 for i := range m {
152 mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
153 }
154 return mentions
155}
156
157type Emu struct {
158 ID string
159 Name string
160}
161
162var re_link = regexp.MustCompile(`@?https?://[^\s"]+[\w/)]`)
163var re_emus = regexp.MustCompile(`:[[:alnum:]_]+:`)
164
165func herdofemus(noise string) []Emu {
166 m := re_emus.FindAllString(noise, -1)
167 m = oneofakind(m)
168 var emus []Emu
169 for _, e := range m {
170 fname := e[1 : len(e)-1]
171 url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
172 emus = append(emus, Emu{ID: url, Name: e})
173 }
174 return emus
175}
176
177var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
178
179func memetics(noise string) []*Donk {
180 var donks []*Donk
181 m := re_memes.FindAllString(noise, -1)
182 for _, x := range m {
183 name := x[5:]
184 if name[0] == ' ' {
185 name = name[1:]
186 }
187 fd, err := os.Open("memes/" + name)
188 if err != nil {
189 log.Printf("no meme for %s", name)
190 continue
191 }
192 var peek [512]byte
193 n, _ := fd.Read(peek[:])
194 ct := http.DetectContentType(peek[:n])
195 fd.Close()
196
197 url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
198 res, err := stmtSaveFile.Exec("", name, url, ct, 0, "")
199 if err != nil {
200 log.Printf("error saving meme: %s", err)
201 continue
202 }
203 var d Donk
204 d.FileID, _ = res.LastInsertId()
205 d.XID = ""
206 d.Name = name
207 d.Media = ct
208 d.URL = url
209 d.Local = false
210 donks = append(donks, &d)
211 }
212 return donks
213}
214
215var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?'-]+)\*\*($|\W)`)
216var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?'-]+)\*($|\W)`)
217var re_bigcoder = regexp.MustCompile("```\n?((?s:.*?))\n?```\n?")
218var re_coder = regexp.MustCompile("`([^`]*)`")
219var re_quoter = regexp.MustCompile(`(?m:^> (.*)\n?)`)
220
221func markitzero(s string) string {
222 var bigcodes []string
223 bigsaver := func(code string) string {
224 bigcodes = append(bigcodes, code)
225 return "``````"
226 }
227 s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
228 var lilcodes []string
229 lilsaver := func(code string) string {
230 lilcodes = append(lilcodes, code)
231 return "`x`"
232 }
233 s = re_coder.ReplaceAllStringFunc(s, lilsaver)
234 s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
235 s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
236 s = re_quoter.ReplaceAllString(s, "<blockquote>$1</blockquote><p>")
237 lilun := func(s string) string {
238 code := lilcodes[0]
239 lilcodes = lilcodes[1:]
240 return code
241 }
242 s = re_coder.ReplaceAllStringFunc(s, lilun)
243 bigun := func(s string) string {
244 code := bigcodes[0]
245 bigcodes = bigcodes[1:]
246 return code
247 }
248 s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
249 s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre><p>")
250 s = re_coder.ReplaceAllString(s, "<code>$1</code>")
251 return s
252}
253
254func obfusbreak(s string) string {
255 s = strings.TrimSpace(s)
256 s = strings.Replace(s, "\r", "", -1)
257 s = html.EscapeString(s)
258 // dammit go
259 s = strings.Replace(s, "'", "'", -1)
260 linkfn := func(url string) string {
261 if url[0] == '@' {
262 return url
263 }
264 addparen := false
265 adddot := false
266 if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
267 url = url[:len(url)-1]
268 addparen = true
269 }
270 if strings.HasSuffix(url, ".") {
271 url = url[:len(url)-1]
272 adddot = true
273 }
274 url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
275 if adddot {
276 url += "."
277 }
278 if addparen {
279 url += ")"
280 }
281 return url
282 }
283 s = re_link.ReplaceAllStringFunc(s, linkfn)
284
285 s = markitzero(s)
286
287 s = strings.Replace(s, "\n", "<br>", -1)
288 return s
289}
290
291func mentionize(s string) string {
292 s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
293 where := gofish(m)
294 if where == "" {
295 return m
296 }
297 who := m[0 : 1+strings.IndexByte(m[1:], '@')]
298 return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
299 html.EscapeString(where), html.EscapeString(who))
300 })
301 s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
302 return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
303 html.EscapeString(m[1:]), html.EscapeString(m))
304 })
305 return s
306}
307
308var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
309
310func originate(u string) string {
311 m := re_unurl.FindStringSubmatch(u)
312 if len(m) > 2 {
313 return m[1]
314 }
315 return ""
316}
317
318func honkerhandle(h string) string {
319 m := re_unurl.FindStringSubmatch(h)
320 if len(m) > 2 {
321 return m[2]
322 }
323 return h
324}
325
326func prepend(s string, x []string) []string {
327 return append([]string{s}, x...)
328}
329
330// pleroma leaks followers addressed posts to followers
331func butnottooloud(aud []string) {
332 for i, a := range aud {
333 if strings.HasSuffix(a, "/followers") {
334 aud[i] = ""
335 }
336 }
337}
338
339func keepitquiet(aud []string) bool {
340 for _, a := range aud {
341 if a == thewholeworld {
342 return false
343 }
344 }
345 return true
346}
347
348func oneofakind(a []string) []string {
349 var x []string
350 for n, s := range a {
351 if s != "" {
352 x = append(x, s)
353 for i := n + 1; i < len(a); i++ {
354 if a[i] == s {
355 a[i] = ""
356 }
357 }
358 }
359 }
360 return x
361}
362
363var ziggies = make(map[string]*rsa.PrivateKey)
364var zaggies = make(map[string]*rsa.PublicKey)
365var ziggylock sync.Mutex
366
367func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
368 ziggylock.Lock()
369 key = ziggies[username]
370 ziggylock.Unlock()
371 if key == nil {
372 db := opendatabase()
373 row := db.QueryRow("select seckey from users where username = ?", username)
374 var data string
375 row.Scan(&data)
376 var err error
377 key, _, err = pez(data)
378 if err != nil {
379 log.Printf("error decoding %s seckey: %s", username, err)
380 return
381 }
382 ziggylock.Lock()
383 ziggies[username] = key
384 ziggylock.Unlock()
385 }
386 keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
387 return
388}
389
390func zaggy(keyname string) (key *rsa.PublicKey) {
391 ziggylock.Lock()
392 key = zaggies[keyname]
393 ziggylock.Unlock()
394 if key != nil {
395 return
396 }
397 db := opendatabase()
398 row := db.QueryRow("select pubkey from xonkers where xid = ?", keyname)
399 var data string
400 err := row.Scan(&data)
401 if err != nil {
402 log.Printf("hitting the webs for missing pubkey: %s", keyname)
403 j, err := GetJunk(keyname)
404 if err != nil {
405 log.Printf("error getting %s pubkey: %s", keyname, err)
406 return
407 }
408 var ok bool
409 data, ok = jsonfindstring(j, []string{"publicKey", "publicKeyPem"})
410 if !ok {
411 log.Printf("error finding %s pubkey", keyname)
412 return
413 }
414 _, ok = jsonfindstring(j, []string{"publicKey", "owner"})
415 if !ok {
416 log.Printf("error finding %s pubkey owner", keyname)
417 return
418 }
419 _, key, err = pez(data)
420 if err != nil {
421 log.Printf("error decoding %s pubkey: %s", keyname, err)
422 return
423 }
424 _, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
425 if err != nil {
426 log.Printf("error saving key: %s", err)
427 }
428 } else {
429 _, key, err = pez(data)
430 if err != nil {
431 log.Printf("error decoding %s pubkey: %s", keyname, err)
432 return
433 }
434 }
435 ziggylock.Lock()
436 zaggies[keyname] = key
437 ziggylock.Unlock()
438 return
439}
440
441func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
442 db := opendatabase()
443 _, err := db.Exec("delete from xonkers where xid = ?", keyname)
444 if err != nil {
445 log.Printf("error deleting key: %s", err)
446 }
447 ziggylock.Lock()
448 delete(zaggies, keyname)
449 ziggylock.Unlock()
450 return zag(r, payload)
451}
452
453var thumbbiters map[int64]map[string]bool
454var zwordses map[int64][]*regexp.Regexp
455var thumblock sync.Mutex
456
457func bitethethumbs() {
458 rows, err := stmtThumbBiters.Query()
459 if err != nil {
460 log.Printf("error getting thumbbiters: %s", err)
461 return
462 }
463 defer rows.Close()
464 thumblock.Lock()
465 defer thumblock.Unlock()
466 thumbbiters = make(map[int64]map[string]bool)
467 zwordses = make(map[int64][]*regexp.Regexp)
468 for rows.Next() {
469 var userid int64
470 var name, wherefore string
471 err = rows.Scan(&userid, &name, &wherefore)
472 if err != nil {
473 log.Printf("error scanning zonker: %s", err)
474 continue
475 }
476 if wherefore == "zword" {
477 zword := "\\b(?i:" + name + ")\\b"
478 re, err := regexp.Compile(zword)
479 if err != nil {
480 log.Printf("error compiling zword: %s", err)
481 } else {
482 zwordses[userid] = append(zwordses[userid], re)
483 }
484 continue
485 }
486 m := thumbbiters[userid]
487 if m == nil {
488 m = make(map[string]bool)
489 thumbbiters[userid] = m
490 }
491 m[name] = true
492 }
493}
494
495func getzwords(userid int64) []*regexp.Regexp {
496 thumblock.Lock()
497 defer thumblock.Unlock()
498 return zwordses[userid]
499}
500
501func thoudostbitethythumb(userid int64, who []string, objid string) bool {
502 thumblock.Lock()
503 biters := thumbbiters[userid]
504 thumblock.Unlock()
505 for _, w := range who {
506 if biters[w] {
507 return true
508 }
509 where := originate(w)
510 if where != "" {
511 if biters[where] {
512 return true
513 }
514 }
515 }
516 return false
517}
518
519func keymatch(keyname string, actor string) string {
520 hash := strings.IndexByte(keyname, '#')
521 if hash == -1 {
522 hash = len(keyname)
523 }
524 owner := keyname[0:hash]
525 if owner == actor {
526 return originate(actor)
527 }
528 return ""
529}