A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

655 lines
16 KiB

  1. /*
  2. * Copyright © 2018 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "database/sql"
  13. "flag"
  14. "fmt"
  15. "html/template"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "os/signal"
  20. "path/filepath"
  21. "regexp"
  22. "strings"
  23. "syscall"
  24. "time"
  25. _ "github.com/go-sql-driver/mysql"
  26. "github.com/gorilla/mux"
  27. "github.com/gorilla/schema"
  28. "github.com/gorilla/sessions"
  29. "github.com/manifoldco/promptui"
  30. "github.com/writeas/go-strip-markdown"
  31. "github.com/writeas/web-core/auth"
  32. "github.com/writeas/web-core/converter"
  33. "github.com/writeas/web-core/log"
  34. "github.com/writeas/writefreely/author"
  35. "github.com/writeas/writefreely/config"
  36. "github.com/writeas/writefreely/migrations"
  37. "github.com/writeas/writefreely/page"
  38. )
  39. const (
  40. staticDir = "static"
  41. assumedTitleLen = 80
  42. postsPerPage = 10
  43. serverSoftware = "WriteFreely"
  44. softwareURL = "https://writefreely.org"
  45. )
  46. var (
  47. debugging bool
  48. // Software version can be set from git env using -ldflags
  49. softwareVer = "0.9.0"
  50. // DEPRECATED VARS
  51. // TODO: pass app.cfg into GetCollection* calls so we can get these values
  52. // from Collection methods and we no longer need these.
  53. hostName string
  54. isSingleUser bool
  55. )
  56. type app struct {
  57. router *mux.Router
  58. db *datastore
  59. cfg *config.Config
  60. cfgFile string
  61. keys *keychain
  62. sessionStore *sessions.CookieStore
  63. formDecoder *schema.Decoder
  64. timeline *localTimeline
  65. }
  66. // handleViewHome shows page at root path. Will be the Pad if logged in and the
  67. // catch-all landing page otherwise.
  68. func handleViewHome(app *app, w http.ResponseWriter, r *http.Request) error {
  69. if app.cfg.App.SingleUser {
  70. // Render blog index
  71. return handleViewCollection(app, w, r)
  72. }
  73. // Multi-user instance
  74. u := getUserSession(app, r)
  75. if u != nil {
  76. // User is logged in, so show the Pad
  77. return handleViewPad(app, w, r)
  78. }
  79. p := struct {
  80. page.StaticPage
  81. Flashes []template.HTML
  82. }{
  83. StaticPage: pageForReq(app, r),
  84. }
  85. // Get error messages
  86. session, err := app.sessionStore.Get(r, cookieName)
  87. if err != nil {
  88. // Ignore this
  89. log.Error("Unable to get session in handleViewHome; ignoring: %v", err)
  90. }
  91. flashes, _ := getSessionFlashes(app, w, r, session)
  92. for _, flash := range flashes {
  93. p.Flashes = append(p.Flashes, template.HTML(flash))
  94. }
  95. // Show landing page
  96. return renderPage(w, "landing.tmpl", p)
  97. }
  98. func handleTemplatedPage(app *app, w http.ResponseWriter, r *http.Request, t *template.Template) error {
  99. p := struct {
  100. page.StaticPage
  101. ContentTitle string
  102. Content template.HTML
  103. PlainContent string
  104. Updated string
  105. AboutStats *InstanceStats
  106. }{
  107. StaticPage: pageForReq(app, r),
  108. }
  109. if r.URL.Path == "/about" || r.URL.Path == "/privacy" {
  110. var c *instanceContent
  111. var err error
  112. if r.URL.Path == "/about" {
  113. c, err = getAboutPage(app)
  114. // Fetch stats
  115. p.AboutStats = &InstanceStats{}
  116. p.AboutStats.NumPosts, _ = app.db.GetTotalPosts()
  117. p.AboutStats.NumBlogs, _ = app.db.GetTotalCollections()
  118. } else {
  119. c, err = getPrivacyPage(app)
  120. }
  121. if err != nil {
  122. return err
  123. }
  124. p.ContentTitle = c.Title.String
  125. p.Content = template.HTML(applyMarkdown([]byte(c.Content), ""))
  126. p.PlainContent = shortPostDescription(stripmd.Strip(c.Content))
  127. if !c.Updated.IsZero() {
  128. p.Updated = c.Updated.Format("January 2, 2006")
  129. }
  130. }
  131. // Serve templated page
  132. err := t.ExecuteTemplate(w, "base", p)
  133. if err != nil {
  134. log.Error("Unable to render page: %v", err)
  135. }
  136. return nil
  137. }
  138. func pageForReq(app *app, r *http.Request) page.StaticPage {
  139. p := page.StaticPage{
  140. AppCfg: app.cfg.App,
  141. Path: r.URL.Path,
  142. Version: "v" + softwareVer,
  143. }
  144. // Add user information, if given
  145. var u *User
  146. accessToken := r.FormValue("t")
  147. if accessToken != "" {
  148. userID := app.db.GetUserID(accessToken)
  149. if userID != -1 {
  150. var err error
  151. u, err = app.db.GetUserByID(userID)
  152. if err == nil {
  153. p.Username = u.Username
  154. }
  155. }
  156. } else {
  157. u = getUserSession(app, r)
  158. if u != nil {
  159. p.Username = u.Username
  160. }
  161. }
  162. return p
  163. }
  164. var shttp = http.NewServeMux()
  165. var fileRegex = regexp.MustCompile("/([^/]*\\.[^/]*)$")
  166. func Serve() {
  167. // General options usable with other commands
  168. debugPtr := flag.Bool("debug", false, "Enables debug logging.")
  169. configFile := flag.String("c", "config.ini", "The configuration file to use")
  170. // Setup actions
  171. createConfig := flag.Bool("create-config", false, "Creates a basic configuration and exits")
  172. doConfig := flag.Bool("config", false, "Run the configuration process")
  173. genKeys := flag.Bool("gen-keys", false, "Generate encryption and authentication keys")
  174. createSchema := flag.Bool("init-db", false, "Initialize app database")
  175. migrate := flag.Bool("migrate", false, "Migrate the database")
  176. // Admin actions
  177. createAdmin := flag.String("create-admin", "", "Create an admin with the given username:password")
  178. createUser := flag.String("create-user", "", "Create a regular user with the given username:password")
  179. resetPassUser := flag.String("reset-pass", "", "Reset the given user's password")
  180. outputVersion := flag.Bool("v", false, "Output the current version")
  181. flag.Parse()
  182. debugging = *debugPtr
  183. app := &app{
  184. cfgFile: *configFile,
  185. }
  186. if *outputVersion {
  187. fmt.Println(serverSoftware + " " + softwareVer)
  188. os.Exit(0)
  189. } else if *createConfig {
  190. log.Info("Creating configuration...")
  191. c := config.New()
  192. log.Info("Saving configuration %s...", app.cfgFile)
  193. err := config.Save(c, app.cfgFile)
  194. if err != nil {
  195. log.Error("Unable to save configuration: %v", err)
  196. os.Exit(1)
  197. }
  198. os.Exit(0)
  199. } else if *doConfig {
  200. d, err := config.Configure(app.cfgFile)
  201. if err != nil {
  202. log.Error("Unable to configure: %v", err)
  203. os.Exit(1)
  204. }
  205. if d.User != nil {
  206. app.cfg = d.Config
  207. connectToDatabase(app)
  208. defer shutdown(app)
  209. if !app.db.DatabaseInitialized() {
  210. err = adminInitDatabase(app)
  211. if err != nil {
  212. log.Error(err.Error())
  213. os.Exit(1)
  214. }
  215. }
  216. u := &User{
  217. Username: d.User.Username,
  218. HashedPass: d.User.HashedPass,
  219. Created: time.Now().Truncate(time.Second).UTC(),
  220. }
  221. // Create blog
  222. log.Info("Creating user %s...\n", u.Username)
  223. err = app.db.CreateUser(u, app.cfg.App.SiteName)
  224. if err != nil {
  225. log.Error("Unable to create user: %s", err)
  226. os.Exit(1)
  227. }
  228. log.Info("Done!")
  229. }
  230. os.Exit(0)
  231. } else if *genKeys {
  232. errStatus := 0
  233. // Read keys path from config
  234. loadConfig(app)
  235. // Create keys dir if it doesn't exist yet
  236. fullKeysDir := filepath.Join(app.cfg.Server.KeysParentDir, keysDir)
  237. if _, err := os.Stat(fullKeysDir); os.IsNotExist(err) {
  238. err = os.Mkdir(fullKeysDir, 0700)
  239. if err != nil {
  240. log.Error("%s", err)
  241. os.Exit(1)
  242. }
  243. }
  244. // Generate keys
  245. initKeyPaths(app)
  246. err := generateKey(emailKeyPath)
  247. if err != nil {
  248. errStatus = 1
  249. }
  250. err = generateKey(cookieAuthKeyPath)
  251. if err != nil {
  252. errStatus = 1
  253. }
  254. err = generateKey(cookieKeyPath)
  255. if err != nil {
  256. errStatus = 1
  257. }
  258. os.Exit(errStatus)
  259. } else if *createSchema {
  260. loadConfig(app)
  261. connectToDatabase(app)
  262. defer shutdown(app)
  263. err := adminInitDatabase(app)
  264. if err != nil {
  265. log.Error(err.Error())
  266. os.Exit(1)
  267. }
  268. os.Exit(0)
  269. } else if *createAdmin != "" {
  270. err := adminCreateUser(app, *createAdmin, true)
  271. if err != nil {
  272. log.Error(err.Error())
  273. os.Exit(1)
  274. }
  275. os.Exit(0)
  276. } else if *createUser != "" {
  277. err := adminCreateUser(app, *createUser, false)
  278. if err != nil {
  279. log.Error(err.Error())
  280. os.Exit(1)
  281. }
  282. os.Exit(0)
  283. } else if *resetPassUser != "" {
  284. // Connect to the database
  285. loadConfig(app)
  286. connectToDatabase(app)
  287. defer shutdown(app)
  288. // Fetch user
  289. u, err := app.db.GetUserForAuth(*resetPassUser)
  290. if err != nil {
  291. log.Error("Get user: %s", err)
  292. os.Exit(1)
  293. }
  294. // Prompt for new password
  295. prompt := promptui.Prompt{
  296. Templates: &promptui.PromptTemplates{
  297. Success: "{{ . | bold | faint }}: ",
  298. },
  299. Label: "New password",
  300. Mask: '*',
  301. }
  302. newPass, err := prompt.Run()
  303. if err != nil {
  304. log.Error("%s", err)
  305. os.Exit(1)
  306. }
  307. // Do the update
  308. log.Info("Updating...")
  309. err = adminResetPassword(app, u, newPass)
  310. if err != nil {
  311. log.Error("%s", err)
  312. os.Exit(1)
  313. }
  314. log.Info("Success.")
  315. os.Exit(0)
  316. } else if *migrate {
  317. loadConfig(app)
  318. connectToDatabase(app)
  319. defer shutdown(app)
  320. err := migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  321. if err != nil {
  322. log.Error("migrate: %s", err)
  323. os.Exit(1)
  324. }
  325. os.Exit(0)
  326. }
  327. log.Info("Initializing...")
  328. loadConfig(app)
  329. hostName = app.cfg.App.Host
  330. isSingleUser = app.cfg.App.SingleUser
  331. app.cfg.Server.Dev = *debugPtr
  332. err := initTemplates(app.cfg)
  333. if err != nil {
  334. log.Error("load templates: %s", err)
  335. os.Exit(1)
  336. }
  337. // Load keys
  338. log.Info("Loading encryption keys...")
  339. initKeyPaths(app)
  340. err = initKeys(app)
  341. if err != nil {
  342. log.Error("\n%s\n", err)
  343. }
  344. // Initialize modules
  345. app.sessionStore = initSession(app)
  346. app.formDecoder = schema.NewDecoder()
  347. app.formDecoder.RegisterConverter(converter.NullJSONString{}, converter.ConvertJSONNullString)
  348. app.formDecoder.RegisterConverter(converter.NullJSONBool{}, converter.ConvertJSONNullBool)
  349. app.formDecoder.RegisterConverter(sql.NullString{}, converter.ConvertSQLNullString)
  350. app.formDecoder.RegisterConverter(sql.NullBool{}, converter.ConvertSQLNullBool)
  351. app.formDecoder.RegisterConverter(sql.NullInt64{}, converter.ConvertSQLNullInt64)
  352. app.formDecoder.RegisterConverter(sql.NullFloat64{}, converter.ConvertSQLNullFloat64)
  353. // Check database configuration
  354. if app.cfg.Database.Type == driverMySQL && (app.cfg.Database.User == "" || app.cfg.Database.Password == "") {
  355. log.Error("Database user or password not set.")
  356. os.Exit(1)
  357. }
  358. if app.cfg.Database.Host == "" {
  359. app.cfg.Database.Host = "localhost"
  360. }
  361. if app.cfg.Database.Database == "" {
  362. app.cfg.Database.Database = "writefreely"
  363. }
  364. connectToDatabase(app)
  365. defer shutdown(app)
  366. // Test database connection
  367. err = app.db.Ping()
  368. if err != nil {
  369. log.Error("Database ping failed: %s", err)
  370. }
  371. r := mux.NewRouter()
  372. handler := NewHandler(app)
  373. handler.SetErrorPages(&ErrorPages{
  374. NotFound: pages["404-general.tmpl"],
  375. Gone: pages["410.tmpl"],
  376. InternalServerError: pages["500.tmpl"],
  377. Blank: pages["blank.tmpl"],
  378. })
  379. // Handle app routes
  380. initRoutes(handler, r, app.cfg, app.db)
  381. // Handle local timeline, if enabled
  382. if app.cfg.App.LocalTimeline {
  383. log.Info("Initializing local timeline...")
  384. initLocalTimeline(app)
  385. }
  386. // Handle static files
  387. fs := http.FileServer(http.Dir(filepath.Join(app.cfg.Server.StaticParentDir, staticDir)))
  388. shttp.Handle("/", fs)
  389. r.PathPrefix("/").Handler(fs)
  390. // Handle shutdown
  391. c := make(chan os.Signal, 2)
  392. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  393. go func() {
  394. <-c
  395. log.Info("Shutting down...")
  396. shutdown(app)
  397. log.Info("Done.")
  398. os.Exit(0)
  399. }()
  400. http.Handle("/", r)
  401. // Start web application server
  402. var bindAddress = app.cfg.Server.Bind
  403. if bindAddress == "" {
  404. bindAddress = "localhost"
  405. }
  406. if app.cfg.IsSecureStandalone() {
  407. log.Info("Serving redirects on http://%s:80", bindAddress)
  408. go func() {
  409. err = http.ListenAndServe(
  410. fmt.Sprintf("%s:80", bindAddress), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  411. http.Redirect(w, r, app.cfg.App.Host, http.StatusMovedPermanently)
  412. }))
  413. log.Error("Unable to start redirect server: %v", err)
  414. }()
  415. log.Info("Serving on https://%s:443", bindAddress)
  416. log.Info("---")
  417. err = http.ListenAndServeTLS(
  418. fmt.Sprintf("%s:443", bindAddress), app.cfg.Server.TLSCertPath, app.cfg.Server.TLSKeyPath, nil)
  419. } else {
  420. log.Info("Serving on http://%s:%d\n", bindAddress, app.cfg.Server.Port)
  421. log.Info("---")
  422. err = http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddress, app.cfg.Server.Port), nil)
  423. }
  424. if err != nil {
  425. log.Error("Unable to start: %v", err)
  426. os.Exit(1)
  427. }
  428. }
  429. func loadConfig(app *app) {
  430. log.Info("Loading %s configuration...", app.cfgFile)
  431. cfg, err := config.Load(app.cfgFile)
  432. if err != nil {
  433. log.Error("Unable to load configuration: %v", err)
  434. os.Exit(1)
  435. }
  436. app.cfg = cfg
  437. }
  438. func connectToDatabase(app *app) {
  439. log.Info("Connecting to %s database...", app.cfg.Database.Type)
  440. var db *sql.DB
  441. var err error
  442. if app.cfg.Database.Type == driverMySQL {
  443. db, err = sql.Open(app.cfg.Database.Type, fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true&loc=%s", app.cfg.Database.User, app.cfg.Database.Password, app.cfg.Database.Host, app.cfg.Database.Port, app.cfg.Database.Database, url.QueryEscape(time.Local.String())))
  444. db.SetMaxOpenConns(50)
  445. } else if app.cfg.Database.Type == driverSQLite {
  446. if !SQLiteEnabled {
  447. log.Error("Invalid database type '%s'. Binary wasn't compiled with SQLite3 support.", app.cfg.Database.Type)
  448. os.Exit(1)
  449. }
  450. if app.cfg.Database.FileName == "" {
  451. log.Error("SQLite database filename value in config.ini is empty.")
  452. os.Exit(1)
  453. }
  454. db, err = sql.Open("sqlite3_with_regex", app.cfg.Database.FileName+"?parseTime=true&cached=shared")
  455. db.SetMaxOpenConns(1)
  456. } else {
  457. log.Error("Invalid database type '%s'. Only 'mysql' and 'sqlite3' are supported right now.", app.cfg.Database.Type)
  458. os.Exit(1)
  459. }
  460. if err != nil {
  461. log.Error("%s", err)
  462. os.Exit(1)
  463. }
  464. app.db = &datastore{db, app.cfg.Database.Type}
  465. }
  466. func shutdown(app *app) {
  467. log.Info("Closing database connection...")
  468. app.db.Close()
  469. }
  470. func adminCreateUser(app *app, credStr string, isAdmin bool) error {
  471. // Create an admin user with --create-admin
  472. creds := strings.Split(credStr, ":")
  473. if len(creds) != 2 {
  474. c := "user"
  475. if isAdmin {
  476. c = "admin"
  477. }
  478. return fmt.Errorf("usage: writefreely --create-%s username:password", c)
  479. }
  480. loadConfig(app)
  481. connectToDatabase(app)
  482. defer shutdown(app)
  483. // Ensure an admin / first user doesn't already exist
  484. firstUser, _ := app.db.GetUserByID(1)
  485. if isAdmin {
  486. // Abort if trying to create admin user, but one already exists
  487. if firstUser != nil {
  488. return fmt.Errorf("Admin user already exists (%s). Create a regular user with: writefreely --create-user", firstUser.Username)
  489. }
  490. } else {
  491. // Abort if trying to create regular user, but no admin exists yet
  492. if firstUser == nil {
  493. return fmt.Errorf("No admin user exists yet. Create an admin first with: writefreely --create-admin")
  494. }
  495. }
  496. // Create the user
  497. username := creds[0]
  498. password := creds[1]
  499. // Normalize and validate username
  500. desiredUsername := username
  501. username = getSlug(username, "")
  502. usernameDesc := username
  503. if username != desiredUsername {
  504. usernameDesc += " (originally: " + desiredUsername + ")"
  505. }
  506. if !author.IsValidUsername(app.cfg, username) {
  507. return fmt.Errorf("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, app.cfg.App.MinUsernameLen)
  508. }
  509. // Hash the password
  510. hashedPass, err := auth.HashPass([]byte(password))
  511. if err != nil {
  512. return fmt.Errorf("Unable to hash password: %v", err)
  513. }
  514. u := &User{
  515. Username: username,
  516. HashedPass: hashedPass,
  517. Created: time.Now().Truncate(time.Second).UTC(),
  518. }
  519. userType := "user"
  520. if isAdmin {
  521. userType = "admin"
  522. }
  523. log.Info("Creating %s %s...", userType, usernameDesc)
  524. err = app.db.CreateUser(u, desiredUsername)
  525. if err != nil {
  526. return fmt.Errorf("Unable to create user: %s", err)
  527. }
  528. log.Info("Done!")
  529. return nil
  530. }
  531. func adminInitDatabase(app *app) error {
  532. schemaFileName := "schema.sql"
  533. if app.cfg.Database.Type == driverSQLite {
  534. schemaFileName = "sqlite.sql"
  535. }
  536. schema, err := Asset(schemaFileName)
  537. if err != nil {
  538. return fmt.Errorf("Unable to load schema file: %v", err)
  539. }
  540. tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`")
  541. queries := strings.Split(string(schema), ";\n")
  542. for _, q := range queries {
  543. if strings.TrimSpace(q) == "" {
  544. continue
  545. }
  546. parts := tblReg.FindStringSubmatch(q)
  547. if len(parts) >= 3 {
  548. log.Info("Creating table %s...", parts[2])
  549. } else {
  550. log.Info("Creating table ??? (Weird query) No match in: %v", parts)
  551. }
  552. _, err = app.db.Exec(q)
  553. if err != nil {
  554. log.Error("%s", err)
  555. } else {
  556. log.Info("Created.")
  557. }
  558. }
  559. // Set up migrations table
  560. log.Info("Initializing appmigrations table...")
  561. err = migrations.SetInitialMigrations(migrations.NewDatastore(app.db.DB, app.db.driverName))
  562. if err != nil {
  563. return fmt.Errorf("Unable to set initial migrations: %v", err)
  564. }
  565. log.Info("Running migrations...")
  566. err = migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  567. if err != nil {
  568. return fmt.Errorf("migrate: %s", err)
  569. }
  570. log.Info("Done.")
  571. return nil
  572. }