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 "humungus.tedunangst.com/r/webs/httpsig"
33)
34
35func reverbolate(userid int64, honks []*Honk) {
36 filt := htfilter.New()
37 zilences := getzilences(userid)
38 for _, h := range honks {
39 h.What += "ed"
40 if h.What == "tonked" {
41 h.What = "honked back"
42 h.Style = "subtle"
43 }
44 if !h.Public {
45 h.Style += " limited"
46 }
47 if h.Whofore == 2 || h.Whofore == 3 {
48 h.URL = h.XID
49 if h.What != "bonked" {
50 h.Noise = mentionize(h.Noise)
51 h.Noise = ontologize(h.Noise)
52 }
53 h.Username, h.Handle = handles(h.Honker)
54 } else {
55 _, h.Handle = handles(h.Honker)
56 h.Username = h.Handle
57 if len(h.Username) > 20 {
58 h.Username = h.Username[:20] + ".."
59 }
60 if h.URL == "" {
61 h.URL = h.XID
62 }
63 }
64 if h.Oonker != "" {
65 _, h.Oondle = handles(h.Oonker)
66 }
67 zap := make(map[*Donk]bool)
68 h.Noise = unpucker(h.Noise)
69 h.Open = "open"
70 if badword := unsee(zilences, h.Precis, h.Noise); badword != "" {
71 if h.Precis == "" {
72 h.Precis = badword
73 }
74 h.Open = ""
75 } else if h.Precis == "unspecified horror" {
76 h.Precis = ""
77 }
78 h.Precis = unpucker(h.Precis)
79 h.HTML, _ = filt.String(h.Noise)
80 emuxifier := func(e string) string {
81 for _, d := range h.Donks {
82 if d.Name == e {
83 zap[d] = true
84 if d.Local {
85 return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
86 }
87 }
88 }
89 return e
90 }
91 h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
92 j := 0
93 for i := 0; i < len(h.Donks); i++ {
94 if !zap[h.Donks[i]] {
95 h.Donks[j] = h.Donks[i]
96 j++
97 }
98 }
99 h.Donks = h.Donks[:j]
100 }
101}
102
103func unsee(zilences []*regexp.Regexp, precis string, noise string) string {
104 for _, z := range zilences {
105 if z.MatchString(precis) || z.MatchString(noise) {
106 if precis == "" {
107 w := z.String()
108 return w[6 : len(w)-3]
109 }
110 return precis
111 }
112 }
113 return ""
114}
115
116func osmosis(honks []*Honk, userid int64) []*Honk {
117 zords := getzords(userid)
118 j := 0
119outer:
120 for _, h := range honks {
121 for _, z := range zords {
122 if z.MatchString(h.Precis) || z.MatchString(h.Noise) {
123 continue outer
124 }
125 }
126 honks[j] = h
127 j++
128 }
129 honks = honks[0:j]
130 return honks
131}
132
133func shortxid(xid string) string {
134 idx := strings.LastIndexByte(xid, '/')
135 if idx == -1 {
136 return xid
137 }
138 return xid[idx+1:]
139}
140
141func xfiltrate() string {
142 letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
143 var b [18]byte
144 rand.Read(b[:])
145 for i, c := range b {
146 b[i] = letters[c&63]
147 }
148 s := string(b[:])
149 return s
150}
151
152var re_hashes = regexp.MustCompile(`(?:^| )#[[:alnum:]][[:alnum:]_-]*`)
153
154func ontologies(s string) []string {
155 m := re_hashes.FindAllString(s, -1)
156 j := 0
157 for _, h := range m {
158 if h[0] == '&' {
159 continue
160 }
161 if h[0] != '#' {
162 h = h[1:]
163 }
164 m[j] = h
165 j++
166 }
167 return m[:j]
168}
169
170type Mention struct {
171 who string
172 where string
173}
174
175var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]*[[:alnum:]]`)
176var re_urltions = regexp.MustCompile(`@https://\S+`)
177
178func grapevine(s string) []string {
179 var mentions []string
180 m := re_mentions.FindAllString(s, -1)
181 for i := range m {
182 where := gofish(m[i])
183 if where != "" {
184 mentions = append(mentions, where)
185 }
186 }
187 m = re_urltions.FindAllString(s, -1)
188 for i := range m {
189 mentions = append(mentions, m[i][1:])
190 }
191 return mentions
192}
193
194func bunchofgrapes(s string) []Mention {
195 m := re_mentions.FindAllString(s, -1)
196 var mentions []Mention
197 for i := range m {
198 where := gofish(m[i])
199 if where != "" {
200 mentions = append(mentions, Mention{who: m[i], where: where})
201 }
202 }
203 m = re_urltions.FindAllString(s, -1)
204 for i := range m {
205 mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
206 }
207 return mentions
208}
209
210type Emu struct {
211 ID string
212 Name string
213}
214
215var re_link = regexp.MustCompile(`@?https?://[^\s"]+[\w/)]`)
216var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
217
218func herdofemus(noise string) []Emu {
219 m := re_emus.FindAllString(noise, -1)
220 m = oneofakind(m)
221 var emus []Emu
222 for _, e := range m {
223 fname := e[1 : len(e)-1]
224 _, err := os.Stat("emus/" + fname + ".png")
225 if err != nil {
226 continue
227 }
228 url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
229 emus = append(emus, Emu{ID: url, Name: e})
230 }
231 return emus
232}
233
234var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
235
236func memetize(honk *Honk) {
237 repl := func(x string) string {
238 name := x[5:]
239 if name[0] == ' ' {
240 name = name[1:]
241 }
242 fd, err := os.Open("memes/" + name)
243 if err != nil {
244 log.Printf("no meme for %s", name)
245 return x
246 }
247 var peek [512]byte
248 n, _ := fd.Read(peek[:])
249 ct := http.DetectContentType(peek[:n])
250 fd.Close()
251
252 url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
253 res, err := stmtSaveFile.Exec("", name, url, ct, 0, "")
254 if err != nil {
255 log.Printf("error saving meme: %s", err)
256 return x
257 }
258 var d Donk
259 d.FileID, _ = res.LastInsertId()
260 d.XID = ""
261 d.Name = name
262 d.Media = ct
263 d.URL = url
264 d.Local = false
265 honk.Donks = append(honk.Donks, &d)
266 return ""
267 }
268 honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
269}
270
271var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?'-]+)\*\*($|\W)`)
272var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?'-]+)\*($|\W)`)
273var re_bigcoder = regexp.MustCompile("```\n?((?s:.*?))\n?```\n?")
274var re_coder = regexp.MustCompile("`([^`]*)`")
275var re_quoter = regexp.MustCompile(`(?m:^> (.*)\n?)`)
276
277func markitzero(s string) string {
278 var bigcodes []string
279 bigsaver := func(code string) string {
280 bigcodes = append(bigcodes, code)
281 return "``````"
282 }
283 s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
284 var lilcodes []string
285 lilsaver := func(code string) string {
286 lilcodes = append(lilcodes, code)
287 return "`x`"
288 }
289 s = re_coder.ReplaceAllStringFunc(s, lilsaver)
290 s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
291 s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
292 s = re_quoter.ReplaceAllString(s, "<blockquote>$1</blockquote><p>")
293 lilun := func(s string) string {
294 code := lilcodes[0]
295 lilcodes = lilcodes[1:]
296 return code
297 }
298 s = re_coder.ReplaceAllStringFunc(s, lilun)
299 bigun := func(s string) string {
300 code := bigcodes[0]
301 bigcodes = bigcodes[1:]
302 return code
303 }
304 s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
305 s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre><p>")
306 s = re_coder.ReplaceAllString(s, "<code>$1</code>")
307 return s
308}
309
310func obfusbreak(s string) string {
311 s = strings.TrimSpace(s)
312 s = strings.Replace(s, "\r", "", -1)
313 s = html.EscapeString(s)
314 // dammit go
315 s = strings.Replace(s, "'", "'", -1)
316 linkfn := func(url string) string {
317 if url[0] == '@' {
318 return url
319 }
320 addparen := false
321 adddot := false
322 if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
323 url = url[:len(url)-1]
324 addparen = true
325 }
326 if strings.HasSuffix(url, ".") {
327 url = url[:len(url)-1]
328 adddot = true
329 }
330 url = fmt.Sprintf(`<a class="mention u-url" href="%s">%s</a>`, url, url)
331 if adddot {
332 url += "."
333 }
334 if addparen {
335 url += ")"
336 }
337 return url
338 }
339 s = re_link.ReplaceAllStringFunc(s, linkfn)
340
341 s = markitzero(s)
342
343 s = strings.Replace(s, "\n", "<br>", -1)
344 return s
345}
346
347var re_quickmention = regexp.MustCompile("(^| )@[[:alnum:]]+ ")
348
349func quickrename(s string, userid int64) string {
350 return re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
351 prefix := ""
352 if m[0] == ' ' {
353 prefix = " "
354 m = m[1:]
355 }
356 prefix += "@"
357 m = m[1:]
358 m = m[:len(m)-1]
359
360 row := stmtOneHonker.QueryRow(m, userid)
361 var xid string
362 err := row.Scan(&xid)
363 if err == nil {
364 _, name := handles(xid)
365 if name != "" {
366 m = name
367 }
368 }
369 return prefix + m + " "
370 })
371}
372
373func mentionize(s string) string {
374 s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
375 where := gofish(m)
376 if where == "" {
377 return m
378 }
379 who := m[0 : 1+strings.IndexByte(m[1:], '@')]
380 return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
381 html.EscapeString(where), html.EscapeString(who))
382 })
383 s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
384 return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
385 html.EscapeString(m[1:]), html.EscapeString(m))
386 })
387 return s
388}
389
390func ontologize(s string) string {
391 s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
392 if o[0] == '&' {
393 return o
394 }
395 p := ""
396 h := o
397 if h[0] != '#' {
398 p = h[:1]
399 h = h[1:]
400 }
401 return fmt.Sprintf(`%s<a class="mention u-url" href="https://%s/o/%s">%s</a>`, p, serverName,
402 strings.ToLower(h[1:]), h)
403 })
404 return s
405}
406
407var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
408var re_urlhost = regexp.MustCompile("https://([^/]+)")
409
410func originate(u string) string {
411 m := re_urlhost.FindStringSubmatch(u)
412 if len(m) > 1 {
413 return m[1]
414 }
415 return ""
416}
417
418var allhandles = make(map[string]string)
419var handlelock sync.Mutex
420
421// handle, handle@host
422func handles(xid string) (string, string) {
423 if xid == "" {
424 return "", ""
425 }
426 handlelock.Lock()
427 handle := allhandles[xid]
428 handlelock.Unlock()
429 if handle == "" {
430 handle = findhandle(xid)
431 handlelock.Lock()
432 allhandles[xid] = handle
433 handlelock.Unlock()
434 }
435 if handle == xid {
436 return xid, xid
437 }
438 return handle, handle + "@" + originate(xid)
439}
440
441func findhandle(xid string) string {
442 row := stmtGetXonker.QueryRow(xid, "handle")
443 var handle string
444 err := row.Scan(&handle)
445 if err != nil {
446 p, _ := investigate(xid)
447 if p == nil {
448 m := re_unurl.FindStringSubmatch(xid)
449 if len(m) > 2 {
450 handle = m[2]
451 } else {
452 handle = xid
453 }
454 } else {
455 handle = p.Handle
456 }
457 _, err = stmtSaveXonker.Exec(xid, handle, "handle")
458 if err != nil {
459 log.Printf("error saving handle: %s", err)
460 }
461 }
462 return handle
463}
464
465var handleprelock sync.Mutex
466
467func prehandle(xid string) {
468 handleprelock.Lock()
469 defer handleprelock.Unlock()
470 handles(xid)
471}
472
473func prepend(s string, x []string) []string {
474 return append([]string{s}, x...)
475}
476
477// pleroma leaks followers addressed posts to followers
478func butnottooloud(aud []string) {
479 for i, a := range aud {
480 if strings.HasSuffix(a, "/followers") {
481 aud[i] = ""
482 }
483 }
484}
485
486func keepitquiet(aud []string) bool {
487 for _, a := range aud {
488 if a == thewholeworld {
489 return false
490 }
491 }
492 return true
493}
494
495func firstclass(honk *Honk) bool {
496 return honk.Audience[0] == thewholeworld
497}
498
499func oneofakind(a []string) []string {
500 var x []string
501 for n, s := range a {
502 if s != "" {
503 x = append(x, s)
504 for i := n + 1; i < len(a); i++ {
505 if a[i] == s {
506 a[i] = ""
507 }
508 }
509 }
510 }
511 return x
512}
513
514var ziggies = make(map[string]*rsa.PrivateKey)
515var zaggies = make(map[string]*rsa.PublicKey)
516var ziggylock sync.Mutex
517
518func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
519 ziggylock.Lock()
520 key = ziggies[username]
521 ziggylock.Unlock()
522 if key == nil {
523 db := opendatabase()
524 row := db.QueryRow("select seckey from users where username = ?", username)
525 var data string
526 row.Scan(&data)
527 var err error
528 key, _, err = httpsig.DecodeKey(data)
529 if err != nil {
530 log.Printf("error decoding %s seckey: %s", username, err)
531 return
532 }
533 ziggylock.Lock()
534 ziggies[username] = key
535 ziggylock.Unlock()
536 }
537 keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
538 return
539}
540
541func zaggy(keyname string) (key *rsa.PublicKey) {
542 ziggylock.Lock()
543 key = zaggies[keyname]
544 ziggylock.Unlock()
545 if key != nil {
546 return
547 }
548 row := stmtGetXonker.QueryRow(keyname, "pubkey")
549 var data string
550 err := row.Scan(&data)
551 if err != nil {
552 log.Printf("hitting the webs for missing pubkey: %s", keyname)
553 j, err := GetJunk(keyname)
554 if err != nil {
555 log.Printf("error getting %s pubkey: %s", keyname, err)
556 return
557 }
558 keyobj, ok := j.GetMap("publicKey")
559 if ok {
560 j = keyobj
561 }
562 data, ok = j.GetString("publicKeyPem")
563 if !ok {
564 log.Printf("error finding %s pubkey", keyname)
565 return
566 }
567 _, ok = j.GetString("owner")
568 if !ok {
569 log.Printf("error finding %s pubkey owner", keyname)
570 return
571 }
572 _, key, err = httpsig.DecodeKey(data)
573 if err != nil {
574 log.Printf("error decoding %s pubkey: %s", keyname, err)
575 return
576 }
577 _, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
578 if err != nil {
579 log.Printf("error saving key: %s", err)
580 }
581 } else {
582 _, key, err = httpsig.DecodeKey(data)
583 if err != nil {
584 log.Printf("error decoding %s pubkey: %s", keyname, err)
585 return
586 }
587 }
588 ziggylock.Lock()
589 zaggies[keyname] = key
590 ziggylock.Unlock()
591 return
592}
593
594func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
595 _, err := stmtDeleteXonker.Exec(keyname, "pubkey")
596 if err != nil {
597 log.Printf("error deleting key: %s", err)
598 }
599 ziggylock.Lock()
600 delete(zaggies, keyname)
601 ziggylock.Unlock()
602 return httpsig.VerifyRequest(r, payload, zaggy)
603}
604
605var thumbbiters map[int64]map[string]bool
606var zordses map[int64][]*regexp.Regexp
607var zilences map[int64][]*regexp.Regexp
608var thumblock sync.Mutex
609
610func bitethethumbs() {
611 rows, err := stmtThumbBiters.Query()
612 if err != nil {
613 log.Printf("error getting thumbbiters: %s", err)
614 return
615 }
616 defer rows.Close()
617
618 thumblock.Lock()
619 defer thumblock.Unlock()
620 thumbbiters = make(map[int64]map[string]bool)
621 zordses = make(map[int64][]*regexp.Regexp)
622 zilences = make(map[int64][]*regexp.Regexp)
623 for rows.Next() {
624 var userid int64
625 var name, wherefore string
626 err = rows.Scan(&userid, &name, &wherefore)
627 if err != nil {
628 log.Printf("error scanning zonker: %s", err)
629 continue
630 }
631 if wherefore == "zord" || wherefore == "zilence" {
632 zord := "\\b(?i:" + name + ")\\b"
633 re, err := regexp.Compile(zord)
634 if err != nil {
635 log.Printf("error compiling zord: %s", err)
636 } else {
637 if wherefore == "zord" {
638 zordses[userid] = append(zordses[userid], re)
639 } else {
640 zilences[userid] = append(zilences[userid], re)
641 }
642 }
643 continue
644 }
645 m := thumbbiters[userid]
646 if m == nil {
647 m = make(map[string]bool)
648 thumbbiters[userid] = m
649 }
650 m[name] = true
651 }
652}
653
654func getzords(userid int64) []*regexp.Regexp {
655 thumblock.Lock()
656 defer thumblock.Unlock()
657 return zordses[userid]
658}
659
660func getzilences(userid int64) []*regexp.Regexp {
661 thumblock.Lock()
662 defer thumblock.Unlock()
663 return zilences[userid]
664}
665
666func thoudostbitethythumb(userid int64, who []string, objid string) bool {
667 thumblock.Lock()
668 biters := thumbbiters[userid]
669 thumblock.Unlock()
670 objwhere := originate(objid)
671 if objwhere != "" && biters[objwhere] {
672 log.Printf("thumbbiter: %s", objid)
673 return true
674 }
675 for _, w := range who {
676 if biters[w] {
677 log.Printf("thumbbiter: %s", w)
678 return true
679 }
680 where := originate(w)
681 if where != "" {
682 if biters[where] {
683 log.Printf("thumbbiter: %s", w)
684 return true
685 }
686 }
687 }
688 return false
689}
690
691func keymatch(keyname string, actor string) string {
692 hash := strings.IndexByte(keyname, '#')
693 if hash == -1 {
694 hash = len(keyname)
695 }
696 owner := keyname[0:hash]
697 if owner == actor {
698 return originate(actor)
699 }
700 return ""
701}