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