all repos — honk @ b93adc318d2266c3e43dbf776142b20d1eae5b18

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