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