web.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 "bytes"
20 "database/sql"
21 "fmt"
22 "html/template"
23 "io"
24 notrand "math/rand"
25 "net/http"
26 "net/url"
27 "os"
28 "os/signal"
29 "regexp"
30 "sort"
31 "strconv"
32 "strings"
33 "syscall"
34 "time"
35 "unicode/utf8"
36
37 "github.com/gorilla/mux"
38 "humungus.tedunangst.com/r/webs/cache"
39 "humungus.tedunangst.com/r/webs/httpsig"
40 "humungus.tedunangst.com/r/webs/junk"
41 "humungus.tedunangst.com/r/webs/login"
42 "humungus.tedunangst.com/r/webs/rss"
43 "humungus.tedunangst.com/r/webs/templates"
44)
45
46var readviews *templates.Template
47
48var userSep = "u"
49var honkSep = "h"
50
51var develMode = false
52
53var allemus []Emu
54
55func getuserstyle(u *login.UserInfo) template.HTMLAttr {
56 if u == nil {
57 return ""
58 }
59 user, _ := butwhatabout(u.Username)
60 class := template.HTMLAttr("")
61 if user.Options.SkinnyCSS {
62 class += `class="skinny"`
63 }
64 return class
65}
66
67func getmaplink(u *login.UserInfo) string {
68 if u == nil {
69 return "osm"
70 }
71 user, _ := butwhatabout(u.Username)
72 ml := user.Options.MapLink
73 if ml == "" {
74 ml = "osm"
75 }
76 return ml
77}
78
79func getInfo(r *http.Request) map[string]interface{} {
80 templinfo := make(map[string]interface{})
81 templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
82 templinfo["LocalStyleParam"] = getassetparam(dataDir + "/views/local.css")
83 templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
84 templinfo["LocalJSParam"] = getassetparam(dataDir + "/views/local.js")
85 templinfo["MiscJSParam"] = getassetparam(dataDir + "/views/misc.js")
86 templinfo["ServerName"] = serverName
87 templinfo["IconName"] = iconName
88 templinfo["UserSep"] = userSep
89 if u := login.GetUserInfo(r); u != nil {
90 templinfo["UserInfo"], _ = butwhatabout(u.Username)
91 templinfo["UserStyle"] = getuserstyle(u)
92 var combos []string
93 combocache.Get(u.UserID, &combos)
94 templinfo["Combos"] = combos
95 }
96 return templinfo
97}
98
99func homepage(w http.ResponseWriter, r *http.Request) {
100 templinfo := getInfo(r)
101 u := login.GetUserInfo(r)
102 var honks []*Honk
103 var userid int64 = -1
104
105 templinfo["ServerMessage"] = serverMsg
106 if u == nil || r.URL.Path == "/front" {
107 switch r.URL.Path {
108 case "/events":
109 honks = geteventhonks(userid)
110 templinfo["ServerMessage"] = "some recent and upcoming events"
111 default:
112 templinfo["ShowRSS"] = true
113 honks = getpublichonks()
114 }
115 } else {
116 userid = u.UserID
117 switch r.URL.Path {
118 case "/atme":
119 templinfo["ServerMessage"] = "at me!"
120 templinfo["PageName"] = "atme"
121 honks = gethonksforme(userid, 0)
122 honks = osmosis(honks, userid, false)
123 menewnone(userid)
124 templinfo["UserInfo"], _ = butwhatabout(u.Username)
125 case "/longago":
126 templinfo["ServerMessage"] = "long ago and far away!"
127 templinfo["PageName"] = "longago"
128 honks = gethonksfromlongago(userid, 0)
129 honks = osmosis(honks, userid, false)
130 case "/events":
131 templinfo["ServerMessage"] = "some recent and upcoming events"
132 templinfo["PageName"] = "events"
133 honks = geteventhonks(userid)
134 honks = osmosis(honks, userid, true)
135 case "/first":
136 templinfo["PageName"] = "first"
137 honks = gethonksforuserfirstclass(userid, 0)
138 honks = osmosis(honks, userid, true)
139 case "/saved":
140 templinfo["ServerMessage"] = "saved honks"
141 templinfo["PageName"] = "saved"
142 honks = getsavedhonks(userid, 0)
143 default:
144 templinfo["PageName"] = "home"
145 honks = gethonksforuser(userid, 0)
146 honks = osmosis(honks, userid, true)
147 }
148 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
149 }
150
151 honkpage(w, u, honks, templinfo)
152}
153
154func showemus(w http.ResponseWriter, r *http.Request) {
155 templinfo := getInfo(r)
156 templinfo["Emus"] = allemus
157 err := readviews.Execute(w, "emus.html", templinfo)
158 if err != nil {
159 elog.Print(err)
160 }
161}
162
163func showfunzone(w http.ResponseWriter, r *http.Request) {
164 var emunames, memenames []string
165 emuext := make(map[string]string)
166 dir, err := os.Open(dataDir + "/emus")
167 if err == nil {
168 emunames, _ = dir.Readdirnames(0)
169 dir.Close()
170 }
171 for i, e := range emunames {
172 if len(e) > 4 {
173 emunames[i] = e[:len(e)-4]
174 emuext[emunames[i]] = e[len(e)-4:]
175 }
176 }
177 dir, err = os.Open(dataDir + "/memes")
178 if err == nil {
179 memenames, _ = dir.Readdirnames(0)
180 dir.Close()
181 }
182 sort.Strings(emunames)
183 sort.Strings(memenames)
184 templinfo := getInfo(r)
185 templinfo["Emus"] = emunames
186 templinfo["Emuext"] = emuext
187 templinfo["Memes"] = memenames
188 err = readviews.Execute(w, "funzone.html", templinfo)
189 if err != nil {
190 elog.Print(err)
191 }
192}
193
194func showrss(w http.ResponseWriter, r *http.Request) {
195 name := mux.Vars(r)["name"]
196
197 var honks []*Honk
198 if name != "" {
199 honks = gethonksbyuser(name, false, 0)
200 } else {
201 honks = getpublichonks()
202 }
203 reverbolate(-1, honks)
204
205 home := fmt.Sprintf("https://%s/", serverName)
206 base := home
207 if name != "" {
208 home += "u/" + name
209 name += " "
210 }
211 feed := rss.Feed{
212 Title: name + "honk",
213 Link: home,
214 Description: name + "honk rss",
215 Image: &rss.Image{
216 URL: base + "icon.png",
217 Title: name + "honk rss",
218 Link: home,
219 },
220 }
221 var modtime time.Time
222 for _, honk := range honks {
223 if !firstclass(honk) {
224 continue
225 }
226 desc := string(honk.HTML)
227 if t := honk.Time; t != nil {
228 desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
229 if t.Duration != 0 {
230 desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
231 }
232 }
233 if p := honk.Place; p != nil {
234 desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
235 p.Url, p.Name, p.Latitude, p.Longitude))
236 }
237 for _, d := range honk.Donks {
238 desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
239 d.URL, d.Desc))
240 if strings.HasPrefix(d.Media, "image") {
241 desc += string(templates.Sprintf(`<img src="%s">`, d.URL))
242 }
243 }
244
245 feed.Items = append(feed.Items, &rss.Item{
246 Title: fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
247 Description: rss.CData{Data: desc},
248 Link: honk.URL,
249 PubDate: honk.Date.Format(time.RFC1123),
250 Guid: &rss.Guid{IsPermaLink: true, Value: honk.URL},
251 })
252 if honk.Date.After(modtime) {
253 modtime = honk.Date
254 }
255 }
256 if !develMode {
257 w.Header().Set("Cache-Control", "max-age=300")
258 w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
259 }
260
261 err := feed.Write(w)
262 if err != nil {
263 elog.Printf("error writing rss: %s", err)
264 }
265}
266
267func crappola(j junk.Junk) bool {
268 t, _ := j.GetString("type")
269 a, _ := j.GetString("actor")
270 o, _ := j.GetString("object")
271 if t == "Delete" && a == o {
272 dlog.Printf("crappola from %s", a)
273 return true
274 }
275 return false
276}
277
278func ping(user *WhatAbout, who string) {
279 if targ := fullname(who, user.ID); targ != "" {
280 who = targ
281 }
282 if !strings.HasPrefix(who, "https:") {
283 who = gofish(who)
284 }
285 if who == "" {
286 ilog.Printf("nobody to ping!")
287 return
288 }
289 var box *Box
290 ok := boxofboxes.Get(who, &box)
291 if !ok {
292 ilog.Printf("no inbox to ping %s", who)
293 return
294 }
295 ilog.Printf("sending ping to %s", box.In)
296 j := junk.New()
297 j["@context"] = itiswhatitis
298 j["type"] = "Ping"
299 j["id"] = user.URL + "/ping/" + xfiltrate()
300 j["actor"] = user.URL
301 j["to"] = who
302 ki := ziggy(user.ID)
303 if ki == nil {
304 return
305 }
306 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
307 if err != nil {
308 elog.Printf("can't send ping: %s", err)
309 return
310 }
311 ilog.Printf("sent ping to %s: %s", who, j["id"])
312}
313
314func pong(user *WhatAbout, who string, obj string) {
315 var box *Box
316 ok := boxofboxes.Get(who, &box)
317 if !ok {
318 ilog.Printf("no inbox to pong %s", who)
319 return
320 }
321 j := junk.New()
322 j["@context"] = itiswhatitis
323 j["type"] = "Pong"
324 j["id"] = user.URL + "/pong/" + xfiltrate()
325 j["actor"] = user.URL
326 j["to"] = who
327 j["object"] = obj
328 ki := ziggy(user.ID)
329 if ki == nil {
330 return
331 }
332 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
333 if err != nil {
334 elog.Printf("can't send pong: %s", err)
335 return
336 }
337}
338
339func inbox(w http.ResponseWriter, r *http.Request) {
340 name := mux.Vars(r)["name"]
341 user, err := butwhatabout(name)
342 if err != nil {
343 http.NotFound(w, r)
344 return
345 }
346 if stealthmode(user.ID, r) {
347 http.NotFound(w, r)
348 return
349 }
350 var buf bytes.Buffer
351 limiter := io.LimitReader(r.Body, 1*1024*1024)
352 io.Copy(&buf, limiter)
353 payload := buf.Bytes()
354 j, err := junk.FromBytes(payload)
355 if err != nil {
356 ilog.Printf("bad payload: %s", err)
357 ilog.Writer().Write(payload)
358 ilog.Writer().Write([]byte{'\n'})
359 return
360 }
361
362 if crappola(j) {
363 return
364 }
365 what, _ := j.GetString("type")
366 obj, _ := j.GetString("object")
367 if what == "Like" || (what == "EmojiReact" && originate(obj) != serverName) {
368 return
369 }
370 who, _ := j.GetString("actor")
371 if rejectactor(user.ID, who) {
372 return
373 }
374
375 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
376 if err != nil && keyname != "" {
377 savingthrow(keyname)
378 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
379 }
380 if err != nil {
381 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
382 if keyname != "" {
383 ilog.Printf("bad signature from %s", keyname)
384 }
385 http.Error(w, "what did you call me?", http.StatusTeapot)
386 return
387 }
388 origin := keymatch(keyname, who)
389 if origin == "" {
390 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
391 return
392 }
393
394 switch what {
395 case "Ping":
396 id, _ := j.GetString("id")
397 ilog.Printf("ping from %s: %s", who, id)
398 pong(user, who, obj)
399 case "Pong":
400 ilog.Printf("pong from %s: %s", who, obj)
401 case "Follow":
402 if obj != user.URL {
403 ilog.Printf("can't follow %s", obj)
404 return
405 }
406 followme(user, who, who, j)
407 case "Accept":
408 followyou2(user, j)
409 case "Reject":
410 nofollowyou2(user, j)
411 case "Update":
412 obj, ok := j.GetMap("object")
413 if ok {
414 what, _ := obj.GetString("type")
415 switch what {
416 case "Service":
417 fallthrough
418 case "Person":
419 return
420 case "Question":
421 return
422 case "Note":
423 go xonksaver(user, j, origin)
424 return
425 }
426 }
427 ilog.Printf("unknown Update activity")
428 dumpactivity(j)
429 case "Undo":
430 obj, ok := j.GetMap("object")
431 if !ok {
432 folxid, ok := j.GetString("object")
433 if ok && originate(folxid) == origin {
434 unfollowme(user, "", "", j)
435 }
436 return
437 }
438 what, _ := obj.GetString("type")
439 switch what {
440 case "Follow":
441 unfollowme(user, who, who, j)
442 case "Announce":
443 xid, _ := obj.GetString("object")
444 dlog.Printf("undo announce: %s", xid)
445 case "Like":
446 default:
447 ilog.Printf("unknown undo: %s", what)
448 }
449 case "EmojiReact":
450 obj, ok := j.GetString("object")
451 if ok {
452 content, _ := j.GetString("content")
453 addreaction(user, obj, who, content)
454 }
455 default:
456 go xonksaver(user, j, origin)
457 }
458}
459
460func serverinbox(w http.ResponseWriter, r *http.Request) {
461 user := getserveruser()
462 if stealthmode(user.ID, r) {
463 http.NotFound(w, r)
464 return
465 }
466 var buf bytes.Buffer
467 io.Copy(&buf, r.Body)
468 payload := buf.Bytes()
469 j, err := junk.FromBytes(payload)
470 if err != nil {
471 ilog.Printf("bad payload: %s", err)
472 ilog.Writer().Write(payload)
473 ilog.Writer().Write([]byte{'\n'})
474 return
475 }
476 if crappola(j) {
477 return
478 }
479 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
480 if err != nil && keyname != "" {
481 savingthrow(keyname)
482 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
483 }
484 if err != nil {
485 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
486 if keyname != "" {
487 ilog.Printf("bad signature from %s", keyname)
488 }
489 http.Error(w, "what did you call me?", http.StatusTeapot)
490 return
491 }
492 who, _ := j.GetString("actor")
493 origin := keymatch(keyname, who)
494 if origin == "" {
495 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
496 return
497 }
498 if rejectactor(user.ID, who) {
499 return
500 }
501 re_ont := regexp.MustCompile("https://" + serverName + "/o/([\\pL[:digit:]]+)")
502 what, _ := j.GetString("type")
503 dlog.Printf("server got a %s", what)
504 switch what {
505 case "Follow":
506 obj, _ := j.GetString("object")
507 if obj == user.URL {
508 ilog.Printf("can't follow the server!")
509 return
510 }
511 m := re_ont.FindStringSubmatch(obj)
512 if len(m) != 2 {
513 ilog.Printf("not sure how to handle this")
514 return
515 }
516 ont := "#" + m[1]
517
518 followme(user, who, ont, j)
519 case "Undo":
520 obj, ok := j.GetMap("object")
521 if !ok {
522 ilog.Printf("unknown undo no object")
523 return
524 }
525 what, _ := obj.GetString("type")
526 if what != "Follow" {
527 ilog.Printf("unknown undo: %s", what)
528 return
529 }
530 targ, _ := obj.GetString("object")
531 m := re_ont.FindStringSubmatch(targ)
532 if len(m) != 2 {
533 ilog.Printf("not sure how to handle this")
534 return
535 }
536 ont := "#" + m[1]
537 unfollowme(user, who, ont, j)
538 default:
539 ilog.Printf("unhandled server activity: %s", what)
540 dumpactivity(j)
541 }
542}
543
544func serveractor(w http.ResponseWriter, r *http.Request) {
545 user := getserveruser()
546 if stealthmode(user.ID, r) {
547 http.NotFound(w, r)
548 return
549 }
550 j := junkuser(user)
551 j.Write(w)
552}
553
554func ximport(w http.ResponseWriter, r *http.Request) {
555 u := login.GetUserInfo(r)
556 xid := strings.TrimSpace(r.FormValue("xid"))
557 xonk := getxonk(u.UserID, xid)
558 if xonk == nil {
559 p, _ := investigate(xid)
560 if p != nil {
561 xid = p.XID
562 }
563 j, err := GetJunk(u.UserID, xid)
564 if err != nil {
565 http.Error(w, "error getting external object", http.StatusInternalServerError)
566 ilog.Printf("error getting external object: %s", err)
567 return
568 }
569 allinjest(originate(xid), j)
570 dlog.Printf("importing %s", xid)
571 user, _ := butwhatabout(u.Username)
572
573 info, _ := somethingabout(j)
574 if info == nil {
575 xonk = xonksaver(user, j, originate(xid))
576 } else if info.What == SomeActor {
577 outbox, _ := j.GetString("outbox")
578 gimmexonks(user, outbox)
579 http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
580 return
581 } else if info.What == SomeCollection {
582 gimmexonks(user, xid)
583 http.Redirect(w, r, "/xzone", http.StatusSeeOther)
584 return
585 }
586 }
587 convoy := ""
588 if xonk != nil {
589 convoy = xonk.Convoy
590 }
591 http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
592}
593
594func xzone(w http.ResponseWriter, r *http.Request) {
595 u := login.GetUserInfo(r)
596 rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
597 if err != nil {
598 elog.Printf("query err: %s", err)
599 return
600 }
601 defer rows.Close()
602 var honkers []Honker
603 for rows.Next() {
604 var xid string
605 rows.Scan(&xid)
606 honkers = append(honkers, Honker{XID: xid})
607 }
608 rows.Close()
609 for i, _ := range honkers {
610 _, honkers[i].Handle = handles(honkers[i].XID)
611 }
612 templinfo := getInfo(r)
613 templinfo["XCSRF"] = login.GetCSRF("ximport", r)
614 templinfo["Honkers"] = honkers
615 err = readviews.Execute(w, "xzone.html", templinfo)
616 if err != nil {
617 elog.Print(err)
618 }
619}
620
621var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
622 user, err := butwhatabout(name)
623 if err != nil {
624 return nil, false
625 }
626 honks := gethonksbyuser(name, false, 0)
627 if len(honks) > 20 {
628 honks = honks[0:20]
629 }
630
631 var jonks []junk.Junk
632 for _, h := range honks {
633 j, _ := jonkjonk(user, h)
634 jonks = append(jonks, j)
635 }
636
637 j := junk.New()
638 j["@context"] = itiswhatitis
639 j["id"] = user.URL + "/outbox"
640 j["attributedTo"] = user.URL
641 j["type"] = "OrderedCollection"
642 j["totalItems"] = len(jonks)
643 j["orderedItems"] = jonks
644
645 return j.ToBytes(), true
646}, Duration: 1 * time.Minute})
647
648func outbox(w http.ResponseWriter, r *http.Request) {
649 name := mux.Vars(r)["name"]
650 user, err := butwhatabout(name)
651 if err != nil {
652 http.NotFound(w, r)
653 return
654 }
655 if stealthmode(user.ID, r) {
656 http.NotFound(w, r)
657 return
658 }
659 var j []byte
660 ok := oldoutbox.Get(name, &j)
661 if ok {
662 w.Header().Set("Content-Type", theonetruename)
663 w.Write(j)
664 } else {
665 http.NotFound(w, r)
666 }
667}
668
669var oldempties = cache.New(cache.Options{Filler: func(url string) ([]byte, bool) {
670 colname := "/followers"
671 if strings.HasSuffix(url, "/following") {
672 colname = "/following"
673 }
674 user := fmt.Sprintf("https://%s%s", serverName, url[:len(url)-10])
675 j := junk.New()
676 j["@context"] = itiswhatitis
677 j["id"] = user + colname
678 j["attributedTo"] = user
679 j["type"] = "OrderedCollection"
680 j["totalItems"] = 0
681 j["orderedItems"] = []junk.Junk{}
682
683 return j.ToBytes(), true
684}})
685
686func emptiness(w http.ResponseWriter, r *http.Request) {
687 name := mux.Vars(r)["name"]
688 user, err := butwhatabout(name)
689 if err != nil {
690 http.NotFound(w, r)
691 return
692 }
693 if stealthmode(user.ID, r) {
694 http.NotFound(w, r)
695 return
696 }
697 var j []byte
698 ok := oldempties.Get(r.URL.Path, &j)
699 if ok {
700 w.Header().Set("Content-Type", theonetruename)
701 w.Write(j)
702 } else {
703 http.NotFound(w, r)
704 }
705}
706
707func showuser(w http.ResponseWriter, r *http.Request) {
708 name := mux.Vars(r)["name"]
709 user, err := butwhatabout(name)
710 if err != nil {
711 ilog.Printf("user not found %s: %s", name, err)
712 http.NotFound(w, r)
713 return
714 }
715 if stealthmode(user.ID, r) {
716 http.NotFound(w, r)
717 return
718 }
719 if friendorfoe(r.Header.Get("Accept")) {
720 j, ok := asjonker(name)
721 if ok {
722 w.Header().Set("Content-Type", theonetruename)
723 w.Write(j)
724 } else {
725 http.NotFound(w, r)
726 }
727 return
728 }
729 u := login.GetUserInfo(r)
730 honks := gethonksbyuser(name, u != nil && u.Username == name, 0)
731 templinfo := getInfo(r)
732 templinfo["PageName"] = "user"
733 templinfo["PageArg"] = name
734 templinfo["Name"] = user.Name
735 templinfo["WhatAbout"] = user.HTAbout
736 templinfo["ServerMessage"] = ""
737 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
738 honkpage(w, u, honks, templinfo)
739}
740
741func showhonker(w http.ResponseWriter, r *http.Request) {
742 u := login.GetUserInfo(r)
743 name := mux.Vars(r)["name"]
744 var honks []*Honk
745 if name == "" {
746 name = r.FormValue("xid")
747 honks = gethonksbyxonker(u.UserID, name, 0)
748 } else {
749 honks = gethonksbyhonker(u.UserID, name, 0)
750 }
751 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
752<input type="hidden" name="CSRF" value="%s">
753<input type="hidden" name="url" value="%s">
754<button tabindex=1 name="add honker" value="add honker">add honker</button>
755</form>`, login.GetCSRF("submithonker", r), name)
756 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
757 templinfo := getInfo(r)
758 templinfo["PageName"] = "honker"
759 templinfo["PageArg"] = name
760 templinfo["ServerMessage"] = msg
761 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
762 honkpage(w, u, honks, templinfo)
763}
764
765func showcombo(w http.ResponseWriter, r *http.Request) {
766 name := mux.Vars(r)["name"]
767 u := login.GetUserInfo(r)
768 honks := gethonksbycombo(u.UserID, name, 0)
769 honks = osmosis(honks, u.UserID, true)
770 templinfo := getInfo(r)
771 templinfo["PageName"] = "combo"
772 templinfo["PageArg"] = name
773 templinfo["ServerMessage"] = "honks by combo: " + name
774 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
775 honkpage(w, u, honks, templinfo)
776}
777func showconvoy(w http.ResponseWriter, r *http.Request) {
778 c := r.FormValue("c")
779 u := login.GetUserInfo(r)
780 honks := gethonksbyconvoy(u.UserID, c, 0)
781 templinfo := getInfo(r)
782 if len(honks) > 0 {
783 templinfo["TopHID"] = honks[0].ID
784 }
785 honks = osmosis(honks, u.UserID, false)
786 reversehonks(honks)
787 templinfo["PageName"] = "convoy"
788 templinfo["PageArg"] = c
789 templinfo["ServerMessage"] = "honks in convoy: " + c
790 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
791 honkpage(w, u, honks, templinfo)
792}
793func showsearch(w http.ResponseWriter, r *http.Request) {
794 q := r.FormValue("q")
795 u := login.GetUserInfo(r)
796 honks := gethonksbysearch(u.UserID, q, 0)
797 templinfo := getInfo(r)
798 templinfo["PageName"] = "search"
799 templinfo["PageArg"] = q
800 templinfo["ServerMessage"] = "honks for search: " + q
801 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
802 honkpage(w, u, honks, templinfo)
803}
804func showontology(w http.ResponseWriter, r *http.Request) {
805 name := mux.Vars(r)["name"]
806 u := login.GetUserInfo(r)
807 var userid int64 = -1
808 if u != nil {
809 userid = u.UserID
810 }
811 honks := gethonksbyontology(userid, "#"+name, 0)
812 if friendorfoe(r.Header.Get("Accept")) {
813 if len(honks) > 40 {
814 honks = honks[0:40]
815 }
816
817 var xids []string
818 for _, h := range honks {
819 xids = append(xids, h.XID)
820 }
821
822 user := getserveruser()
823
824 j := junk.New()
825 j["@context"] = itiswhatitis
826 j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
827 j["name"] = "#" + name
828 j["attributedTo"] = user.URL
829 j["type"] = "OrderedCollection"
830 j["totalItems"] = len(xids)
831 j["orderedItems"] = xids
832
833 j.Write(w)
834 return
835 }
836
837 templinfo := getInfo(r)
838 templinfo["ServerMessage"] = "honks by ontology: " + name
839 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
840 honkpage(w, u, honks, templinfo)
841}
842
843type Ont struct {
844 Name string
845 Count int64
846}
847
848func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
849 u := login.GetUserInfo(r)
850 var userid int64 = -1
851 if u != nil {
852 userid = u.UserID
853 }
854 rows, err := stmtAllOnts.Query(userid)
855 if err != nil {
856 elog.Printf("selection error: %s", err)
857 return
858 }
859 defer rows.Close()
860 var onts []Ont
861 for rows.Next() {
862 var o Ont
863 err := rows.Scan(&o.Name, &o.Count)
864 if err != nil {
865 elog.Printf("error scanning ont: %s", err)
866 continue
867 }
868 if utf8.RuneCountInString(o.Name) > 24 {
869 continue
870 }
871 o.Name = o.Name[1:]
872 onts = append(onts, o)
873 }
874 sort.Slice(onts, func(i, j int) bool {
875 return onts[i].Name < onts[j].Name
876 })
877 if u == nil && !develMode {
878 w.Header().Set("Cache-Control", "max-age=300")
879 }
880 templinfo := getInfo(r)
881 templinfo["Onts"] = onts
882 templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
883 err = readviews.Execute(w, "onts.html", templinfo)
884 if err != nil {
885 elog.Print(err)
886 }
887}
888
889type Track struct {
890 xid string
891 who string
892}
893
894func getbacktracks(xid string) []string {
895 c := make(chan bool)
896 dumptracks <- c
897 <-c
898 row := stmtGetTracks.QueryRow(xid)
899 var rawtracks string
900 err := row.Scan(&rawtracks)
901 if err != nil {
902 if err != sql.ErrNoRows {
903 elog.Printf("error scanning tracks: %s", err)
904 }
905 return nil
906 }
907 var rcpts []string
908 for _, f := range strings.Split(rawtracks, " ") {
909 idx := strings.LastIndexByte(f, '#')
910 if idx != -1 {
911 f = f[:idx]
912 }
913 if !strings.HasPrefix(f, "https://") {
914 f = fmt.Sprintf("%%https://%s/inbox", f)
915 }
916 rcpts = append(rcpts, f)
917 }
918 return rcpts
919}
920
921func savetracks(tracks map[string][]string) {
922 db := opendatabase()
923 tx, err := db.Begin()
924 if err != nil {
925 elog.Printf("savetracks begin error: %s", err)
926 return
927 }
928 defer func() {
929 err := tx.Commit()
930 if err != nil {
931 elog.Printf("savetracks commit error: %s", err)
932 }
933
934 }()
935 stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
936 if err != nil {
937 elog.Printf("savetracks error: %s", err)
938 return
939 }
940 stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
941 if err != nil {
942 elog.Printf("savetracks error: %s", err)
943 return
944 }
945 stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
946 if err != nil {
947 elog.Printf("savetracks error: %s", err)
948 return
949 }
950 count := 0
951 for xid, f := range tracks {
952 count += len(f)
953 var prev string
954 row := stmtGetTracks.QueryRow(xid)
955 err := row.Scan(&prev)
956 if err == sql.ErrNoRows {
957 f = oneofakind(f)
958 stmtNewTracks.Exec(xid, strings.Join(f, " "))
959 } else if err == nil {
960 all := append(strings.Split(prev, " "), f...)
961 all = oneofakind(all)
962 stmtUpdateTracks.Exec(strings.Join(all, " "))
963 } else {
964 elog.Printf("savetracks error: %s", err)
965 }
966 }
967 dlog.Printf("saved %d new fetches", count)
968}
969
970var trackchan = make(chan Track)
971var dumptracks = make(chan chan bool)
972
973func tracker() {
974 timeout := 4 * time.Minute
975 sleeper := time.NewTimer(timeout)
976 tracks := make(map[string][]string)
977 workinprogress++
978 for {
979 select {
980 case track := <-trackchan:
981 tracks[track.xid] = append(tracks[track.xid], track.who)
982 case <-sleeper.C:
983 if len(tracks) > 0 {
984 go savetracks(tracks)
985 tracks = make(map[string][]string)
986 }
987 sleeper.Reset(timeout)
988 case c := <-dumptracks:
989 if len(tracks) > 0 {
990 savetracks(tracks)
991 }
992 c <- true
993 case <-endoftheworld:
994 if len(tracks) > 0 {
995 savetracks(tracks)
996 }
997 readyalready <- true
998 return
999 }
1000 }
1001}
1002
1003var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1004
1005func trackback(xid string, r *http.Request) {
1006 agent := r.UserAgent()
1007 who := originate(agent)
1008 sig := r.Header.Get("Signature")
1009 if sig != "" {
1010 m := re_keyholder.FindStringSubmatch(sig)
1011 if len(m) == 2 {
1012 who = m[1]
1013 }
1014 }
1015 if who != "" {
1016 trackchan <- Track{xid: xid, who: who}
1017 }
1018}
1019
1020func showonehonk(w http.ResponseWriter, r *http.Request) {
1021 name := mux.Vars(r)["name"]
1022 user, err := butwhatabout(name)
1023 if err != nil {
1024 http.NotFound(w, r)
1025 return
1026 }
1027 if stealthmode(user.ID, r) {
1028 http.NotFound(w, r)
1029 return
1030 }
1031 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1032
1033 if friendorfoe(r.Header.Get("Accept")) {
1034 j, ok := gimmejonk(xid)
1035 if ok {
1036 trackback(xid, r)
1037 w.Header().Set("Content-Type", theonetruename)
1038 w.Write(j)
1039 } else {
1040 http.NotFound(w, r)
1041 }
1042 return
1043 }
1044 honk := getxonk(user.ID, xid)
1045 if honk == nil {
1046 http.NotFound(w, r)
1047 return
1048 }
1049 u := login.GetUserInfo(r)
1050 if u != nil && u.UserID != user.ID {
1051 u = nil
1052 }
1053 if !honk.Public {
1054 if u == nil {
1055 http.NotFound(w, r)
1056 return
1057
1058 }
1059 honks := []*Honk{honk}
1060 donksforhonks(honks)
1061 templinfo := getInfo(r)
1062 templinfo["ServerMessage"] = "one honk maybe more"
1063 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1064 honkpage(w, u, honks, templinfo)
1065 return
1066 }
1067 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1068 reversehonks(rawhonks)
1069 var honks []*Honk
1070 for _, h := range rawhonks {
1071 if h.XID == xid && len(honks) != 0 {
1072 h.Style += " glow"
1073 }
1074 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1075 honks = append(honks, h)
1076 }
1077 }
1078
1079 templinfo := getInfo(r)
1080 templinfo["ServerMessage"] = "one honk maybe more"
1081 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1082 honkpage(w, u, honks, templinfo)
1083}
1084
1085func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1086 var userid int64 = -1
1087 if u != nil {
1088 userid = u.UserID
1089 templinfo["User"], _ = butwhatabout(u.Username)
1090 }
1091 reverbolate(userid, honks)
1092 templinfo["Honks"] = honks
1093 templinfo["MapLink"] = getmaplink(u)
1094 if templinfo["TopHID"] == nil {
1095 if len(honks) > 0 {
1096 templinfo["TopHID"] = honks[0].ID
1097 } else {
1098 templinfo["TopHID"] = 0
1099 }
1100 }
1101 if u == nil && !develMode {
1102 w.Header().Set("Cache-Control", "max-age=60")
1103 }
1104 err := readviews.Execute(w, "honkpage.html", templinfo)
1105 if err != nil {
1106 elog.Print(err)
1107 }
1108}
1109
1110func saveuser(w http.ResponseWriter, r *http.Request) {
1111 whatabout := r.FormValue("whatabout")
1112 whatabout = strings.Replace(whatabout, "\r", "", -1)
1113 u := login.GetUserInfo(r)
1114 user, _ := butwhatabout(u.Username)
1115 db := opendatabase()
1116
1117 options := user.Options
1118 if r.FormValue("skinny") == "skinny" {
1119 options.SkinnyCSS = true
1120 } else {
1121 options.SkinnyCSS = false
1122 }
1123 if r.FormValue("omitimages") == "omitimages" {
1124 options.OmitImages = true
1125 } else {
1126 options.OmitImages = false
1127 }
1128 if r.FormValue("mentionall") == "mentionall" {
1129 options.MentionAll = true
1130 } else {
1131 options.MentionAll = false
1132 }
1133 if r.FormValue("inlineqts") == "inlineqts" {
1134 options.InlineQuotes = true
1135 } else {
1136 options.InlineQuotes = false
1137 }
1138 if r.FormValue("maps") == "apple" {
1139 options.MapLink = "apple"
1140 } else {
1141 options.MapLink = ""
1142 }
1143 options.Reaction = r.FormValue("reaction")
1144
1145 sendupdate := false
1146 ava := re_avatar.FindString(whatabout)
1147 if ava != "" {
1148 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1149 ava = ava[7:]
1150 if ava[0] == ' ' {
1151 ava = ava[1:]
1152 }
1153 ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1154 }
1155 if ava != options.Avatar {
1156 options.Avatar = ava
1157 sendupdate = true
1158 }
1159 ban := re_banner.FindString(whatabout)
1160 if ban != "" {
1161 whatabout = re_banner.ReplaceAllString(whatabout, "")
1162 ban = ban[7:]
1163 if ban[0] == ' ' {
1164 ban = ban[1:]
1165 }
1166 ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1167 }
1168 if ban != options.Banner {
1169 options.Banner = ban
1170 sendupdate = true
1171 }
1172 whatabout = strings.TrimSpace(whatabout)
1173 if whatabout != user.About {
1174 sendupdate = true
1175 }
1176 j, err := jsonify(options)
1177 if err == nil {
1178 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1179 }
1180 if err != nil {
1181 elog.Printf("error bouting what: %s", err)
1182 }
1183 somenamedusers.Clear(u.Username)
1184 somenumberedusers.Clear(u.UserID)
1185 oldjonkers.Clear(u.Username)
1186
1187 if sendupdate {
1188 updateMe(u.Username)
1189 }
1190
1191 http.Redirect(w, r, "/account", http.StatusSeeOther)
1192}
1193
1194func bonkit(xid string, user *WhatAbout) {
1195 dlog.Printf("bonking %s", xid)
1196
1197 xonk := getxonk(user.ID, xid)
1198 if xonk == nil {
1199 return
1200 }
1201 if !xonk.Public {
1202 return
1203 }
1204 if xonk.IsBonked() {
1205 return
1206 }
1207 donksforhonks([]*Honk{xonk})
1208
1209 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1210 if err != nil {
1211 elog.Printf("error acking bonk: %s", err)
1212 }
1213
1214 oonker := xonk.Oonker
1215 if oonker == "" {
1216 oonker = xonk.Honker
1217 }
1218 dt := time.Now().UTC()
1219 bonk := &Honk{
1220 UserID: user.ID,
1221 Username: user.Name,
1222 What: "bonk",
1223 Honker: user.URL,
1224 Oonker: oonker,
1225 XID: xonk.XID,
1226 RID: xonk.RID,
1227 Noise: xonk.Noise,
1228 Precis: xonk.Precis,
1229 URL: xonk.URL,
1230 Date: dt,
1231 Donks: xonk.Donks,
1232 Whofore: 2,
1233 Convoy: xonk.Convoy,
1234 Audience: []string{thewholeworld, oonker},
1235 Public: true,
1236 Format: xonk.Format,
1237 Place: xonk.Place,
1238 Onts: xonk.Onts,
1239 Time: xonk.Time,
1240 }
1241
1242 err = savehonk(bonk)
1243 if err != nil {
1244 elog.Printf("uh oh")
1245 return
1246 }
1247
1248 go honkworldwide(user, bonk)
1249}
1250
1251func submitbonk(w http.ResponseWriter, r *http.Request) {
1252 xid := r.FormValue("xid")
1253 userinfo := login.GetUserInfo(r)
1254 user, _ := butwhatabout(userinfo.Username)
1255
1256 bonkit(xid, user)
1257
1258 if r.FormValue("js") != "1" {
1259 templinfo := getInfo(r)
1260 templinfo["ServerMessage"] = "Bonked!"
1261 err := readviews.Execute(w, "msg.html", templinfo)
1262 if err != nil {
1263 elog.Print(err)
1264 }
1265 }
1266}
1267
1268func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1269 zonk := &Honk{
1270 What: what,
1271 XID: xonk.XID,
1272 Date: time.Now().UTC(),
1273 Audience: oneofakind(xonk.Audience),
1274 Noise: aux,
1275 }
1276 zonk.Public = loudandproud(zonk.Audience)
1277
1278 dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1279 go honkworldwide(user, zonk)
1280}
1281
1282func zonkit(w http.ResponseWriter, r *http.Request) {
1283 wherefore := r.FormValue("wherefore")
1284 what := r.FormValue("what")
1285 userinfo := login.GetUserInfo(r)
1286 user, _ := butwhatabout(userinfo.Username)
1287
1288 if wherefore == "save" {
1289 xonk := getxonk(userinfo.UserID, what)
1290 if xonk != nil {
1291 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1292 if err != nil {
1293 elog.Printf("error saving: %s", err)
1294 }
1295 }
1296 return
1297 }
1298
1299 if wherefore == "unsave" {
1300 xonk := getxonk(userinfo.UserID, what)
1301 if xonk != nil {
1302 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1303 if err != nil {
1304 elog.Printf("error unsaving: %s", err)
1305 }
1306 }
1307 return
1308 }
1309
1310 if wherefore == "react" {
1311 reaction := user.Options.Reaction
1312 if r2 := r.FormValue("reaction"); r2 != "" {
1313 reaction = r2
1314 }
1315 if reaction == "none" {
1316 return
1317 }
1318 xonk := getxonk(userinfo.UserID, what)
1319 if xonk != nil {
1320 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1321 if err != nil {
1322 elog.Printf("error saving: %s", err)
1323 }
1324 sendzonkofsorts(xonk, user, "react", reaction)
1325 }
1326 return
1327 }
1328
1329 // my hammer is too big, oh well
1330 defer oldjonks.Flush()
1331
1332 if wherefore == "ack" {
1333 xonk := getxonk(userinfo.UserID, what)
1334 if xonk != nil && !xonk.IsAcked() {
1335 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1336 if err != nil {
1337 elog.Printf("error acking: %s", err)
1338 }
1339 sendzonkofsorts(xonk, user, "ack", "")
1340 }
1341 return
1342 }
1343
1344 if wherefore == "deack" {
1345 xonk := getxonk(userinfo.UserID, what)
1346 if xonk != nil && xonk.IsAcked() {
1347 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1348 if err != nil {
1349 elog.Printf("error deacking: %s", err)
1350 }
1351 sendzonkofsorts(xonk, user, "deack", "")
1352 }
1353 return
1354 }
1355
1356 if wherefore == "bonk" {
1357 user, _ := butwhatabout(userinfo.Username)
1358 bonkit(what, user)
1359 return
1360 }
1361
1362 if wherefore == "unbonk" {
1363 xonk := getbonk(userinfo.UserID, what)
1364 if xonk != nil {
1365 deletehonk(xonk.ID)
1366 xonk = getxonk(userinfo.UserID, what)
1367 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1368 if err != nil {
1369 elog.Printf("error unbonking: %s", err)
1370 }
1371 sendzonkofsorts(xonk, user, "unbonk", "")
1372 }
1373 return
1374 }
1375
1376 if wherefore == "untag" {
1377 xonk := getxonk(userinfo.UserID, what)
1378 if xonk != nil {
1379 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1380 if err != nil {
1381 elog.Printf("error untagging: %s", err)
1382 }
1383 }
1384 var badparents map[string]bool
1385 untagged.GetAndLock(userinfo.UserID, &badparents)
1386 badparents[what] = true
1387 untagged.Unlock()
1388 return
1389 }
1390
1391 ilog.Printf("zonking %s %s", wherefore, what)
1392 if wherefore == "zonk" {
1393 xonk := getxonk(userinfo.UserID, what)
1394 if xonk != nil {
1395 deletehonk(xonk.ID)
1396 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1397 sendzonkofsorts(xonk, user, "zonk", "")
1398 }
1399 }
1400 }
1401 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1402 if err != nil {
1403 elog.Printf("error saving zonker: %s", err)
1404 return
1405 }
1406}
1407
1408func edithonkpage(w http.ResponseWriter, r *http.Request) {
1409 u := login.GetUserInfo(r)
1410 user, _ := butwhatabout(u.Username)
1411 xid := r.FormValue("xid")
1412 honk := getxonk(u.UserID, xid)
1413 if !canedithonk(user, honk) {
1414 http.Error(w, "no editing that please", http.StatusInternalServerError)
1415 return
1416 }
1417
1418 noise := honk.Noise
1419
1420 honks := []*Honk{honk}
1421 donksforhonks(honks)
1422 reverbolate(u.UserID, honks)
1423 templinfo := getInfo(r)
1424 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1425 templinfo["Honks"] = honks
1426 templinfo["MapLink"] = getmaplink(u)
1427 templinfo["Noise"] = noise
1428 templinfo["SavedPlace"] = honk.Place
1429 if tm := honk.Time; tm != nil {
1430 templinfo["ShowTime"] = " "
1431 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1432 if tm.Duration != 0 {
1433 templinfo["Duration"] = tm.Duration
1434 }
1435 }
1436 templinfo["ServerMessage"] = "honk edit 2"
1437 templinfo["IsPreview"] = true
1438 templinfo["UpdateXID"] = honk.XID
1439 if len(honk.Donks) > 0 {
1440 templinfo["SavedFile"] = honk.Donks[0].XID
1441 }
1442 err := readviews.Execute(w, "honkpage.html", templinfo)
1443 if err != nil {
1444 elog.Print(err)
1445 }
1446}
1447
1448func newhonkpage(w http.ResponseWriter, r *http.Request) {
1449 u := login.GetUserInfo(r)
1450 rid := r.FormValue("rid")
1451 noise := ""
1452
1453 xonk := getxonk(u.UserID, rid)
1454 if xonk != nil {
1455 _, replto := handles(xonk.Honker)
1456 if replto != "" {
1457 noise = "@" + replto + " "
1458 }
1459 }
1460
1461 templinfo := getInfo(r)
1462 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1463 templinfo["InReplyTo"] = rid
1464 templinfo["Noise"] = noise
1465 templinfo["ServerMessage"] = "compose honk"
1466 templinfo["IsPreview"] = true
1467 err := readviews.Execute(w, "honkpage.html", templinfo)
1468 if err != nil {
1469 elog.Print(err)
1470 }
1471}
1472
1473func canedithonk(user *WhatAbout, honk *Honk) bool {
1474 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1475 return false
1476 }
1477 return true
1478}
1479
1480func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1481 if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1482 return nil, nil
1483 }
1484 file, filehdr, err := r.FormFile("donk")
1485 if err != nil {
1486 if err == http.ErrMissingFile {
1487 return nil, nil
1488 }
1489 elog.Printf("error reading donk: %s", err)
1490 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1491 return nil, err
1492 }
1493 var buf bytes.Buffer
1494 io.Copy(&buf, file)
1495 file.Close()
1496 data := buf.Bytes()
1497 var media, name string
1498 img, err := shrinkit(data)
1499 if err == nil {
1500 data = img.Data
1501 format := img.Format
1502 media = "image/" + format
1503 if format == "jpeg" {
1504 format = "jpg"
1505 }
1506 name = xfiltrate() + "." + format
1507 } else {
1508 ct := http.DetectContentType(data)
1509 switch ct {
1510 case "application/pdf":
1511 maxsize := 10000000
1512 if len(data) > maxsize {
1513 ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1514 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1515 return nil, err
1516 }
1517 media = ct
1518 name = filehdr.Filename
1519 if name == "" {
1520 name = xfiltrate() + ".pdf"
1521 }
1522 default:
1523 maxsize := 100000
1524 if len(data) > maxsize {
1525 ilog.Printf("bad image: %s too much text: %d", err, len(data))
1526 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1527 return nil, err
1528 }
1529 for i := 0; i < len(data); i++ {
1530 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1531 ilog.Printf("bad image: %s not text: %d", err, data[i])
1532 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1533 return nil, err
1534 }
1535 }
1536 media = "text/plain"
1537 name = filehdr.Filename
1538 if name == "" {
1539 name = xfiltrate() + ".txt"
1540 }
1541 }
1542 }
1543 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1544 if desc == "" {
1545 desc = name
1546 }
1547 fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1548 if err != nil {
1549 elog.Printf("unable to save image: %s", err)
1550 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1551 return nil, err
1552 }
1553 d := &Donk{
1554 FileID: fileid,
1555 XID: xid,
1556 Desc: desc,
1557 Local: true,
1558 }
1559 return d, nil
1560}
1561
1562func websubmithonk(w http.ResponseWriter, r *http.Request) {
1563 h := submithonk(w, r)
1564 if h == nil {
1565 return
1566 }
1567 http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1568}
1569
1570// what a hot mess this function is
1571func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1572 rid := r.FormValue("rid")
1573 noise := r.FormValue("noise")
1574 format := r.FormValue("format")
1575 if format == "" {
1576 format = "markdown"
1577 }
1578 if !(format == "markdown" || format == "html") {
1579 http.Error(w, "unknown format", 500)
1580 return nil
1581 }
1582
1583 userinfo := login.GetUserInfo(r)
1584 user, _ := butwhatabout(userinfo.Username)
1585
1586 dt := time.Now().UTC()
1587 updatexid := r.FormValue("updatexid")
1588 var honk *Honk
1589 if updatexid != "" {
1590 honk = getxonk(userinfo.UserID, updatexid)
1591 if !canedithonk(user, honk) {
1592 http.Error(w, "no editing that please", http.StatusInternalServerError)
1593 return nil
1594 }
1595 honk.Date = dt
1596 honk.What = "update"
1597 honk.Format = format
1598 } else {
1599 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1600 what := "honk"
1601 if rid != "" {
1602 what = "tonk"
1603 }
1604 honk = &Honk{
1605 UserID: userinfo.UserID,
1606 Username: userinfo.Username,
1607 What: what,
1608 Honker: user.URL,
1609 XID: xid,
1610 Date: dt,
1611 Format: format,
1612 }
1613 }
1614
1615 var convoy string
1616 noise = strings.Replace(noise, "\r", "", -1)
1617 if updatexid == "" && rid == "" {
1618 noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1619 convoy = m[7:]
1620 convoy = strings.TrimSpace(convoy)
1621 if !re_convalidate.MatchString(convoy) {
1622 convoy = ""
1623 }
1624 return ""
1625 })
1626 }
1627 noise = quickrename(noise, userinfo.UserID)
1628 noise = hooterize(noise)
1629 honk.Noise = noise
1630 precipitate(honk)
1631 noise = honk.Noise
1632 translate(honk)
1633
1634 if rid != "" {
1635 xonk := getxonk(userinfo.UserID, rid)
1636 if xonk == nil {
1637 http.Error(w, "replyto disappeared", http.StatusNotFound)
1638 return nil
1639 }
1640 if xonk.Public {
1641 honk.Audience = append(honk.Audience, xonk.Audience...)
1642 }
1643 convoy = xonk.Convoy
1644 for i, a := range honk.Audience {
1645 if a == thewholeworld {
1646 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1647 break
1648 }
1649 }
1650 honk.RID = rid
1651 if xonk.Precis != "" && honk.Precis == "" {
1652 honk.Precis = xonk.Precis
1653 if !re_dangerous.MatchString(honk.Precis) {
1654 honk.Precis = "re: " + honk.Precis
1655 }
1656 }
1657 } else {
1658 honk.Audience = []string{thewholeworld}
1659 }
1660 if honk.Noise != "" && honk.Noise[0] == '@' {
1661 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1662 } else {
1663 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1664 }
1665
1666 if convoy == "" {
1667 convoy = "data:,electrichonkytonk-" + xfiltrate()
1668 }
1669 butnottooloud(honk.Audience)
1670 honk.Audience = oneofakind(honk.Audience)
1671 if len(honk.Audience) == 0 {
1672 ilog.Printf("honk to nowhere")
1673 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1674 return nil
1675 }
1676 honk.Public = loudandproud(honk.Audience)
1677 honk.Convoy = convoy
1678
1679 donkxid := r.FormValue("donkxid")
1680 if donkxid == "" {
1681 d, err := submitdonk(w, r)
1682 if err != nil && err != http.ErrMissingFile {
1683 return nil
1684 }
1685 if d != nil {
1686 honk.Donks = append(honk.Donks, d)
1687 donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1688 }
1689 } else {
1690 p := strings.Split(donkxid, ":")
1691 xid := p[0]
1692 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1693 var donk *Donk
1694 if len(p) > 1 {
1695 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1696 donk = finddonkid(fileid, url)
1697 } else {
1698 donk = finddonk(url)
1699 }
1700 if donk != nil {
1701 honk.Donks = append(honk.Donks, donk)
1702 } else {
1703 ilog.Printf("can't find file: %s", xid)
1704 }
1705 }
1706 memetize(honk)
1707 imaginate(honk)
1708
1709 placename := strings.TrimSpace(r.FormValue("placename"))
1710 placelat := strings.TrimSpace(r.FormValue("placelat"))
1711 placelong := strings.TrimSpace(r.FormValue("placelong"))
1712 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1713 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1714 p := new(Place)
1715 p.Name = placename
1716 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1717 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1718 p.Url = placeurl
1719 honk.Place = p
1720 }
1721 timestart := strings.TrimSpace(r.FormValue("timestart"))
1722 if timestart != "" {
1723 t := new(Time)
1724 now := time.Now().Local()
1725 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1726 start, err := time.ParseInLocation(layout, timestart, now.Location())
1727 if err == nil {
1728 if start.Year() == 0 {
1729 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1730 }
1731 t.StartTime = start
1732 break
1733 }
1734 }
1735 timeend := r.FormValue("timeend")
1736 dur := parseDuration(timeend)
1737 if dur != 0 {
1738 t.Duration = Duration(dur)
1739 }
1740 if !t.StartTime.IsZero() {
1741 honk.What = "event"
1742 honk.Time = t
1743 }
1744 }
1745
1746 if honk.Public {
1747 honk.Whofore = 2
1748 } else {
1749 honk.Whofore = 3
1750 }
1751
1752 // back to markdown
1753 honk.Noise = noise
1754
1755 if r.FormValue("preview") == "preview" {
1756 honks := []*Honk{honk}
1757 reverbolate(userinfo.UserID, honks)
1758 templinfo := getInfo(r)
1759 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1760 templinfo["Honks"] = honks
1761 templinfo["MapLink"] = getmaplink(userinfo)
1762 templinfo["InReplyTo"] = r.FormValue("rid")
1763 templinfo["Noise"] = r.FormValue("noise")
1764 templinfo["SavedFile"] = donkxid
1765 if tm := honk.Time; tm != nil {
1766 templinfo["ShowTime"] = " "
1767 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1768 if tm.Duration != 0 {
1769 templinfo["Duration"] = tm.Duration
1770 }
1771 }
1772 templinfo["IsPreview"] = true
1773 templinfo["UpdateXID"] = updatexid
1774 templinfo["ServerMessage"] = "honk preview"
1775 err := readviews.Execute(w, "honkpage.html", templinfo)
1776 if err != nil {
1777 elog.Print(err)
1778 }
1779 return nil
1780 }
1781
1782 if updatexid != "" {
1783 updatehonk(honk)
1784 oldjonks.Clear(honk.XID)
1785 } else {
1786 err := savehonk(honk)
1787 if err != nil {
1788 elog.Printf("uh oh")
1789 return nil
1790 }
1791 }
1792
1793 // reload for consistency
1794 honk.Donks = nil
1795 donksforhonks([]*Honk{honk})
1796
1797 go honkworldwide(user, honk)
1798
1799 return honk
1800}
1801
1802func showhonkers(w http.ResponseWriter, r *http.Request) {
1803 userinfo := login.GetUserInfo(r)
1804 templinfo := getInfo(r)
1805 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1806 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1807 err := readviews.Execute(w, "honkers.html", templinfo)
1808 if err != nil {
1809 elog.Print(err)
1810 }
1811}
1812
1813func showchatter(w http.ResponseWriter, r *http.Request) {
1814 u := login.GetUserInfo(r)
1815 chatnewnone(u.UserID)
1816 chatter := loadchatter(u.UserID)
1817 for _, chat := range chatter {
1818 for _, ch := range chat.Chonks {
1819 filterchonk(ch)
1820 }
1821 }
1822
1823 templinfo := getInfo(r)
1824 templinfo["Chatter"] = chatter
1825 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1826 err := readviews.Execute(w, "chatter.html", templinfo)
1827 if err != nil {
1828 elog.Print(err)
1829 }
1830}
1831
1832func submitchonk(w http.ResponseWriter, r *http.Request) {
1833 u := login.GetUserInfo(r)
1834 user, _ := butwhatabout(u.Username)
1835 noise := r.FormValue("noise")
1836 target := r.FormValue("target")
1837 format := "markdown"
1838 dt := time.Now().UTC()
1839 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1840
1841 if !strings.HasPrefix(target, "https://") {
1842 target = fullname(target, u.UserID)
1843 }
1844 if target == "" {
1845 http.Error(w, "who is that?", http.StatusInternalServerError)
1846 return
1847 }
1848 ch := Chonk{
1849 UserID: u.UserID,
1850 XID: xid,
1851 Who: user.URL,
1852 Target: target,
1853 Date: dt,
1854 Noise: noise,
1855 Format: format,
1856 }
1857 d, err := submitdonk(w, r)
1858 if err != nil && err != http.ErrMissingFile {
1859 return
1860 }
1861 if d != nil {
1862 ch.Donks = append(ch.Donks, d)
1863 }
1864
1865 translatechonk(&ch)
1866 savechonk(&ch)
1867 // reload for consistency
1868 ch.Donks = nil
1869 donksforchonks([]*Chonk{&ch})
1870 go sendchonk(user, &ch)
1871
1872 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1873}
1874
1875var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1876 honkers := gethonkers(userid)
1877 var combos []string
1878 for _, h := range honkers {
1879 combos = append(combos, h.Combos...)
1880 }
1881 for i, c := range combos {
1882 if c == "-" {
1883 combos[i] = ""
1884 }
1885 }
1886 combos = oneofakind(combos)
1887 sort.Strings(combos)
1888 return combos, true
1889}, Invalidator: &honkerinvalidator})
1890
1891func showcombos(w http.ResponseWriter, r *http.Request) {
1892 userinfo := login.GetUserInfo(r)
1893 var combos []string
1894 combocache.Get(userinfo.UserID, &combos)
1895 templinfo := getInfo(r)
1896 err := readviews.Execute(w, "combos.html", templinfo)
1897 if err != nil {
1898 elog.Print(err)
1899 }
1900}
1901
1902func websubmithonker(w http.ResponseWriter, r *http.Request) {
1903 h := submithonker(w, r)
1904 if h == nil {
1905 return
1906 }
1907 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1908}
1909
1910func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
1911 u := login.GetUserInfo(r)
1912 user, _ := butwhatabout(u.Username)
1913 name := strings.TrimSpace(r.FormValue("name"))
1914 url := strings.TrimSpace(r.FormValue("url"))
1915 peep := r.FormValue("peep")
1916 combos := strings.TrimSpace(r.FormValue("combos"))
1917 combos = " " + combos + " "
1918 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1919
1920 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
1921 if name != "" && !re_namecheck.MatchString(name) {
1922 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
1923 return nil
1924 }
1925
1926 var meta HonkerMeta
1927 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1928 mj, _ := jsonify(&meta)
1929
1930 defer honkerinvalidator.Clear(u.UserID)
1931
1932 // mostly dummy, fill in later...
1933 h := &Honker{
1934 ID: honkerid,
1935 }
1936
1937 if honkerid > 0 {
1938 if r.FormValue("delete") == "delete" {
1939 unfollowyou(user, honkerid, false)
1940 stmtDeleteHonker.Exec(honkerid)
1941 return h
1942 }
1943 if r.FormValue("unsub") == "unsub" {
1944 unfollowyou(user, honkerid, false)
1945 }
1946 if r.FormValue("sub") == "sub" {
1947 followyou(user, honkerid, false)
1948 }
1949 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1950 if err != nil {
1951 elog.Printf("update honker err: %s", err)
1952 return nil
1953 }
1954 return h
1955 }
1956
1957 if url == "" {
1958 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1959 return nil
1960 }
1961
1962 flavor := "presub"
1963 if peep == "peep" {
1964 flavor = "peep"
1965 }
1966
1967 id, err := savehonker(user, url, name, flavor, combos, mj)
1968 if err != nil {
1969 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
1970 return nil
1971 }
1972 if flavor == "presub" {
1973 followyou(user, honkerid, false)
1974 }
1975 h.ID = id
1976 return h
1977}
1978
1979func hfcspage(w http.ResponseWriter, r *http.Request) {
1980 userinfo := login.GetUserInfo(r)
1981
1982 filters := getfilters(userinfo.UserID, filtAny)
1983
1984 templinfo := getInfo(r)
1985 templinfo["Filters"] = filters
1986 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1987 err := readviews.Execute(w, "hfcs.html", templinfo)
1988 if err != nil {
1989 elog.Print(err)
1990 }
1991}
1992
1993func savehfcs(w http.ResponseWriter, r *http.Request) {
1994 userinfo := login.GetUserInfo(r)
1995 itsok := r.FormValue("itsok")
1996 if itsok == "iforgiveyou" {
1997 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1998 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1999 if err != nil {
2000 elog.Printf("error deleting filter: %s", err)
2001 }
2002 filtInvalidator.Clear(userinfo.UserID)
2003 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2004 return
2005 }
2006
2007 filt := new(Filter)
2008 filt.Name = strings.TrimSpace(r.FormValue("name"))
2009 filt.Date = time.Now().UTC()
2010 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2011 filt.IncludeAudience = r.FormValue("incaud") == "yes"
2012 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2013 filt.IsReply = r.FormValue("isreply") == "yes"
2014 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2015 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2016 filt.Reject = r.FormValue("doreject") == "yes"
2017 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2018 filt.Hide = r.FormValue("dohide") == "yes"
2019 filt.Collapse = r.FormValue("docollapse") == "yes"
2020 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2021 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2022 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2023 filt.Expiration = time.Now().UTC().Add(dur)
2024 }
2025 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2026
2027 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2028 ilog.Printf("blank filter")
2029 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2030 return
2031 }
2032
2033 j, err := jsonify(filt)
2034 if err == nil {
2035 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2036 }
2037 if err != nil {
2038 elog.Printf("error saving filter: %s", err)
2039 }
2040
2041 filtInvalidator.Clear(userinfo.UserID)
2042 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2043}
2044
2045func accountpage(w http.ResponseWriter, r *http.Request) {
2046 u := login.GetUserInfo(r)
2047 user, _ := butwhatabout(u.Username)
2048 templinfo := getInfo(r)
2049 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2050 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2051 templinfo["User"] = user
2052 about := user.About
2053 if ava := user.Options.Avatar; ava != "" {
2054 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2055 }
2056 if ban := user.Options.Banner; ban != "" {
2057 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2058 }
2059 templinfo["WhatAbout"] = about
2060 err := readviews.Execute(w, "account.html", templinfo)
2061 if err != nil {
2062 elog.Print(err)
2063 }
2064}
2065
2066func dochpass(w http.ResponseWriter, r *http.Request) {
2067 err := login.ChangePassword(w, r)
2068 if err != nil {
2069 elog.Printf("error changing password: %s", err)
2070 }
2071 http.Redirect(w, r, "/account", http.StatusSeeOther)
2072}
2073
2074func fingerlicker(w http.ResponseWriter, r *http.Request) {
2075 orig := r.FormValue("resource")
2076
2077 dlog.Printf("finger lick: %s", orig)
2078
2079 if strings.HasPrefix(orig, "acct:") {
2080 orig = orig[5:]
2081 }
2082
2083 name := orig
2084 idx := strings.LastIndexByte(name, '/')
2085 if idx != -1 {
2086 name = name[idx+1:]
2087 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2088 ilog.Printf("foreign request rejected")
2089 name = ""
2090 }
2091 } else {
2092 idx = strings.IndexByte(name, '@')
2093 if idx != -1 {
2094 name = name[:idx]
2095 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2096 ilog.Printf("foreign request rejected")
2097 name = ""
2098 }
2099 }
2100 }
2101 user, err := butwhatabout(name)
2102 if err != nil {
2103 http.NotFound(w, r)
2104 return
2105 }
2106 if stealthmode(user.ID, r) {
2107 http.NotFound(w, r)
2108 return
2109 }
2110
2111 j := junk.New()
2112 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2113 j["aliases"] = []string{user.URL}
2114 l := junk.New()
2115 l["rel"] = "self"
2116 l["type"] = `application/activity+json`
2117 l["href"] = user.URL
2118 j["links"] = []junk.Junk{l}
2119
2120 w.Header().Set("Content-Type", "application/jrd+json")
2121 j.Write(w)
2122}
2123
2124func somedays() string {
2125 secs := 432000 + notrand.Int63n(432000)
2126 return fmt.Sprintf("%d", secs)
2127}
2128
2129func lookatme(ava string) string {
2130 if strings.Contains(ava, serverName+"/"+userSep) {
2131 idx := strings.LastIndexByte(ava, '/')
2132 if idx < len(ava) {
2133 name := ava[idx+1:]
2134 user, _ := butwhatabout(name)
2135 if user != nil && user.URL == ava {
2136 return user.Options.Avatar
2137 }
2138 }
2139 }
2140 return ""
2141}
2142
2143func avatate(w http.ResponseWriter, r *http.Request) {
2144 if develMode {
2145 loadAvatarColors()
2146 }
2147 n := r.FormValue("a")
2148 if redir := lookatme(n); redir != "" {
2149 http.Redirect(w, r, redir, http.StatusSeeOther)
2150 return
2151 }
2152 a := genAvatar(n)
2153 if !develMode {
2154 w.Header().Set("Cache-Control", "max-age="+somedays())
2155 }
2156 w.Write(a)
2157}
2158
2159func serveviewasset(w http.ResponseWriter, r *http.Request) {
2160 serveasset(w, r, viewDir)
2161}
2162func servedataasset(w http.ResponseWriter, r *http.Request) {
2163 if r.URL.Path == "/favicon.ico" {
2164 r.URL.Path = "/icon.png"
2165 }
2166 serveasset(w, r, dataDir)
2167}
2168
2169func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2170 if !develMode {
2171 w.Header().Set("Cache-Control", "max-age=7776000")
2172 }
2173 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2174}
2175func servehelp(w http.ResponseWriter, r *http.Request) {
2176 name := mux.Vars(r)["name"]
2177 if !develMode {
2178 w.Header().Set("Cache-Control", "max-age=3600")
2179 }
2180 http.ServeFile(w, r, viewDir+"/docs/"+name)
2181}
2182func servehtml(w http.ResponseWriter, r *http.Request) {
2183 u := login.GetUserInfo(r)
2184 templinfo := getInfo(r)
2185 templinfo["AboutMsg"] = aboutMsg
2186 templinfo["LoginMsg"] = loginMsg
2187 templinfo["HonkVersion"] = softwareVersion
2188 if r.URL.Path == "/about" {
2189 templinfo["Sensors"] = getSensors()
2190 }
2191 if u == nil && !develMode {
2192 w.Header().Set("Cache-Control", "max-age=60")
2193 }
2194 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2195 if err != nil {
2196 elog.Print(err)
2197 }
2198}
2199func serveemu(w http.ResponseWriter, r *http.Request) {
2200 emu := mux.Vars(r)["emu"]
2201
2202 w.Header().Set("Cache-Control", "max-age="+somedays())
2203 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2204}
2205func servememe(w http.ResponseWriter, r *http.Request) {
2206 meme := mux.Vars(r)["meme"]
2207
2208 w.Header().Set("Cache-Control", "max-age="+somedays())
2209 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2210}
2211
2212func servefile(w http.ResponseWriter, r *http.Request) {
2213 xid := mux.Vars(r)["xid"]
2214 var media string
2215 var data []byte
2216 row := stmtGetFileData.QueryRow(xid)
2217 err := row.Scan(&media, &data)
2218 if err != nil {
2219 elog.Printf("error loading file: %s", err)
2220 http.NotFound(w, r)
2221 return
2222 }
2223 w.Header().Set("Content-Type", media)
2224 w.Header().Set("X-Content-Type-Options", "nosniff")
2225 w.Header().Set("Cache-Control", "max-age="+somedays())
2226 w.Write(data)
2227}
2228
2229func nomoroboto(w http.ResponseWriter, r *http.Request) {
2230 io.WriteString(w, "User-agent: *\n")
2231 io.WriteString(w, "Disallow: /a\n")
2232 io.WriteString(w, "Disallow: /d/\n")
2233 io.WriteString(w, "Disallow: /meme/\n")
2234 io.WriteString(w, "Disallow: /o\n")
2235 io.WriteString(w, "Disallow: /o/\n")
2236 io.WriteString(w, "Disallow: /help/\n")
2237 for _, u := range allusers() {
2238 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2239 }
2240}
2241
2242type Hydration struct {
2243 Tophid int64
2244 Srvmsg template.HTML
2245 Honks string
2246 MeCount int64
2247 ChatCount int64
2248}
2249
2250func webhydra(w http.ResponseWriter, r *http.Request) {
2251 u := login.GetUserInfo(r)
2252 userid := u.UserID
2253 templinfo := getInfo(r)
2254 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2255 page := r.FormValue("page")
2256
2257 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2258
2259 var hydra Hydration
2260
2261 var honks []*Honk
2262 switch page {
2263 case "atme":
2264 honks = gethonksforme(userid, wanted)
2265 honks = osmosis(honks, userid, false)
2266 menewnone(userid)
2267 hydra.Srvmsg = "at me!"
2268 case "longago":
2269 honks = gethonksfromlongago(userid, wanted)
2270 honks = osmosis(honks, userid, false)
2271 hydra.Srvmsg = "from long ago"
2272 case "home":
2273 honks = gethonksforuser(userid, wanted)
2274 honks = osmosis(honks, userid, true)
2275 hydra.Srvmsg = serverMsg
2276 case "first":
2277 honks = gethonksforuserfirstclass(userid, wanted)
2278 honks = osmosis(honks, userid, true)
2279 hydra.Srvmsg = "first class only"
2280 case "saved":
2281 honks = getsavedhonks(userid, wanted)
2282 templinfo["PageName"] = "saved"
2283 hydra.Srvmsg = "saved honks"
2284 case "combo":
2285 c := r.FormValue("c")
2286 honks = gethonksbycombo(userid, c, wanted)
2287 honks = osmosis(honks, userid, false)
2288 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2289 case "convoy":
2290 c := r.FormValue("c")
2291 honks = gethonksbyconvoy(userid, c, wanted)
2292 honks = osmosis(honks, userid, false)
2293 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2294 case "honker":
2295 xid := r.FormValue("xid")
2296 honks = gethonksbyxonker(userid, xid, wanted)
2297 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2298 <input type="hidden" name="CSRF" value="%s">
2299 <input type="hidden" name="url" value="%s">
2300 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2301 </form>`, login.GetCSRF("submithonker", r), xid)
2302 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2303 hydra.Srvmsg = msg
2304 case "user":
2305 uname := r.FormValue("uname")
2306 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2307 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2308 default:
2309 http.NotFound(w, r)
2310 }
2311
2312 if len(honks) > 0 {
2313 hydra.Tophid = honks[0].ID
2314 } else {
2315 hydra.Tophid = wanted
2316 }
2317 reverbolate(userid, honks)
2318
2319 user, _ := butwhatabout(u.Username)
2320
2321 var buf strings.Builder
2322 templinfo["Honks"] = honks
2323 templinfo["MapLink"] = getmaplink(u)
2324 templinfo["User"], _ = butwhatabout(u.Username)
2325 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2326 if err != nil {
2327 elog.Printf("frag error: %s", err)
2328 return
2329 }
2330 hydra.Honks = buf.String()
2331 hydra.MeCount = user.Options.MeCount
2332 hydra.ChatCount = user.Options.ChatCount
2333 w.Header().Set("Content-Type", "application/json")
2334 j, _ := jsonify(&hydra)
2335 io.WriteString(w, j)
2336}
2337
2338var honkline = make(chan bool)
2339
2340func honkhonkline() {
2341 for {
2342 select {
2343 case honkline <- true:
2344 default:
2345 return
2346 }
2347 }
2348}
2349
2350func apihandler(w http.ResponseWriter, r *http.Request) {
2351 u := login.GetUserInfo(r)
2352 userid := u.UserID
2353 action := r.FormValue("action")
2354 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2355 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2356 switch action {
2357 case "honk":
2358 h := submithonk(w, r)
2359 if h == nil {
2360 return
2361 }
2362 fmt.Fprintf(w, "%s", h.XID)
2363 case "donk":
2364 d, err := submitdonk(w, r)
2365 if err != nil {
2366 http.Error(w, err.Error(), http.StatusBadRequest)
2367 return
2368 }
2369 if d == nil {
2370 http.Error(w, "missing donk", http.StatusBadRequest)
2371 return
2372 }
2373 w.Write([]byte(d.XID))
2374 case "zonkit":
2375 zonkit(w, r)
2376 case "gethonks":
2377 var honks []*Honk
2378 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2379 page := r.FormValue("page")
2380 var waitchan <-chan time.Time
2381 requery:
2382 switch page {
2383 case "atme":
2384 honks = gethonksforme(userid, wanted)
2385 honks = osmosis(honks, userid, false)
2386 menewnone(userid)
2387 case "longago":
2388 honks = gethonksfromlongago(userid, wanted)
2389 honks = osmosis(honks, userid, false)
2390 case "home":
2391 honks = gethonksforuser(userid, wanted)
2392 honks = osmosis(honks, userid, true)
2393 case "myhonks":
2394 honks = gethonksbyuser(u.Username, true, wanted)
2395 honks = osmosis(honks, userid, true)
2396 default:
2397 http.Error(w, "unknown page", http.StatusNotFound)
2398 return
2399 }
2400 if len(honks) == 0 && wait > 0 {
2401 if waitchan == nil {
2402 waitchan = time.After(time.Duration(wait) * time.Second)
2403 }
2404 select {
2405 case <-honkline:
2406 goto requery
2407 case <-waitchan:
2408 }
2409 }
2410 reverbolate(userid, honks)
2411 j := junk.New()
2412 j["honks"] = honks
2413 j.Write(w)
2414 case "sendactivity":
2415 user, _ := butwhatabout(u.Username)
2416 public := r.FormValue("public") == "1"
2417 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2418 msg := []byte(r.FormValue("msg"))
2419 for rcpt := range rcpts {
2420 go deliverate(0, userid, rcpt, msg, true)
2421 }
2422 case "gethonkers":
2423 j := junk.New()
2424 j["honkers"] = gethonkers(u.UserID)
2425 j.Write(w)
2426 case "savehonker":
2427 h := submithonker(w, r)
2428 if h == nil {
2429 return
2430 }
2431 fmt.Fprintf(w, "%d", h.ID)
2432 default:
2433 http.Error(w, "unknown action", http.StatusNotFound)
2434 return
2435 }
2436}
2437
2438var endoftheworld = make(chan bool)
2439var readyalready = make(chan bool)
2440var workinprogress = 0
2441
2442func enditall() {
2443 sig := make(chan os.Signal)
2444 signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2445 <-sig
2446 ilog.Printf("stopping...")
2447 for i := 0; i < workinprogress; i++ {
2448 endoftheworld <- true
2449 }
2450 ilog.Printf("waiting...")
2451 for i := 0; i < workinprogress; i++ {
2452 <-readyalready
2453 }
2454 ilog.Printf("apocalypse")
2455 os.Exit(0)
2456}
2457
2458var preservehooks []func()
2459
2460func bgmonitor() {
2461 for {
2462 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2463 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2464 if err != nil {
2465 elog.Printf("error deleting old xonkers: %s", err)
2466 }
2467 zaggies.Flush()
2468 time.Sleep(50 * time.Minute)
2469 }
2470}
2471
2472func addcspheaders(next http.Handler) http.Handler {
2473 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2474 w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'; report-uri /csp-violation")
2475 next.ServeHTTP(w, r)
2476 })
2477}
2478
2479func emuinit() {
2480 var emunames []string
2481 dir, err := os.Open(dataDir + "/emus")
2482 if err == nil {
2483 emunames, _ = dir.Readdirnames(0)
2484 dir.Close()
2485 }
2486 for _, e := range emunames {
2487 if len(e) <= 4 {
2488 continue
2489 }
2490 ext := e[len(e)-4:]
2491 emu := Emu{
2492 ID: fmt.Sprintf("/emu/%s", e),
2493 Name: e[:len(e)-4],
2494 Type: "image/" + ext[1:],
2495 }
2496 allemus = append(allemus, emu)
2497 }
2498 sort.Slice(allemus, func(i, j int) bool {
2499 return allemus[i].Name < allemus[j].Name
2500 })
2501}
2502
2503func serve() {
2504 db := opendatabase()
2505 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2506
2507 listener, err := openListener()
2508 if err != nil {
2509 elog.Fatal(err)
2510 }
2511 runBackendServer()
2512 go enditall()
2513 go redeliverator()
2514 go tracker()
2515 go bgmonitor()
2516 loadLingo()
2517 emuinit()
2518
2519 readviews = templates.Load(develMode,
2520 viewDir+"/views/honkpage.html",
2521 viewDir+"/views/honkfrags.html",
2522 viewDir+"/views/honkers.html",
2523 viewDir+"/views/chatter.html",
2524 viewDir+"/views/hfcs.html",
2525 viewDir+"/views/combos.html",
2526 viewDir+"/views/honkform.html",
2527 viewDir+"/views/honk.html",
2528 viewDir+"/views/account.html",
2529 viewDir+"/views/about.html",
2530 viewDir+"/views/funzone.html",
2531 viewDir+"/views/login.html",
2532 viewDir+"/views/xzone.html",
2533 viewDir+"/views/msg.html",
2534 viewDir+"/views/header.html",
2535 viewDir+"/views/onts.html",
2536 viewDir+"/views/emus.html",
2537 viewDir+"/views/honkpage.js",
2538 )
2539 if !develMode {
2540 assets := []string{
2541 viewDir + "/views/style.css",
2542 dataDir + "/views/local.css",
2543 viewDir + "/views/honkpage.js",
2544 dataDir + "/views/local.js",
2545 }
2546 for _, s := range assets {
2547 savedassetparams[s] = getassetparam(s)
2548 }
2549 loadAvatarColors()
2550 }
2551
2552 for _, h := range preservehooks {
2553 h()
2554 }
2555
2556 mux := mux.NewRouter()
2557 mux.Use(addcspheaders)
2558 mux.Use(login.Checker)
2559
2560 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2561
2562 posters := mux.Methods("POST").Subrouter()
2563 getters := mux.Methods("GET").Subrouter()
2564
2565 getters.HandleFunc("/", homepage)
2566 getters.HandleFunc("/home", homepage)
2567 getters.HandleFunc("/front", homepage)
2568 getters.HandleFunc("/events", homepage)
2569 getters.HandleFunc("/robots.txt", nomoroboto)
2570 getters.HandleFunc("/rss", showrss)
2571 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2572 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2573 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2574 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2575 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2576 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2577 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2578 getters.HandleFunc("/a", avatate)
2579 getters.HandleFunc("/o", thelistingoftheontologies)
2580 getters.HandleFunc("/o/{name:.+}", showontology)
2581 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2582 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2583 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2584 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2585
2586 getters.HandleFunc("/flag/{code:.+}", showflag)
2587
2588 getters.HandleFunc("/server", serveractor)
2589 posters.HandleFunc("/server/inbox", serverinbox)
2590 posters.HandleFunc("/inbox", serverinbox)
2591
2592 getters.HandleFunc("/style.css", serveviewasset)
2593 getters.HandleFunc("/honkpage.js", serveviewasset)
2594 getters.HandleFunc("/misc.js", serveviewasset)
2595 getters.HandleFunc("/local.css", servedataasset)
2596 getters.HandleFunc("/local.js", servedataasset)
2597 getters.HandleFunc("/icon.png", servedataasset)
2598 getters.HandleFunc("/favicon.ico", servedataasset)
2599
2600 getters.HandleFunc("/about", servehtml)
2601 getters.HandleFunc("/login", servehtml)
2602 posters.HandleFunc("/dologin", login.LoginFunc)
2603 getters.HandleFunc("/logout", login.LogoutFunc)
2604 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2605
2606 loggedin := mux.NewRoute().Subrouter()
2607 loggedin.Use(login.Required)
2608 loggedin.HandleFunc("/first", homepage)
2609 loggedin.HandleFunc("/chatter", showchatter)
2610 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2611 loggedin.HandleFunc("/saved", homepage)
2612 loggedin.HandleFunc("/account", accountpage)
2613 loggedin.HandleFunc("/funzone", showfunzone)
2614 loggedin.HandleFunc("/chpass", dochpass)
2615 loggedin.HandleFunc("/atme", homepage)
2616 loggedin.HandleFunc("/longago", homepage)
2617 loggedin.HandleFunc("/hfcs", hfcspage)
2618 loggedin.HandleFunc("/xzone", xzone)
2619 loggedin.HandleFunc("/newhonk", newhonkpage)
2620 loggedin.HandleFunc("/edit", edithonkpage)
2621 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2622 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2623 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2624 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2625 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2626 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2627 loggedin.HandleFunc("/honkers", showhonkers)
2628 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2629 loggedin.HandleFunc("/h", showhonker)
2630 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2631 loggedin.HandleFunc("/c", showcombos)
2632 loggedin.HandleFunc("/t", showconvoy)
2633 loggedin.HandleFunc("/q", showsearch)
2634 loggedin.HandleFunc("/hydra", webhydra)
2635 loggedin.HandleFunc("/emus", showemus)
2636 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2637
2638 err = http.Serve(listener, mux)
2639 if err != nil {
2640 elog.Fatal(err)
2641 }
2642}