all repos — honk @ 20d0db8381895b0f90be8231e09a5bf2455cdadd

my fork of honk

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