all repos — honk @ c87769f82efe12be91a75cef02a3a9ab36947ec3

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			}
 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:^&gt; (.*)\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, "&#39;", "'", -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 oneofakind(a []string) []string {
452	var x []string
453	for n, s := range a {
454		if s != "" {
455			x = append(x, s)
456			for i := n + 1; i < len(a); i++ {
457				if a[i] == s {
458					a[i] = ""
459				}
460			}
461		}
462	}
463	return x
464}
465
466var ziggies = make(map[string]*rsa.PrivateKey)
467var zaggies = make(map[string]*rsa.PublicKey)
468var ziggylock sync.Mutex
469
470func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
471	ziggylock.Lock()
472	key = ziggies[username]
473	ziggylock.Unlock()
474	if key == nil {
475		db := opendatabase()
476		row := db.QueryRow("select seckey from users where username = ?", username)
477		var data string
478		row.Scan(&data)
479		var err error
480		key, _, err = httpsig.DecodeKey(data)
481		if err != nil {
482			log.Printf("error decoding %s seckey: %s", username, err)
483			return
484		}
485		ziggylock.Lock()
486		ziggies[username] = key
487		ziggylock.Unlock()
488	}
489	keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
490	return
491}
492
493func zaggy(keyname string) (key *rsa.PublicKey) {
494	ziggylock.Lock()
495	key = zaggies[keyname]
496	ziggylock.Unlock()
497	if key != nil {
498		return
499	}
500	row := stmtGetXonker.QueryRow(keyname, "pubkey")
501	var data string
502	err := row.Scan(&data)
503	if err != nil {
504		log.Printf("hitting the webs for missing pubkey: %s", keyname)
505		j, err := GetJunk(keyname)
506		if err != nil {
507			log.Printf("error getting %s pubkey: %s", keyname, err)
508			return
509		}
510		keyobj, ok := j.GetMap("publicKey")
511		if ok {
512			j = keyobj
513		}
514		data, ok = j.GetString("publicKeyPem")
515		if !ok {
516			log.Printf("error finding %s pubkey", keyname)
517			return
518		}
519		_, ok = j.GetString("owner")
520		if !ok {
521			log.Printf("error finding %s pubkey owner", keyname)
522			return
523		}
524		_, key, err = httpsig.DecodeKey(data)
525		if err != nil {
526			log.Printf("error decoding %s pubkey: %s", keyname, err)
527			return
528		}
529		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
530		if err != nil {
531			log.Printf("error saving key: %s", err)
532		}
533	} else {
534		_, key, err = httpsig.DecodeKey(data)
535		if err != nil {
536			log.Printf("error decoding %s pubkey: %s", keyname, err)
537			return
538		}
539	}
540	ziggylock.Lock()
541	zaggies[keyname] = key
542	ziggylock.Unlock()
543	return
544}
545
546func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
547	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
548	if err != nil {
549		log.Printf("error deleting key: %s", err)
550	}
551	ziggylock.Lock()
552	delete(zaggies, keyname)
553	ziggylock.Unlock()
554	return httpsig.VerifyRequest(r, payload, zaggy)
555}
556
557var thumbbiters map[int64]map[string]bool
558var zordses map[int64][]*regexp.Regexp
559var zilences map[int64][]*regexp.Regexp
560var thumblock sync.Mutex
561
562func bitethethumbs() {
563	rows, err := stmtThumbBiters.Query()
564	if err != nil {
565		log.Printf("error getting thumbbiters: %s", err)
566		return
567	}
568	defer rows.Close()
569
570	thumblock.Lock()
571	defer thumblock.Unlock()
572	thumbbiters = make(map[int64]map[string]bool)
573	zordses = make(map[int64][]*regexp.Regexp)
574	zilences = make(map[int64][]*regexp.Regexp)
575	for rows.Next() {
576		var userid int64
577		var name, wherefore string
578		err = rows.Scan(&userid, &name, &wherefore)
579		if err != nil {
580			log.Printf("error scanning zonker: %s", err)
581			continue
582		}
583		if wherefore == "zord" || wherefore == "zilence" {
584			zord := "\\b(?i:" + name + ")\\b"
585			re, err := regexp.Compile(zord)
586			if err != nil {
587				log.Printf("error compiling zord: %s", err)
588			} else {
589				if wherefore == "zord" {
590					zordses[userid] = append(zordses[userid], re)
591				} else {
592					zilences[userid] = append(zilences[userid], re)
593				}
594			}
595			continue
596		}
597		m := thumbbiters[userid]
598		if m == nil {
599			m = make(map[string]bool)
600			thumbbiters[userid] = m
601		}
602		m[name] = true
603	}
604}
605
606func getzords(userid int64) []*regexp.Regexp {
607	thumblock.Lock()
608	defer thumblock.Unlock()
609	return zordses[userid]
610}
611
612func getzilences(userid int64) []*regexp.Regexp {
613	thumblock.Lock()
614	defer thumblock.Unlock()
615	return zilences[userid]
616}
617
618func thoudostbitethythumb(userid int64, who []string, objid string) bool {
619	thumblock.Lock()
620	biters := thumbbiters[userid]
621	thumblock.Unlock()
622	objwhere := originate(objid)
623	if objwhere != "" && biters[objwhere] {
624		return true
625	}
626	for _, w := range who {
627		if biters[w] {
628			return true
629		}
630		where := originate(w)
631		if where != "" {
632			if biters[where] {
633				return true
634			}
635		}
636	}
637	return false
638}
639
640func keymatch(keyname string, actor string) string {
641	hash := strings.IndexByte(keyname, '#')
642	if hash == -1 {
643		hash = len(keyname)
644	}
645	owner := keyname[0:hash]
646	if owner == actor {
647		return originate(actor)
648	}
649	return ""
650}