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