all repos — flounder @ 4bd0c00ffa82f67b619dd88c894107c0cfbd5d20

A small site builder for the Gemini protocol

main.go (view raw)

  1package main
  2
  3import (
  4	"crypto/rand"
  5	"database/sql"
  6	"flag"
  7	"fmt"
  8	"github.com/gorilla/sessions"
  9	"io"
 10	"io/ioutil"
 11	"log"
 12	mathrand "math/rand"
 13	"mime"
 14	"os"
 15	"path"
 16	"path/filepath"
 17	"sort"
 18	"strings"
 19	"sync"
 20	"time"
 21)
 22
 23var c Config // global var to hold static configuration
 24
 25type File struct { // also folders
 26	Creator     string
 27	Name        string // includes folder
 28	UpdatedTime time.Time
 29	TimeAgo     string
 30	IsText      bool
 31	Children    []*File
 32	Host        string
 33}
 34
 35type User struct {
 36	Username  string
 37	Email     string
 38	Active    bool
 39	Admin     bool
 40	CreatedAt int // timestamp
 41}
 42
 43// returns in a random order
 44func getActiveUserNames() ([]string, error) {
 45	rows, err := DB.Query(`SELECT username from user WHERE active is true`)
 46	if err != nil {
 47		return nil, err
 48	}
 49	var users []string
 50	for rows.Next() {
 51		var user string
 52		err = rows.Scan(&user)
 53		if err != nil {
 54			return nil, err
 55		}
 56		users = append(users, user)
 57	}
 58
 59	dest := make([]string, len(users))
 60	perm := mathrand.Perm(len(users))
 61	for i, v := range perm {
 62		dest[v] = users[i]
 63	}
 64	return dest, nil
 65}
 66
 67func getUsers() ([]User, error) {
 68	rows, err := DB.Query(`SELECT username, email, active, admin, created_at from user ORDER BY created_at DESC`)
 69	if err != nil {
 70		return nil, err
 71	}
 72	var users []User
 73	for rows.Next() {
 74		var user User
 75		err = rows.Scan(&user.Username, &user.Email, &user.Active, &user.Admin, &user.CreatedAt)
 76		if err != nil {
 77			return nil, err
 78		}
 79		users = append(users, user)
 80	}
 81	return users, nil
 82}
 83
 84// get the user-reltaive local path from the filespath
 85// NOTE -- dont use on unsafe input ( I think )
 86func getLocalPath(filesPath string) string {
 87	l := len(strings.Split(c.FilesDirectory, "/"))
 88	return strings.Join(strings.Split(filesPath, "/")[l+1:], "/")
 89}
 90
 91func getCreator(filePath string) string {
 92	l := len(strings.Split(c.FilesDirectory, "/"))
 93	r := strings.Split(filePath, "/")[l]
 94	return r
 95}
 96
 97func getIndexFiles() ([]*File, error) { // cache this function
 98	result := []*File{}
 99	err := filepath.Walk(c.FilesDirectory, func(thepath string, info os.FileInfo, err error) error {
100		if err != nil {
101			log.Printf("Failure accessing a path %q: %v\n", thepath, err)
102			return err // think about
103		}
104		// make this do what it should
105		if !info.IsDir() {
106			creatorFolder := getCreator(thepath)
107			updatedTime := info.ModTime()
108			result = append(result, &File{
109				Name:        getLocalPath(thepath),
110				Creator:     path.Base(creatorFolder),
111				UpdatedTime: updatedTime,
112				TimeAgo:     timeago(&updatedTime),
113			})
114		}
115		return nil
116	})
117	if err != nil {
118		return nil, err
119	}
120	sort.Slice(result, func(i, j int) bool {
121		return result[i].UpdatedTime.After(result[j].UpdatedTime)
122	})
123	if len(result) > 50 {
124		result = result[:50]
125	}
126	return result, nil
127} // todo clean up paths
128
129func getMyFilesRecursive(p string, creator string) ([]*File, error) {
130	result := []*File{}
131	files, err := ioutil.ReadDir(p)
132	if err != nil {
133		return nil, err
134	}
135	for _, file := range files {
136		isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(file.Name())), "text")
137		fullPath := path.Join(p, file.Name())
138		localPath := getLocalPath(fullPath)
139		f := &File{
140			Name:        localPath,
141			Creator:     creator,
142			UpdatedTime: file.ModTime(),
143			IsText:      isText,
144			Host:        c.Host,
145		}
146		if file.IsDir() {
147			f.Children, err = getMyFilesRecursive(path.Join(p, file.Name()), creator)
148		}
149		result = append(result, f)
150	}
151	return result, nil
152}
153
154func createTablesIfDNE() {
155	_, err := DB.Exec(`CREATE TABLE IF NOT EXISTS user (
156  id INTEGER PRIMARY KEY NOT NULL,
157  username TEXT NOT NULL UNIQUE,
158  email TEXT NOT NULL UNIQUE,
159  password_hash TEXT NOT NULL,
160  active boolean NOT NULL DEFAULT false,
161  admin boolean NOT NULL DEFAULT false,
162  created_at INTEGER DEFAULT (strftime('%s', 'now'))
163);
164
165CREATE TABLE IF NOT EXISTS cookie_key (
166  value TEXT NOT NULL
167);`)
168	if err != nil {
169		log.Fatal(err)
170	}
171}
172
173// Generate a cryptographically secure key for the cookie store
174func generateCookieKeyIfDNE() []byte {
175	rows, err := DB.Query("SELECT value FROM cookie_key LIMIT 1")
176	defer rows.Close()
177	if err != nil {
178		log.Fatal(err)
179	}
180	if rows.Next() {
181		var cookie []byte
182		err := rows.Scan(&cookie)
183		if err != nil {
184			log.Fatal(err)
185		}
186		return cookie
187	} else {
188		k := make([]byte, 32)
189		_, err := io.ReadFull(rand.Reader, k)
190		if err != nil {
191			log.Fatal(err)
192		}
193		_, err = DB.Exec("insert into cookie_key values ($1)", k)
194		if err != nil {
195			log.Fatal(err)
196		}
197		return k
198	}
199}
200
201func main() {
202	configPath := flag.String("c", "flounder.toml", "path to config file") // doesnt work atm
203	flag.Parse()
204	args := flag.Args()
205	if len(args) < 1 {
206		fmt.Println("expected 'admin' or 'serve' subcommand")
207		os.Exit(1)
208	}
209
210	var err error
211	c, err = getConfig(*configPath)
212	if err != nil {
213		log.Fatal(err)
214	}
215	logFile, err := os.OpenFile(c.LogFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
216	if err != nil {
217		panic(err)
218	}
219	mw := io.MultiWriter(os.Stdout, logFile)
220	log.SetOutput(mw)
221
222	if c.HttpsEnabled {
223		_, err1 := os.Stat(c.TLSCertFile)
224		_, err2 := os.Stat(c.TLSKeyFile)
225		if os.IsNotExist(err1) || os.IsNotExist(err2) {
226			log.Fatal("Keyfile or certfile does not exist.")
227		}
228	}
229
230	// Generate session cookie key if does not exist
231	DB, err = sql.Open("sqlite3", c.DBFile)
232	if err != nil {
233		log.Fatal(err)
234	}
235
236	createTablesIfDNE()
237	cookie := generateCookieKeyIfDNE()
238	SessionStore = sessions.NewCookieStore(cookie)
239
240	switch args[0] {
241	case "serve":
242		wg := new(sync.WaitGroup)
243		wg.Add(2)
244		go func() {
245			runHTTPServer()
246			wg.Done()
247		}()
248		go func() {
249			runGeminiServer()
250			wg.Done()
251		}()
252		wg.Wait()
253	case "admin":
254		runAdminCommand()
255	}
256}