all repos — flounder @ e53e5ea968f373f93d404acc0c1c90e1a6f52fd9

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:], "/")
 89}
 90
 91func getCreator(filePath string) string {
 92	l := len(strings.Split(c.FilesDirectory, "/"))
 93	return strings.Split(filePath, "/")[l]
 94}
 95
 96func getIndexFiles() ([]*File, error) { // cache this function
 97	result := []*File{}
 98	err := filepath.Walk(c.FilesDirectory, func(thepath string, info os.FileInfo, err error) error {
 99		if err != nil {
100			log.Printf("Failure accessing a path %q: %v\n", thepath, err)
101			return err // think about
102		}
103		// make this do what it should
104		if !info.IsDir() {
105			creatorFolder := getCreator(thepath)
106			updatedTime := info.ModTime()
107			result = append(result, &File{
108				Name:        getLocalPath(thepath),
109				Creator:     path.Base(creatorFolder),
110				UpdatedTime: updatedTime,
111				TimeAgo:     timeago(&updatedTime),
112			})
113		}
114		return nil
115	})
116	if err != nil {
117		return nil, err
118	}
119	sort.Slice(result, func(i, j int) bool {
120		return result[i].UpdatedTime.After(result[j].UpdatedTime)
121	})
122	if len(result) > 50 {
123		result = result[:50]
124	}
125	return result, nil
126} // todo clean up paths
127
128func getMyFilesRecursive(p string, creator string) ([]*File, error) {
129	result := []*File{}
130	files, err := ioutil.ReadDir(p)
131	if err != nil {
132		return nil, err
133	}
134	for _, file := range files {
135		isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(file.Name())), "text")
136		fullPath := path.Join(p, file.Name())
137		localPath := getLocalPath(fullPath)
138		f := &File{
139			Name:        localPath,
140			Creator:     creator,
141			UpdatedTime: file.ModTime(),
142			IsText:      isText,
143			Host:        c.Host,
144		}
145		if file.IsDir() {
146			f.Children, err = getMyFilesRecursive(path.Join(p, file.Name()), creator)
147		}
148		result = append(result, f)
149	}
150	return result, nil
151}
152
153func createTablesIfDNE() {
154	_, err := DB.Exec(`CREATE TABLE IF NOT EXISTS user (
155  id INTEGER PRIMARY KEY NOT NULL,
156  username TEXT NOT NULL UNIQUE,
157  email TEXT NOT NULL UNIQUE,
158  password_hash TEXT NOT NULL,
159  active boolean NOT NULL DEFAULT false,
160  admin boolean NOT NULL DEFAULT false,
161  created_at INTEGER DEFAULT (strftime('%s', 'now'))
162);
163
164CREATE TABLE IF NOT EXISTS cookie_key (
165  value TEXT NOT NULL
166);`)
167	if err != nil {
168		log.Fatal(err)
169	}
170}
171
172// Generate a cryptographically secure key for the cookie store
173func generateCookieKeyIfDNE() []byte {
174	rows, err := DB.Query("SELECT value FROM cookie_key LIMIT 1")
175	defer rows.Close()
176	if err != nil {
177		log.Fatal(err)
178	}
179	if rows.Next() {
180		var cookie []byte
181		err := rows.Scan(&cookie)
182		if err != nil {
183			log.Fatal(err)
184		}
185		return cookie
186	} else {
187		k := make([]byte, 32)
188		_, err := io.ReadFull(rand.Reader, k)
189		if err != nil {
190			log.Fatal(err)
191		}
192		_, err = DB.Exec("insert into cookie_key values ($1)", k)
193		if err != nil {
194			log.Fatal(err)
195		}
196		return k
197	}
198}
199
200func main() {
201	configPath := flag.String("c", "flounder.toml", "path to config file") // doesnt work atm
202	flag.Parse()
203	args := flag.Args()
204	if len(args) < 1 {
205		fmt.Println("expected 'admin' or 'serve' subcommand")
206		os.Exit(1)
207	}
208
209	var err error
210	c, err = getConfig(*configPath)
211	if err != nil {
212		log.Fatal(err)
213	}
214	logFile, err := os.OpenFile(c.LogFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
215	if err != nil {
216		panic(err)
217	}
218	mw := io.MultiWriter(os.Stdout, logFile)
219	log.SetOutput(mw)
220
221	if c.HttpsEnabled {
222		_, err1 := os.Stat(c.TLSCertFile)
223		_, err2 := os.Stat(c.TLSKeyFile)
224		if os.IsNotExist(err1) || os.IsNotExist(err2) {
225			log.Fatal("Keyfile or certfile does not exist.")
226		}
227	}
228
229	// Generate session cookie key if does not exist
230	DB, err = sql.Open("sqlite3", c.DBFile)
231	if err != nil {
232		log.Fatal(err)
233	}
234
235	createTablesIfDNE()
236	cookie := generateCookieKeyIfDNE()
237	SessionStore = sessions.NewCookieStore(cookie)
238
239	switch args[0] {
240	case "serve":
241		wg := new(sync.WaitGroup)
242		wg.Add(2)
243		go func() {
244			runHTTPServer()
245			wg.Done()
246		}()
247		go func() {
248			runGeminiServer()
249			wg.Done()
250		}()
251		wg.Wait()
252	case "admin":
253		runAdminCommand()
254	}
255}