all repos — honk @ c6cd59310deb31536f43e1faf43072b3f6832940

my fork of honk

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