2 SGBlog -- Git-based CGI blogging engine
3 Copyright (C) 2020 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Affero General Public License as
7 published by the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU Affero General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 // Git-based CGI blogging engine
40 "github.com/hjson/hjson-go"
41 "go.cypherpunks.ru/netstring/v2"
42 "golang.org/x/crypto/blake2b"
43 "golang.org/x/tools/blog/atom"
44 "gopkg.in/src-d/go-git.v4"
45 "gopkg.in/src-d/go-git.v4/plumbing"
46 "gopkg.in/src-d/go-git.v4/plumbing/object"
51 WhenFmt = "2006-01-02 15:04:05Z07:00"
52 AtomFeed = "feed.atom"
57 sha1DigestRe = regexp.MustCompilePOSIX("([0-9a-f]{40,40})")
58 defaultLinks = []string{}
60 notesTree *object.Tree
61 commentsTree *object.Tree
63 renderableSchemes = map[string]struct{}{
71 type TableEntry struct {
92 CommentsNotesRef string
96 func makeA(href, text string) string {
97 return `<a href="` + href + `">` + text + `</a>`
100 func etagString(etag hash.Hash) string {
101 return `"` + hex.EncodeToString(etag.Sum(nil)) + `"`
104 func urlParse(what string) *url.URL {
105 if u, err := url.ParseRequestURI(what); err == nil {
106 if _, exists := renderableSchemes[u.Scheme]; exists {
113 func msgSplit(msg string) []string {
114 lines := strings.Split(msg, "\n")
115 lines = lines[:len(lines)-1]
117 lines = []string{lines[0], "", ""}
122 func lineURLize(urlPrefix, line string) string {
123 cols := strings.Split(html.EscapeString(line), " ")
124 for i, col := range cols {
125 if u := urlParse(col); u != nil {
126 cols[i] = makeA(col, col)
129 cols[i] = sha1DigestRe.ReplaceAllString(col, makeA(
130 urlPrefix+"/$1", "$1",
133 return strings.Join(cols, " ")
136 func getNote(tree *object.Tree, what plumbing.Hash) []byte {
140 entry, err := tree.FindEntry(what.String())
144 blob, err := repo.BlobObject(entry.Hash)
148 r, err := blob.Reader()
152 data, err := ioutil.ReadAll(r)
156 return bytes.TrimSuffix(data, []byte{'\n'})
159 func parseComments(data []byte) []string {
160 comments := []string{}
161 nsr := netstring.NewReader(bytes.NewReader(data))
163 if _, err := nsr.Next(); err != nil {
166 if comment, err := ioutil.ReadAll(nsr); err == nil {
167 comments = append(comments, string(comment))
173 func startHeader(etag hash.Hash, gziped bool) string {
175 "Content-Type: text/html; charset=UTF-8",
176 "ETag: " + etagString(etag),
179 lines = append(lines, "Content-Encoding: gzip")
181 lines = append(lines, "")
182 lines = append(lines, "")
183 return strings.Join(lines, "\n")
186 func startHTML(title string, additional []string) string {
187 return fmt.Sprintf(`<html>
189 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
190 <meta name="generator" content="SGBlog %s">
197 strings.Join(append(defaultLinks, additional...), "\n "),
201 func makeErr(err error) {
202 fmt.Print("Content-Type: text/plain; charset=UTF-8\n\n")
207 func checkETag(etag hash.Hash) {
208 ifNoneMatch := os.Getenv("HTTP_IF_NONE_MATCH")
209 if ifNoneMatch != "" && ifNoneMatch == etagString(etag) {
210 fmt.Printf("Status: 304\nETag: %s\n\n", ifNoneMatch)
216 cfgPath := os.Getenv("SGBLOG_CFG")
218 log.Fatalln("SGBLOG_CFG is not set")
220 pathInfo, exists := os.LookupEnv("PATH_INFO")
224 queryValues, err := url.ParseQuery(os.Getenv("QUERY_STRING"))
229 cfgRaw, err := ioutil.ReadFile(cfgPath)
233 var cfgGeneral map[string]interface{}
234 if err = hjson.Unmarshal(cfgRaw, &cfgGeneral); err != nil {
237 cfgRaw, err = json.Marshal(cfgGeneral)
242 if err = json.Unmarshal(cfgRaw, &cfg); err != nil {
246 etagHash, err := blake2b.New256(nil)
250 etagHash.Write([]byte("SGBLOG"))
251 etagHash.Write([]byte(cfg.GitPath))
252 etagHash.Write([]byte(cfg.Branch))
253 etagHash.Write([]byte(cfg.Title))
254 etagHash.Write([]byte(cfg.BaseURL))
255 etagHash.Write([]byte(cfg.URLPrefix))
256 etagHash.Write([]byte(cfg.AtomId))
257 etagHash.Write([]byte(cfg.AtomAuthor))
259 etagHashForWeb := [][]byte{}
261 defaultLinks = append(defaultLinks, `<link rel="stylesheet" type="text/css" href="`+cfg.CSS+`">`)
262 etagHashForWeb = append(etagHashForWeb, []byte(cfg.CSS))
264 if cfg.Webmaster != "" {
265 defaultLinks = append(defaultLinks, `<link rev="made" href="mailto:`+cfg.Webmaster+`">`)
266 etagHashForWeb = append(etagHashForWeb, []byte(cfg.Webmaster))
268 if cfg.AboutURL != "" {
269 etagHashForWeb = append(etagHashForWeb, []byte(cfg.AboutURL))
271 for _, gitURL := range cfg.GitURLs {
272 defaultLinks = append(defaultLinks, `<link rel="vcs-git" href="`+gitURL+`" title="Git repository">`)
273 etagHashForWeb = append(etagHashForWeb, []byte(gitURL))
275 if cfg.CommentsNotesRef != "" {
276 etagHashForWeb = append(etagHashForWeb, []byte(cfg.CommentsNotesRef))
278 if cfg.CommentsEmail != "" {
279 etagHashForWeb = append(etagHashForWeb, []byte(cfg.CommentsEmail))
282 defaultLinks = append(defaultLinks, `<link rel="top" href="`+cfg.URLPrefix+`/" title="top">`)
283 atomURL := cfg.BaseURL + cfg.URLPrefix + "/" + AtomFeed
284 defaultLinks = append(defaultLinks, `<link rel="alternate" title="Atom feed" href="`+atomURL+`" type="application/atom+xml">`)
286 repo, err = git.PlainOpen(cfg.GitPath)
290 head, err := repo.Reference(plumbing.ReferenceName(cfg.Branch), false)
295 if notes, err := repo.Notes(); err == nil {
296 var notesRef *plumbing.Reference
297 var commentsRef *plumbing.Reference
298 notes.ForEach(func(ref *plumbing.Reference) error {
299 switch string(ref.Name()) {
300 case "refs/notes/commits":
302 case cfg.CommentsNotesRef:
308 if commentsCommit, err := repo.CommitObject(notesRef.Hash()); err == nil {
309 notesTree, _ = commentsCommit.Tree()
312 if commentsRef != nil {
313 if commentsCommit, err := repo.CommitObject(commentsRef.Hash()); err == nil {
314 commentsTree, _ = commentsCommit.Tree()
319 var outBuf bytes.Buffer
322 var gzipWriter *gzip.Writer
323 acceptEncoding := os.Getenv("HTTP_ACCEPT_ENCODING")
324 for _, encoding := range strings.Split(acceptEncoding, ", ") {
325 if encoding == "gzip" {
326 gzipWriter = gzip.NewWriter(&outBuf)
333 if offsetRaw, exists := queryValues["offset"]; exists {
334 offset, err = strconv.Atoi(offsetRaw[0])
339 log, err := repo.Log(&git.LogOptions{From: head.Hash()})
344 for i := 0; i < offset; i++ {
345 if _, err = log.Next(); err != nil {
351 entries := make([]TableEntry, 0, PageEntries)
353 for _, data := range etagHashForWeb {
356 etagHash.Write([]byte("INDEX"))
357 for i := 0; i < PageEntries; i++ {
358 commit, err := log.Next()
363 etagHash.Write(commit.Hash[:])
364 commentsRaw := getNote(commentsTree, commit.Hash)
365 etagHash.Write(commentsRaw)
366 entries = append(entries, TableEntry{commit, commentsRaw})
370 var table bytes.Buffer
372 "<table border=1>\n<tr>" +
376 "<th size=\"5%\">L</th>" +
377 "<th size=\"5%\">C</th>" +
378 "<th>Linked to</th></tr>\n")
379 for _, entry := range entries {
381 lines := msgSplit(entry.commit.Message)
382 domains := []string{}
383 for _, line := range lines[2:] {
384 if u := urlParse(line); u == nil {
387 domains = append(domains, makeA(line, u.Host))
390 var commentsValue string
391 if l := len(parseComments(entry.commentsRaw)); l > 0 {
392 commentsValue = strconv.Itoa(l)
394 commentsValue = " "
396 table.WriteString(fmt.Sprintf(
397 "<tr><td>%d</td><td><tt>%s</tt></td>"+
399 "<td>%d</td><td>%s</td>"+
400 "<td>%s</td></tr>\n",
401 commentN, entry.commit.Author.When.Format(WhenFmt),
402 makeA(cfg.URLPrefix+"/"+entry.commit.Hash.String(), lines[0]),
405 strings.Join(domains, " "),
408 table.WriteString("</table>")
412 var refs bytes.Buffer
414 if offsetPrev := offset - PageEntries; offsetPrev > 0 {
415 href = cfg.URLPrefix + "/?offset=" + strconv.Itoa(offsetPrev)
417 href = cfg.URLPrefix + "/"
419 links = append(links, `<link rel="prev" href="`+href+`" title="newer">`)
420 refs.WriteString(makeA(href, " [prev]"))
423 href = cfg.URLPrefix + "/?offset=" + strconv.Itoa(offset+PageEntries)
424 links = append(links, `<link rel="next" href="`+href+`" title="older">`)
425 refs.WriteString(makeA(href, " [next]"))
428 os.Stdout.Write([]byte(startHeader(etagHash, gzipWriter != nil)))
429 out.Write([]byte(startHTML(
430 fmt.Sprintf("%s (%d-%d)", cfg.Title, offset, offset+PageEntries),
433 if cfg.AboutURL != "" {
434 out.Write([]byte(fmt.Sprintf("[%s]", makeA(cfg.AboutURL, "about"))))
436 out.Write(refs.Bytes())
437 out.Write(table.Bytes())
438 out.Write(refs.Bytes())
439 out.Write([]byte("\n"))
440 } else if pathInfo == "/"+AtomFeed {
441 commit, err := repo.CommitObject(head.Hash())
445 etagHash.Write([]byte("ATOM"))
446 etagHash.Write(commit.Hash[:])
451 Updated: atom.Time(commit.Author.When),
456 Author: &atom.Person{Name: cfg.AtomAuthor},
458 log, err := repo.Log(&git.LogOptions{From: head.Hash()})
462 for i := 0; i < PageEntries; i++ {
463 commit, err = log.Next()
468 feedIdRaw := new([16]byte)
469 copy(feedIdRaw[:], commit.Hash[:])
470 feedIdRaw[6] = (feedIdRaw[6] & 0x0F) | uint8(4<<4) // version 4
471 feedId := fmt.Sprintf(
480 lines := msgSplit(commit.Message)
481 feed.Entry = append(feed.Entry, &atom.Entry{
483 ID: "urn:uuid:" + feedId,
486 Href: cfg.BaseURL + cfg.URLPrefix + "/" + commit.Hash.String(),
488 Published: atom.Time(commit.Author.When),
489 Updated: atom.Time(commit.Author.When),
496 Body: strings.Join(lines[2:], "\n"),
500 data, err := xml.MarshalIndent(&feed, "", " ")
505 os.Stdout.WriteString("Content-Type: text/xml; charset=UTF-8\n")
506 os.Stdout.WriteString("ETag: " + etagString(etagHash) + "\n")
507 if gzipWriter != nil {
508 os.Stdout.WriteString("Content-Encoding: gzip\n")
511 os.Stdout.WriteString("\n")
512 os.Stdout.Write(outBuf.Bytes())
514 } else if sha1DigestRe.MatchString(pathInfo[1:]) {
515 commit, err := repo.CommitObject(plumbing.NewHash(pathInfo[1:]))
519 for _, data := range etagHashForWeb {
522 etagHash.Write([]byte("ENTRY"))
523 etagHash.Write(commit.Hash[:])
524 notesRaw := getNote(notesTree, commit.Hash)
525 etagHash.Write(notesRaw)
526 commentsRaw := getNote(commentsTree, commit.Hash)
527 etagHash.Write(commentsRaw)
529 lines := msgSplit(commit.Message)
531 when := commit.Author.When.Format(WhenFmt)
532 os.Stdout.Write([]byte(startHeader(etagHash, gzipWriter != nil)))
535 if len(commit.ParentHashes) > 0 {
536 parent = commit.ParentHashes[0].String()
537 links = append(links, `<link rel="prev" href="`+cfg.URLPrefix+"/"+parent+`" title="older">`)
539 out.Write([]byte(startHTML(fmt.Sprintf("%s (%s)", title, when), links)))
540 if cfg.AboutURL != "" {
541 out.Write([]byte(fmt.Sprintf("[%s] ", makeA(cfg.AboutURL, "about"))))
544 out.Write([]byte(fmt.Sprintf(
546 makeA(cfg.URLPrefix+"/"+parent, "older"),
549 out.Write([]byte(fmt.Sprintf(
550 "[<tt>%s</tt>] [<tt>%s</tt>]<hr/>\n<h2>%s</h2>\n<pre>\n",
551 when, commit.Hash.String(), title,
553 for _, line := range lines[2:] {
554 out.Write([]byte(lineURLize(cfg.URLPrefix, line) + "\n"))
556 out.Write([]byte("</pre>\n<hr/>\n"))
557 if len(notesRaw) > 0 {
558 out.Write([]byte("Note:<pre>\n" + string(notesRaw) + "\n</pre>\n<hr/>\n"))
560 if cfg.CommentsEmail != "" {
561 out.Write([]byte("[" + makeA(
562 "mailto:"+cfg.CommentsEmail+"?subject="+commit.Hash.String(),
566 out.Write([]byte("<dl>\n"))
567 for i, comment := range parseComments(commentsRaw) {
568 out.Write([]byte(fmt.Sprintf(
569 "<dt><a name=\"comment%d\"><a href=\"#comment%d\">comment %d</a>:"+
570 "</dt>\n<dd><pre>\n",
573 lines = strings.Split(comment, "\n")
574 for _, line := range lines[:3] {
575 out.Write([]byte(line + "\n"))
577 for _, line := range lines[3:] {
578 out.Write([]byte(lineURLize(cfg.URLPrefix, line) + "\n"))
580 out.Write([]byte("</pre></dd>\n"))
582 out.Write([]byte("</dl>\n"))
584 makeErr(errors.New("unknown URL action"))
586 out.Write([]byte("</body></html>\n"))
587 if gzipWriter != nil {
590 os.Stdout.Write(outBuf.Bytes())