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.
 
 
 
 
 

628 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.7.1"
  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. Content template.HTML
  102. PlainContent string
  103. Updated string
  104. AboutStats *InstanceStats
  105. }{
  106. StaticPage: pageForReq(app, r),
  107. }
  108. if r.URL.Path == "/about" || r.URL.Path == "/privacy" {
  109. var c string
  110. var updated *time.Time
  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, updated, err = getPrivacyPage(app)
  120. }
  121. if err != nil {
  122. return err
  123. }
  124. p.Content = template.HTML(applyMarkdown([]byte(c)))
  125. p.PlainContent = shortPostDescription(stripmd.Strip(c))
  126. if updated != nil {
  127. p.Updated = updated.Format("January 2, 2006")
  128. }
  129. }
  130. // Serve templated page
  131. err := t.ExecuteTemplate(w, "base", p)
  132. if err != nil {
  133. log.Error("Unable to render page: %v", err)
  134. }
  135. return nil
  136. }
  137. func pageForReq(app *app, r *http.Request) page.StaticPage {
  138. p := page.StaticPage{
  139. AppCfg: app.cfg.App,
  140. Path: r.URL.Path,
  141. Version: "v" + softwareVer,
  142. }
  143. // Add user information, if given
  144. var u *User
  145. accessToken := r.FormValue("t")
  146. if accessToken != "" {
  147. userID := app.db.GetUserID(accessToken)
  148. if userID != -1 {
  149. var err error
  150. u, err = app.db.GetUserByID(userID)
  151. if err == nil {
  152. p.Username = u.Username
  153. }
  154. }
  155. } else {
  156. u = getUserSession(app, r)
  157. if u != nil {
  158. p.Username = u.Username
  159. }
  160. }
  161. return p
  162. }
  163. var shttp = http.NewServeMux()
  164. var fileRegex = regexp.MustCompile("/([^/]*\\.[^/]*)$")
  165. func Serve() {
  166. debugPtr := flag.Bool("debug", false, "Enables debug logging.")
  167. createConfig := flag.Bool("create-config", false, "Creates a basic configuration and exits")
  168. doConfig := flag.Bool("config", false, "Run the configuration process")
  169. genKeys := flag.Bool("gen-keys", false, "Generate encryption and authentication keys")
  170. createSchema := flag.Bool("init-db", false, "Initialize app database")
  171. migrate := flag.Bool("migrate", false, "Migrate the database")
  172. createAdmin := flag.String("create-admin", "", "Create an admin with the given username:password")
  173. createUser := flag.String("create-user", "", "Create a regular user with the given username:password")
  174. resetPassUser := flag.String("reset-pass", "", "Reset the given user's password")
  175. configFile := flag.String("c", "config.ini", "The configuration file to use")
  176. outputVersion := flag.Bool("v", false, "Output the current version")
  177. flag.Parse()
  178. debugging = *debugPtr
  179. app := &app{
  180. cfgFile: *configFile,
  181. }
  182. if *outputVersion {
  183. fmt.Println(serverSoftware + " " + softwareVer)
  184. os.Exit(0)
  185. } else if *createConfig {
  186. log.Info("Creating configuration...")
  187. c := config.New()
  188. log.Info("Saving configuration %s...", app.cfgFile)
  189. err := config.Save(c, app.cfgFile)
  190. if err != nil {
  191. log.Error("Unable to save configuration: %v", err)
  192. os.Exit(1)
  193. }
  194. os.Exit(0)
  195. } else if *doConfig {
  196. d, err := config.Configure(app.cfgFile)
  197. if err != nil {
  198. log.Error("Unable to configure: %v", err)
  199. os.Exit(1)
  200. }
  201. if d.User != nil {
  202. app.cfg = d.Config
  203. connectToDatabase(app)
  204. defer shutdown(app)
  205. if !app.db.DatabaseInitialized() {
  206. adminInitDatabase(app)
  207. }
  208. u := &User{
  209. Username: d.User.Username,
  210. HashedPass: d.User.HashedPass,
  211. Created: time.Now().Truncate(time.Second).UTC(),
  212. }
  213. // Create blog
  214. log.Info("Creating user %s...\n", u.Username)
  215. err = app.db.CreateUser(u, app.cfg.App.SiteName)
  216. if err != nil {
  217. log.Error("Unable to create user: %s", err)
  218. os.Exit(1)
  219. }
  220. log.Info("Done!")
  221. }
  222. os.Exit(0)
  223. } else if *genKeys {
  224. errStatus := 0
  225. // Read keys path from config
  226. loadConfig(app)
  227. // Create keys dir if it doesn't exist yet
  228. fullKeysDir := filepath.Join(app.cfg.Server.KeysParentDir, keysDir)
  229. if _, err := os.Stat(fullKeysDir); os.IsNotExist(err) {
  230. err = os.Mkdir(fullKeysDir, 0700)
  231. if err != nil {
  232. log.Error("%s", err)
  233. os.Exit(1)
  234. }
  235. }
  236. // Generate keys
  237. initKeyPaths(app)
  238. err := generateKey(emailKeyPath)
  239. if err != nil {
  240. errStatus = 1
  241. }
  242. err = generateKey(cookieAuthKeyPath)
  243. if err != nil {
  244. errStatus = 1
  245. }
  246. err = generateKey(cookieKeyPath)
  247. if err != nil {
  248. errStatus = 1
  249. }
  250. os.Exit(errStatus)
  251. } else if *createSchema {
  252. loadConfig(app)
  253. connectToDatabase(app)
  254. defer shutdown(app)
  255. adminInitDatabase(app)
  256. } else if *createAdmin != "" {
  257. adminCreateUser(app, *createAdmin, true)
  258. } else if *createUser != "" {
  259. adminCreateUser(app, *createUser, false)
  260. } else if *resetPassUser != "" {
  261. // Connect to the database
  262. loadConfig(app)
  263. connectToDatabase(app)
  264. defer shutdown(app)
  265. // Fetch user
  266. u, err := app.db.GetUserForAuth(*resetPassUser)
  267. if err != nil {
  268. log.Error("Get user: %s", err)
  269. os.Exit(1)
  270. }
  271. // Prompt for new password
  272. prompt := promptui.Prompt{
  273. Templates: &promptui.PromptTemplates{
  274. Success: "{{ . | bold | faint }}: ",
  275. },
  276. Label: "New password",
  277. Mask: '*',
  278. }
  279. newPass, err := prompt.Run()
  280. if err != nil {
  281. log.Error("%s", err)
  282. os.Exit(1)
  283. }
  284. // Do the update
  285. log.Info("Updating...")
  286. err = adminResetPassword(app, u, newPass)
  287. if err != nil {
  288. log.Error("%s", err)
  289. os.Exit(1)
  290. }
  291. log.Info("Success.")
  292. os.Exit(0)
  293. } else if *migrate {
  294. loadConfig(app)
  295. connectToDatabase(app)
  296. defer shutdown(app)
  297. err := migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  298. if err != nil {
  299. log.Error("migrate: %s", err)
  300. os.Exit(1)
  301. }
  302. os.Exit(0)
  303. }
  304. log.Info("Initializing...")
  305. loadConfig(app)
  306. hostName = app.cfg.App.Host
  307. isSingleUser = app.cfg.App.SingleUser
  308. app.cfg.Server.Dev = *debugPtr
  309. err := initTemplates(app.cfg)
  310. if err != nil {
  311. log.Error("load templates: %s", err)
  312. os.Exit(1)
  313. }
  314. // Load keys
  315. log.Info("Loading encryption keys...")
  316. initKeyPaths(app)
  317. err = initKeys(app)
  318. if err != nil {
  319. log.Error("\n%s\n", err)
  320. }
  321. // Initialize modules
  322. app.sessionStore = initSession(app)
  323. app.formDecoder = schema.NewDecoder()
  324. app.formDecoder.RegisterConverter(converter.NullJSONString{}, converter.ConvertJSONNullString)
  325. app.formDecoder.RegisterConverter(converter.NullJSONBool{}, converter.ConvertJSONNullBool)
  326. app.formDecoder.RegisterConverter(sql.NullString{}, converter.ConvertSQLNullString)
  327. app.formDecoder.RegisterConverter(sql.NullBool{}, converter.ConvertSQLNullBool)
  328. app.formDecoder.RegisterConverter(sql.NullInt64{}, converter.ConvertSQLNullInt64)
  329. app.formDecoder.RegisterConverter(sql.NullFloat64{}, converter.ConvertSQLNullFloat64)
  330. // Check database configuration
  331. if app.cfg.Database.Type == driverMySQL && (app.cfg.Database.User == "" || app.cfg.Database.Password == "") {
  332. log.Error("Database user or password not set.")
  333. os.Exit(1)
  334. }
  335. if app.cfg.Database.Host == "" {
  336. app.cfg.Database.Host = "localhost"
  337. }
  338. if app.cfg.Database.Database == "" {
  339. app.cfg.Database.Database = "writefreely"
  340. }
  341. connectToDatabase(app)
  342. defer shutdown(app)
  343. // Test database connection
  344. err = app.db.Ping()
  345. if err != nil {
  346. log.Error("Database ping failed: %s", err)
  347. }
  348. r := mux.NewRouter()
  349. handler := NewHandler(app)
  350. handler.SetErrorPages(&ErrorPages{
  351. NotFound: pages["404-general.tmpl"],
  352. Gone: pages["410.tmpl"],
  353. InternalServerError: pages["500.tmpl"],
  354. Blank: pages["blank.tmpl"],
  355. })
  356. // Handle app routes
  357. initRoutes(handler, r, app.cfg, app.db)
  358. // Handle local timeline, if enabled
  359. if app.cfg.App.LocalTimeline {
  360. log.Info("Initializing local timeline...")
  361. initLocalTimeline(app)
  362. }
  363. // Handle static files
  364. fs := http.FileServer(http.Dir(filepath.Join(app.cfg.Server.StaticParentDir, staticDir)))
  365. shttp.Handle("/", fs)
  366. r.PathPrefix("/").Handler(fs)
  367. // Handle shutdown
  368. c := make(chan os.Signal, 2)
  369. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  370. go func() {
  371. <-c
  372. log.Info("Shutting down...")
  373. shutdown(app)
  374. log.Info("Done.")
  375. os.Exit(0)
  376. }()
  377. http.Handle("/", r)
  378. // Start web application server
  379. var bindAddress = app.cfg.Server.Bind
  380. if bindAddress == "" {
  381. bindAddress = "localhost"
  382. }
  383. if app.cfg.IsSecureStandalone() {
  384. log.Info("Serving redirects on http://%s:80", bindAddress)
  385. go func() {
  386. err = http.ListenAndServe(
  387. fmt.Sprintf("%s:80", bindAddress), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  388. http.Redirect(w, r, app.cfg.App.Host, http.StatusMovedPermanently)
  389. }))
  390. log.Error("Unable to start redirect server: %v", err)
  391. }()
  392. log.Info("Serving on https://%s:443", bindAddress)
  393. log.Info("---")
  394. err = http.ListenAndServeTLS(
  395. fmt.Sprintf("%s:443", bindAddress), app.cfg.Server.TLSCertPath, app.cfg.Server.TLSKeyPath, nil)
  396. } else {
  397. log.Info("Serving on http://%s:%d\n", bindAddress, app.cfg.Server.Port)
  398. log.Info("---")
  399. err = http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddress, app.cfg.Server.Port), nil)
  400. }
  401. if err != nil {
  402. log.Error("Unable to start: %v", err)
  403. os.Exit(1)
  404. }
  405. }
  406. func loadConfig(app *app) {
  407. log.Info("Loading %s configuration...", app.cfgFile)
  408. cfg, err := config.Load(app.cfgFile)
  409. if err != nil {
  410. log.Error("Unable to load configuration: %v", err)
  411. os.Exit(1)
  412. }
  413. app.cfg = cfg
  414. }
  415. func connectToDatabase(app *app) {
  416. log.Info("Connecting to %s database...", app.cfg.Database.Type)
  417. var db *sql.DB
  418. var err error
  419. if app.cfg.Database.Type == driverMySQL {
  420. 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())))
  421. db.SetMaxOpenConns(50)
  422. } else if app.cfg.Database.Type == driverSQLite {
  423. if !SQLiteEnabled {
  424. log.Error("Invalid database type '%s'. Binary wasn't compiled with SQLite3 support.", app.cfg.Database.Type)
  425. os.Exit(1)
  426. }
  427. if app.cfg.Database.FileName == "" {
  428. log.Error("SQLite database filename value in config.ini is empty.")
  429. os.Exit(1)
  430. }
  431. db, err = sql.Open("sqlite3_with_regex", app.cfg.Database.FileName+"?parseTime=true&cached=shared")
  432. db.SetMaxOpenConns(1)
  433. } else {
  434. log.Error("Invalid database type '%s'. Only 'mysql' and 'sqlite3' are supported right now.", app.cfg.Database.Type)
  435. os.Exit(1)
  436. }
  437. if err != nil {
  438. log.Error("%s", err)
  439. os.Exit(1)
  440. }
  441. app.db = &datastore{db, app.cfg.Database.Type}
  442. }
  443. func shutdown(app *app) {
  444. log.Info("Closing database connection...")
  445. app.db.Close()
  446. }
  447. func adminCreateUser(app *app, credStr string, isAdmin bool) {
  448. // Create an admin user with --create-admin
  449. creds := strings.Split(credStr, ":")
  450. if len(creds) != 2 {
  451. log.Error("usage: writefreely --create-admin username:password")
  452. os.Exit(1)
  453. }
  454. loadConfig(app)
  455. connectToDatabase(app)
  456. defer shutdown(app)
  457. // Ensure an admin / first user doesn't already exist
  458. firstUser, _ := app.db.GetUserByID(1)
  459. if isAdmin {
  460. // Abort if trying to create admin user, but one already exists
  461. if firstUser != nil {
  462. log.Error("Admin user already exists (%s). Create a regular user with: writefreely --create-user", firstUser.Username)
  463. os.Exit(1)
  464. }
  465. } else {
  466. // Abort if trying to create regular user, but no admin exists yet
  467. if firstUser == nil {
  468. log.Error("No admin user exists yet. Create an admin first with: writefreely --create-admin")
  469. os.Exit(1)
  470. }
  471. }
  472. // Create the user
  473. username := creds[0]
  474. password := creds[1]
  475. // Normalize and validate username
  476. desiredUsername := username
  477. username = getSlug(username, "")
  478. usernameDesc := username
  479. if username != desiredUsername {
  480. usernameDesc += " (originally: " + desiredUsername + ")"
  481. }
  482. if !author.IsValidUsername(app.cfg, username) {
  483. log.Error("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, app.cfg.App.MinUsernameLen)
  484. os.Exit(1)
  485. }
  486. // Hash the password
  487. hashedPass, err := auth.HashPass([]byte(password))
  488. if err != nil {
  489. log.Error("Unable to hash password: %v", err)
  490. os.Exit(1)
  491. }
  492. u := &User{
  493. Username: username,
  494. HashedPass: hashedPass,
  495. Created: time.Now().Truncate(time.Second).UTC(),
  496. }
  497. userType := "user"
  498. if isAdmin {
  499. userType = "admin"
  500. }
  501. log.Info("Creating %s %s...", userType, usernameDesc)
  502. err = app.db.CreateUser(u, desiredUsername)
  503. if err != nil {
  504. log.Error("Unable to create user: %s", err)
  505. os.Exit(1)
  506. }
  507. log.Info("Done!")
  508. os.Exit(0)
  509. }
  510. func adminInitDatabase(app *app) {
  511. schemaFileName := "schema.sql"
  512. if app.cfg.Database.Type == driverSQLite {
  513. schemaFileName = "sqlite.sql"
  514. }
  515. schema, err := Asset(schemaFileName)
  516. if err != nil {
  517. log.Error("Unable to load schema file: %v", err)
  518. os.Exit(1)
  519. }
  520. tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`")
  521. queries := strings.Split(string(schema), ";\n")
  522. for _, q := range queries {
  523. if strings.TrimSpace(q) == "" {
  524. continue
  525. }
  526. parts := tblReg.FindStringSubmatch(q)
  527. if len(parts) >= 3 {
  528. log.Info("Creating table %s...", parts[2])
  529. } else {
  530. log.Info("Creating table ??? (Weird query) No match in: %v", parts)
  531. }
  532. _, err = app.db.Exec(q)
  533. if err != nil {
  534. log.Error("%s", err)
  535. } else {
  536. log.Info("Created.")
  537. }
  538. }
  539. // Set up migrations table
  540. log.Info("Updating appmigrations table...")
  541. err = migrations.SetInitialMigrations(migrations.NewDatastore(app.db.DB, app.db.driverName))
  542. if err != nil {
  543. log.Error("Unable to set initial migrations: %v", err)
  544. os.Exit(1)
  545. }
  546. log.Info("Done.")
  547. os.Exit(0)
  548. }