all repos — honk @ cf9b3f76bfaed7e0ccf32fa573526dda19f2db9f

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	"regexp"
 27	"strings"
 28	"sync"
 29)
 30
 31func reverbolate(honks []*Honk) {
 32	for _, h := range honks {
 33		h.What += "ed"
 34		if h.Honker == "" {
 35			h.Honker = "https://" + serverName + "/u/" + h.Username
 36			if strings.IndexByte(h.XID, '/') == -1 {
 37				h.URL = h.Honker + "/h/" + h.XID
 38			} else {
 39				h.URL = h.XID
 40			}
 41			h.Noise = mentionize(h.Noise)
 42		} else {
 43			idx := strings.LastIndexByte(h.Honker, '/')
 44			if idx != -1 {
 45				h.Username = honkerhandle(h.Honker)
 46			} else {
 47				h.Username = h.Honker
 48			}
 49			if h.URL == "" {
 50				h.URL = h.XID
 51			}
 52		}
 53		h.Privacy = "limited"
 54		for _, a := range h.Audience {
 55			if a == thewholeworld {
 56				h.Privacy = ""
 57				break
 58			}
 59		}
 60		zap := make(map[*Donk]bool)
 61		h.Noise = unpucker(h.Noise)
 62		h.HTML = cleanstring(h.Noise)
 63		emuxifier := func(e string) string {
 64			for _, d := range h.Donks {
 65				if d.Name == e {
 66					zap[d] = true
 67					return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
 68				}
 69			}
 70			return e
 71		}
 72		h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
 73		j := 0
 74		for i := 0; i < len(h.Donks); i++ {
 75			if !zap[h.Donks[i]] {
 76				h.Donks[j] = h.Donks[i]
 77				j++
 78			}
 79		}
 80		h.Donks = h.Donks[:j]
 81	}
 82}
 83
 84func xfiltrate() string {
 85	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
 86	for {
 87		var b [18]byte
 88		rand.Read(b[:])
 89		for i, c := range b {
 90			b[i] = letters[c&63]
 91		}
 92		s := string(b[:])
 93		return s
 94	}
 95}
 96
 97type Mention struct {
 98	who   string
 99	where string
100}
101
102var re_mentions = regexp.MustCompile(`@[[:alnum:]]+@[[:alnum:].]+`)
103var re_urltions = regexp.MustCompile(`@https://\S+`)
104
105func grapevine(s string) []string {
106	var mentions []string
107	m := re_mentions.FindAllString(s, -1)
108	for i := range m {
109		where := gofish(m[i])
110		if where != "" {
111			mentions = append(mentions, where)
112		}
113	}
114	m = re_urltions.FindAllString(s, -1)
115	for i := range m {
116		mentions = append(mentions, m[i][1:])
117	}
118	return mentions
119}
120
121func bunchofgrapes(s string) []Mention {
122	m := re_mentions.FindAllString(s, -1)
123	var mentions []Mention
124	for i := range m {
125		where := gofish(m[i])
126		if where != "" {
127			mentions = append(mentions, Mention{who: m[i], where: where})
128		}
129	}
130	m = re_urltions.FindAllString(s, -1)
131	for i := range m {
132		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
133	}
134	return mentions
135}
136
137type Emu struct {
138	ID   string
139	Name string
140}
141
142var re_link = regexp.MustCompile(`@?https?://[^\s"]+[\w/)]`)
143var re_emus = regexp.MustCompile(`:[[:alnum:]_]+:`)
144
145func herdofemus(noise string) []Emu {
146	m := re_emus.FindAllString(noise, -1)
147	m = oneofakind(m)
148	var emus []Emu
149	for _, e := range m {
150		fname := e[1 : len(e)-1]
151		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
152		emus = append(emus, Emu{ID: url, Name: e})
153	}
154	return emus
155}
156
157var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?']+)\*\*($|\W)`)
158var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?']+)\*($|\W)`)
159
160func markitzero(s string) string {
161	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
162	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
163	return s
164}
165
166func obfusbreak(s string) string {
167	s = strings.TrimSpace(s)
168	s = strings.Replace(s, "\r", "", -1)
169	s = html.EscapeString(s)
170	// dammit go
171	s = strings.Replace(s, "&#39;", "'", -1)
172	linkfn := func(url string) string {
173		if url[0] == '@' {
174			return url
175		}
176		addparen := false
177		adddot := false
178		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
179			url = url[:len(url)-1]
180			addparen = true
181		}
182		if strings.HasSuffix(url, ".") {
183			url = url[:len(url)-1]
184			adddot = true
185		}
186		url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
187		if adddot {
188			url += "."
189		}
190		if addparen {
191			url += ")"
192		}
193		return url
194	}
195	s = re_link.ReplaceAllStringFunc(s, linkfn)
196
197	s = markitzero(s)
198
199	s = strings.Replace(s, "\n", "<br>", -1)
200	return s
201}
202
203func mentionize(s string) string {
204	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
205		where := gofish(m)
206		if where == "" {
207			return m
208		}
209		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
210		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
211			html.EscapeString(where), html.EscapeString(who))
212	})
213	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
214		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
215			html.EscapeString(m[1:]), html.EscapeString(m))
216	})
217	return s
218}
219
220var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
221
222func honkerhandle(h string) string {
223	m := re_unurl.FindStringSubmatch(h)
224	if len(m) > 2 {
225		return fmt.Sprintf("%s@%s", m[2], m[1])
226	}
227	return h
228}
229
230func prepend(s string, x []string) []string {
231	return append([]string{s}, x...)
232}
233
234// pleroma leaks followers addressed posts to followers
235func butnottooloud(aud []string) {
236	for i, a := range aud {
237		if strings.HasSuffix(a, "/followers") {
238			aud[i] = ""
239		}
240	}
241}
242
243func oneofakind(a []string) []string {
244	var x []string
245	for n, s := range a {
246		if s != "" {
247			x = append(x, s)
248			for i := n + 1; i < len(a); i++ {
249				if a[i] == s {
250					a[i] = ""
251				}
252			}
253		}
254	}
255	return x
256}
257
258var ziggies = make(map[string]*rsa.PrivateKey)
259var zaggies = make(map[string]*rsa.PublicKey)
260var ziggylock sync.Mutex
261
262func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
263	ziggylock.Lock()
264	key = ziggies[username]
265	ziggylock.Unlock()
266	if key == nil {
267		db := opendatabase()
268		row := db.QueryRow("select seckey from users where username = ?", username)
269		var data string
270		row.Scan(&data)
271		var err error
272		key, _, err = pez(data)
273		if err != nil {
274			log.Printf("error decoding %s seckey: %s", username, err)
275			return
276		}
277		ziggylock.Lock()
278		ziggies[username] = key
279		ziggylock.Unlock()
280	}
281	keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
282	return
283}
284
285func zaggy(keyname string) (key *rsa.PublicKey) {
286	ziggylock.Lock()
287	key = zaggies[keyname]
288	ziggylock.Unlock()
289	if key != nil {
290		return
291	}
292	db := opendatabase()
293	row := db.QueryRow("select pubkey from xonkers where xid = ?", keyname)
294	var data string
295	err := row.Scan(&data)
296	if err != nil {
297		log.Printf("hitting the webs for missing pubkey: %s", keyname)
298		j, err := GetJunk(keyname)
299		if err != nil {
300			log.Printf("error getting %s pubkey: %s", keyname, err)
301			return
302		}
303		var ok bool
304		data, ok = jsonfindstring(j, []string{"publicKey", "publicKeyPem"})
305		if !ok {
306			log.Printf("error finding %s pubkey", keyname)
307			return
308		}
309		_, ok = jsonfindstring(j, []string{"publicKey", "owner"})
310		if !ok {
311			log.Printf("error finding %s pubkey owner", keyname)
312			return
313		}
314		_, key, err = pez(data)
315		if err != nil {
316			log.Printf("error decoding %s pubkey: %s", keyname, err)
317			return
318		}
319		_, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
320		if err != nil {
321			log.Printf("error saving key: %s", err)
322		}
323	} else {
324		_, key, err = pez(data)
325		if err != nil {
326			log.Printf("error decoding %s pubkey: %s", keyname, err)
327			return
328		}
329	}
330	ziggylock.Lock()
331	zaggies[keyname] = key
332	ziggylock.Unlock()
333	return
334}
335
336func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
337	db := opendatabase()
338	_, err := db.Exec("delete from xonkers where xid = ?", keyname)
339	if err != nil {
340		log.Printf("error deleting key: %s", err)
341	}
342	ziggylock.Lock()
343	delete(zaggies, keyname)
344	ziggylock.Unlock()
345	return zag(r, payload)
346}
347
348var thumbbiters map[int64]map[string]bool
349var thumblock sync.Mutex
350
351func bitethethumbs() {
352	rows, err := stmtThumbBiters.Query()
353	if err != nil {
354		log.Printf("error getting thumbbiters: %s", err)
355		return
356	}
357	defer rows.Close()
358	thumblock.Lock()
359	defer thumblock.Unlock()
360	thumbbiters = make(map[int64]map[string]bool)
361	for rows.Next() {
362		var userid int64
363		var name, wherefore string
364		err = rows.Scan(&userid, &name, &wherefore)
365		if err != nil {
366			log.Printf("error scanning zonker: %s", err)
367			continue
368		}
369		m := thumbbiters[userid]
370		if m == nil {
371			m = make(map[string]bool)
372			thumbbiters[userid] = m
373		}
374		m[name] = true
375	}
376}
377
378func thoudostbitethythumb(userid int64, who []string, objid string) bool {
379	thumblock.Lock()
380	biters := thumbbiters[userid]
381	thumblock.Unlock()
382	for _, w := range who {
383		if biters[w] {
384			return true
385		}
386		m := re_unurl.FindStringSubmatch(w)
387		if len(m) > 2 {
388			where := m[1]
389			if biters[where] {
390				return true
391			}
392		}
393	}
394	return false
395}
396
397func keymatch(keyname string, actor string, what string, userid int64) bool {
398	hash := strings.IndexByte(keyname, '#')
399	if hash == -1 {
400		hash = len(keyname)
401	}
402	owner := keyname[0:hash]
403	if owner == actor {
404		return true
405	}
406	if what != "Create" {
407		return false
408	}
409	row := stmtHasHonker.QueryRow(owner, userid)
410	var id int64
411	err := row.Scan(&id)
412	if err == nil {
413		log.Printf("allowing resigned content by %s", keyname)
414		return true
415	}
416	return false
417}