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