all repos — honk @ e966ff86b302200bc68754ca53fc119c3d48ed9a

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