all repos — flounder @ b74ecaec8871cf7641c243b21a2f006f3c0d1968

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