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(`(?:^|\W)#[[: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
347func mentionize(s string) string {
348 s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
349 where := gofish(m)
350 if where == "" {
351 return m
352 }
353 who := m[0 : 1+strings.IndexByte(m[1:], '@')]
354 return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
355 html.EscapeString(where), html.EscapeString(who))
356 })
357 s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
358 return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
359 html.EscapeString(m[1:]), html.EscapeString(m))
360 })
361 return s
362}
363
364func ontologize(s string) string {
365 s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
366 if o[0] == '&' {
367 return o
368 }
369 p := ""
370 h := o
371 if h[0] != '#' {
372 p = h[:1]
373 h = h[1:]
374 }
375 log.Printf("fixing: %s", o)
376 return fmt.Sprintf(`%s<a href="https://%s/o/%s">%s</a>`, p, serverName, h[1:], h)
377 })
378 return s
379}
380
381var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
382var re_urlhost = regexp.MustCompile("https://([^/]+)")
383
384func originate(u string) string {
385 m := re_urlhost.FindStringSubmatch(u)
386 if len(m) > 1 {
387 return m[1]
388 }
389 return ""
390}
391
392var allhandles = make(map[string]string)
393var handlelock sync.Mutex
394
395// handle, handle@host
396func handles(xid string) (string, string) {
397 if xid == "" {
398 return "", ""
399 }
400 handlelock.Lock()
401 handle := allhandles[xid]
402 handlelock.Unlock()
403 if handle == "" {
404 handle = findhandle(xid)
405 handlelock.Lock()
406 allhandles[xid] = handle
407 handlelock.Unlock()
408 }
409 if handle == xid {
410 return xid, xid
411 }
412 return handle, handle + "@" + originate(xid)
413}
414
415func findhandle(xid string) string {
416 row := stmtGetXonker.QueryRow(xid, "handle")
417 var handle string
418 err := row.Scan(&handle)
419 if err != nil {
420 p := investigate(xid)
421 if p == nil {
422 m := re_unurl.FindStringSubmatch(xid)
423 if len(m) > 2 {
424 handle = m[2]
425 } else {
426 handle = xid
427 }
428 } else {
429 handle = p.Handle
430 }
431 _, err = stmtSaveXonker.Exec(xid, handle, "handle")
432 if err != nil {
433 log.Printf("error saving handle: %s", err)
434 }
435 }
436 return handle
437}
438
439var handleprelock sync.Mutex
440
441func prehandle(xid string) {
442 handleprelock.Lock()
443 defer handleprelock.Unlock()
444 handles(xid)
445}
446
447func prepend(s string, x []string) []string {
448 return append([]string{s}, x...)
449}
450
451// pleroma leaks followers addressed posts to followers
452func butnottooloud(aud []string) {
453 for i, a := range aud {
454 if strings.HasSuffix(a, "/followers") {
455 aud[i] = ""
456 }
457 }
458}
459
460func keepitquiet(aud []string) bool {
461 for _, a := range aud {
462 if a == thewholeworld {
463 return false
464 }
465 }
466 return true
467}
468
469func firstclass(honk *Honk) bool {
470 return honk.Audience[0] == thewholeworld
471}
472
473func oneofakind(a []string) []string {
474 var x []string
475 for n, s := range a {
476 if s != "" {
477 x = append(x, s)
478 for i := n + 1; i < len(a); i++ {
479 if a[i] == s {
480 a[i] = ""
481 }
482 }
483 }
484 }
485 return x
486}
487
488var ziggies = make(map[string]*rsa.PrivateKey)
489var zaggies = make(map[string]*rsa.PublicKey)
490var ziggylock sync.Mutex
491
492func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
493 ziggylock.Lock()
494 key = ziggies[username]
495 ziggylock.Unlock()
496 if key == nil {
497 db := opendatabase()
498 row := db.QueryRow("select seckey from users where username = ?", username)
499 var data string
500 row.Scan(&data)
501 var err error
502 key, _, err = httpsig.DecodeKey(data)
503 if err != nil {
504 log.Printf("error decoding %s seckey: %s", username, err)
505 return
506 }
507 ziggylock.Lock()
508 ziggies[username] = key
509 ziggylock.Unlock()
510 }
511 keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
512 return
513}
514
515func zaggy(keyname string) (key *rsa.PublicKey) {
516 ziggylock.Lock()
517 key = zaggies[keyname]
518 ziggylock.Unlock()
519 if key != nil {
520 return
521 }
522 row := stmtGetXonker.QueryRow(keyname, "pubkey")
523 var data string
524 err := row.Scan(&data)
525 if err != nil {
526 log.Printf("hitting the webs for missing pubkey: %s", keyname)
527 j, err := GetJunk(keyname)
528 if err != nil {
529 log.Printf("error getting %s pubkey: %s", keyname, err)
530 return
531 }
532 keyobj, ok := j.GetMap("publicKey")
533 if ok {
534 j = keyobj
535 }
536 data, ok = j.GetString("publicKeyPem")
537 if !ok {
538 log.Printf("error finding %s pubkey", keyname)
539 return
540 }
541 _, ok = j.GetString("owner")
542 if !ok {
543 log.Printf("error finding %s pubkey owner", keyname)
544 return
545 }
546 _, key, err = httpsig.DecodeKey(data)
547 if err != nil {
548 log.Printf("error decoding %s pubkey: %s", keyname, err)
549 return
550 }
551 _, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
552 if err != nil {
553 log.Printf("error saving key: %s", err)
554 }
555 } else {
556 _, key, err = httpsig.DecodeKey(data)
557 if err != nil {
558 log.Printf("error decoding %s pubkey: %s", keyname, err)
559 return
560 }
561 }
562 ziggylock.Lock()
563 zaggies[keyname] = key
564 ziggylock.Unlock()
565 return
566}
567
568func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
569 _, err := stmtDeleteXonker.Exec(keyname, "pubkey")
570 if err != nil {
571 log.Printf("error deleting key: %s", err)
572 }
573 ziggylock.Lock()
574 delete(zaggies, keyname)
575 ziggylock.Unlock()
576 return httpsig.VerifyRequest(r, payload, zaggy)
577}
578
579var thumbbiters map[int64]map[string]bool
580var zordses map[int64][]*regexp.Regexp
581var zilences map[int64][]*regexp.Regexp
582var thumblock sync.Mutex
583
584func bitethethumbs() {
585 rows, err := stmtThumbBiters.Query()
586 if err != nil {
587 log.Printf("error getting thumbbiters: %s", err)
588 return
589 }
590 defer rows.Close()
591
592 thumblock.Lock()
593 defer thumblock.Unlock()
594 thumbbiters = make(map[int64]map[string]bool)
595 zordses = make(map[int64][]*regexp.Regexp)
596 zilences = make(map[int64][]*regexp.Regexp)
597 for rows.Next() {
598 var userid int64
599 var name, wherefore string
600 err = rows.Scan(&userid, &name, &wherefore)
601 if err != nil {
602 log.Printf("error scanning zonker: %s", err)
603 continue
604 }
605 if wherefore == "zord" || wherefore == "zilence" {
606 zord := "\\b(?i:" + name + ")\\b"
607 re, err := regexp.Compile(zord)
608 if err != nil {
609 log.Printf("error compiling zord: %s", err)
610 } else {
611 if wherefore == "zord" {
612 zordses[userid] = append(zordses[userid], re)
613 } else {
614 zilences[userid] = append(zilences[userid], re)
615 }
616 }
617 continue
618 }
619 m := thumbbiters[userid]
620 if m == nil {
621 m = make(map[string]bool)
622 thumbbiters[userid] = m
623 }
624 m[name] = true
625 }
626}
627
628func getzords(userid int64) []*regexp.Regexp {
629 thumblock.Lock()
630 defer thumblock.Unlock()
631 return zordses[userid]
632}
633
634func getzilences(userid int64) []*regexp.Regexp {
635 thumblock.Lock()
636 defer thumblock.Unlock()
637 return zilences[userid]
638}
639
640func thoudostbitethythumb(userid int64, who []string, objid string) bool {
641 thumblock.Lock()
642 biters := thumbbiters[userid]
643 thumblock.Unlock()
644 objwhere := originate(objid)
645 if objwhere != "" && biters[objwhere] {
646 return true
647 }
648 for _, w := range who {
649 if biters[w] {
650 return true
651 }
652 where := originate(w)
653 if where != "" {
654 if biters[where] {
655 return true
656 }
657 }
658 }
659 return false
660}
661
662func keymatch(keyname string, actor string) string {
663 hash := strings.IndexByte(keyname, '#')
664 if hash == -1 {
665 hash = len(keyname)
666 }
667 owner := keyname[0:hash]
668 if owner == actor {
669 return originate(actor)
670 }
671 return ""
672}