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.
 
 
 
 
 

598 lines
15 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. err := generateKey(emailKeyPath)
  226. if err != nil {
  227. errStatus = 1
  228. }
  229. err = generateKey(cookieAuthKeyPath)
  230. if err != nil {
  231. errStatus = 1
  232. }
  233. err = generateKey(cookieKeyPath)
  234. if err != nil {
  235. errStatus = 1
  236. }
  237. os.Exit(errStatus)
  238. } else if *createSchema {
  239. loadConfig(app)
  240. connectToDatabase(app)
  241. defer shutdown(app)
  242. adminInitDatabase(app)
  243. } else if *createAdmin != "" {
  244. adminCreateUser(app, *createAdmin, true)
  245. } else if *createUser != "" {
  246. adminCreateUser(app, *createUser, false)
  247. } else if *resetPassUser != "" {
  248. // Connect to the database
  249. loadConfig(app)
  250. connectToDatabase(app)
  251. defer shutdown(app)
  252. // Fetch user
  253. u, err := app.db.GetUserForAuth(*resetPassUser)
  254. if err != nil {
  255. log.Error("Get user: %s", err)
  256. os.Exit(1)
  257. }
  258. // Prompt for new password
  259. prompt := promptui.Prompt{
  260. Templates: &promptui.PromptTemplates{
  261. Success: "{{ . | bold | faint }}: ",
  262. },
  263. Label: "New password",
  264. Mask: '*',
  265. }
  266. newPass, err := prompt.Run()
  267. if err != nil {
  268. log.Error("%s", err)
  269. os.Exit(1)
  270. }
  271. // Do the update
  272. log.Info("Updating...")
  273. err = adminResetPassword(app, u, newPass)
  274. if err != nil {
  275. log.Error("%s", err)
  276. os.Exit(1)
  277. }
  278. log.Info("Success.")
  279. os.Exit(0)
  280. } else if *migrate {
  281. loadConfig(app)
  282. connectToDatabase(app)
  283. defer shutdown(app)
  284. err := migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  285. if err != nil {
  286. log.Error("migrate: %s", err)
  287. os.Exit(1)
  288. }
  289. os.Exit(0)
  290. }
  291. log.Info("Initializing...")
  292. loadConfig(app)
  293. hostName = app.cfg.App.Host
  294. isSingleUser = app.cfg.App.SingleUser
  295. app.cfg.Server.Dev = *debugPtr
  296. initTemplates(app.cfg)
  297. // Load keys
  298. log.Info("Loading encryption keys...")
  299. err := initKeys(app)
  300. if err != nil {
  301. log.Error("\n%s\n", err)
  302. }
  303. // Initialize modules
  304. app.sessionStore = initSession(app)
  305. app.formDecoder = schema.NewDecoder()
  306. app.formDecoder.RegisterConverter(converter.NullJSONString{}, converter.ConvertJSONNullString)
  307. app.formDecoder.RegisterConverter(converter.NullJSONBool{}, converter.ConvertJSONNullBool)
  308. app.formDecoder.RegisterConverter(sql.NullString{}, converter.ConvertSQLNullString)
  309. app.formDecoder.RegisterConverter(sql.NullBool{}, converter.ConvertSQLNullBool)
  310. app.formDecoder.RegisterConverter(sql.NullInt64{}, converter.ConvertSQLNullInt64)
  311. app.formDecoder.RegisterConverter(sql.NullFloat64{}, converter.ConvertSQLNullFloat64)
  312. // Check database configuration
  313. if app.cfg.Database.Type == driverMySQL && (app.cfg.Database.User == "" || app.cfg.Database.Password == "") {
  314. log.Error("Database user or password not set.")
  315. os.Exit(1)
  316. }
  317. if app.cfg.Database.Host == "" {
  318. app.cfg.Database.Host = "localhost"
  319. }
  320. if app.cfg.Database.Database == "" {
  321. app.cfg.Database.Database = "writefreely"
  322. }
  323. connectToDatabase(app)
  324. defer shutdown(app)
  325. // Test database connection
  326. err = app.db.Ping()
  327. if err != nil {
  328. log.Error("Database ping failed: %s", err)
  329. }
  330. r := mux.NewRouter()
  331. handler := NewHandler(app)
  332. handler.SetErrorPages(&ErrorPages{
  333. NotFound: pages["404-general.tmpl"],
  334. Gone: pages["410.tmpl"],
  335. InternalServerError: pages["500.tmpl"],
  336. Blank: pages["blank.tmpl"],
  337. })
  338. // Handle app routes
  339. initRoutes(handler, r, app.cfg, app.db)
  340. // Handle local timeline, if enabled
  341. if app.cfg.App.LocalTimeline {
  342. log.Info("Initializing local timeline...")
  343. initLocalTimeline(app)
  344. }
  345. // Handle static files
  346. fs := http.FileServer(http.Dir(filepath.Join(app.cfg.Server.StaticParentDir, staticDir)))
  347. shttp.Handle("/", fs)
  348. r.PathPrefix("/").Handler(fs)
  349. // Handle shutdown
  350. c := make(chan os.Signal, 2)
  351. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  352. go func() {
  353. <-c
  354. log.Info("Shutting down...")
  355. shutdown(app)
  356. log.Info("Done.")
  357. os.Exit(0)
  358. }()
  359. http.Handle("/", r)
  360. // Start web application server
  361. var bindAddress = app.cfg.Server.Bind
  362. if bindAddress == "" {
  363. bindAddress = "localhost"
  364. }
  365. if app.cfg.IsSecureStandalone() {
  366. log.Info("Serving redirects on http://%s:80", bindAddress)
  367. go func() {
  368. err = http.ListenAndServe(
  369. fmt.Sprintf("%s:80", bindAddress), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  370. http.Redirect(w, r, app.cfg.App.Host, http.StatusMovedPermanently)
  371. }))
  372. log.Error("Unable to start redirect server: %v", err)
  373. }()
  374. log.Info("Serving on https://%s:443", bindAddress)
  375. log.Info("---")
  376. err = http.ListenAndServeTLS(
  377. fmt.Sprintf("%s:443", bindAddress), app.cfg.Server.TLSCertPath, app.cfg.Server.TLSKeyPath, nil)
  378. } else {
  379. log.Info("Serving on http://%s:%d\n", bindAddress, app.cfg.Server.Port)
  380. log.Info("---")
  381. err = http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddress, app.cfg.Server.Port), nil)
  382. }
  383. if err != nil {
  384. log.Error("Unable to start: %v", err)
  385. os.Exit(1)
  386. }
  387. }
  388. func loadConfig(app *app) {
  389. log.Info("Loading %s configuration...", app.cfgFile)
  390. cfg, err := config.Load(app.cfgFile)
  391. if err != nil {
  392. log.Error("Unable to load configuration: %v", err)
  393. os.Exit(1)
  394. }
  395. app.cfg = cfg
  396. }
  397. func connectToDatabase(app *app) {
  398. log.Info("Connecting to %s database...", app.cfg.Database.Type)
  399. var db *sql.DB
  400. var err error
  401. if app.cfg.Database.Type == driverMySQL {
  402. 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())))
  403. db.SetMaxOpenConns(50)
  404. } else if app.cfg.Database.Type == driverSQLite {
  405. if !SQLiteEnabled {
  406. log.Error("Invalid database type '%s'. Binary wasn't compiled with SQLite3 support.", app.cfg.Database.Type)
  407. os.Exit(1)
  408. }
  409. if app.cfg.Database.FileName == "" {
  410. log.Error("SQLite database filename value in config.ini is empty.")
  411. os.Exit(1)
  412. }
  413. db, err = sql.Open("sqlite3_with_regex", app.cfg.Database.FileName+"?parseTime=true&cached=shared")
  414. db.SetMaxOpenConns(1)
  415. } else {
  416. log.Error("Invalid database type '%s'. Only 'mysql' and 'sqlite3' are supported right now.", app.cfg.Database.Type)
  417. os.Exit(1)
  418. }
  419. if err != nil {
  420. log.Error("%s", err)
  421. os.Exit(1)
  422. }
  423. app.db = &datastore{db, app.cfg.Database.Type}
  424. }
  425. func shutdown(app *app) {
  426. log.Info("Closing database connection...")
  427. app.db.Close()
  428. }
  429. func adminCreateUser(app *app, credStr string, isAdmin bool) {
  430. // Create an admin user with --create-admin
  431. creds := strings.Split(credStr, ":")
  432. if len(creds) != 2 {
  433. log.Error("usage: writefreely --create-admin username:password")
  434. os.Exit(1)
  435. }
  436. loadConfig(app)
  437. connectToDatabase(app)
  438. defer shutdown(app)
  439. // Ensure an admin / first user doesn't already exist
  440. firstUser, _ := app.db.GetUserByID(1)
  441. if isAdmin {
  442. // Abort if trying to create admin user, but one already exists
  443. if firstUser != nil {
  444. log.Error("Admin user already exists (%s). Create a regular user with: writefreely --create-user", firstUser.Username)
  445. os.Exit(1)
  446. }
  447. } else {
  448. // Abort if trying to create regular user, but no admin exists yet
  449. if firstUser == nil {
  450. log.Error("No admin user exists yet. Create an admin first with: writefreely --create-admin")
  451. os.Exit(1)
  452. }
  453. }
  454. // Create the user
  455. username := creds[0]
  456. password := creds[1]
  457. // Normalize and validate username
  458. desiredUsername := username
  459. username = getSlug(username, "")
  460. usernameDesc := username
  461. if username != desiredUsername {
  462. usernameDesc += " (originally: " + desiredUsername + ")"
  463. }
  464. if !author.IsValidUsername(app.cfg, username) {
  465. log.Error("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, app.cfg.App.MinUsernameLen)
  466. os.Exit(1)
  467. }
  468. // Hash the password
  469. hashedPass, err := auth.HashPass([]byte(password))
  470. if err != nil {
  471. log.Error("Unable to hash password: %v", err)
  472. os.Exit(1)
  473. }
  474. u := &User{
  475. Username: username,
  476. HashedPass: hashedPass,
  477. Created: time.Now().Truncate(time.Second).UTC(),
  478. }
  479. userType := "user"
  480. if isAdmin {
  481. userType = "admin"
  482. }
  483. log.Info("Creating %s %s...", userType, usernameDesc)
  484. err = app.db.CreateUser(u, desiredUsername)
  485. if err != nil {
  486. log.Error("Unable to create user: %s", err)
  487. os.Exit(1)
  488. }
  489. log.Info("Done!")
  490. os.Exit(0)
  491. }
  492. func adminInitDatabase(app *app) {
  493. schemaFileName := "schema.sql"
  494. if app.cfg.Database.Type == driverSQLite {
  495. schemaFileName = "sqlite.sql"
  496. }
  497. schema, err := Asset(schemaFileName)
  498. if err != nil {
  499. log.Error("Unable to load schema file: %v", err)
  500. os.Exit(1)
  501. }
  502. tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`")
  503. queries := strings.Split(string(schema), ";\n")
  504. for _, q := range queries {
  505. if strings.TrimSpace(q) == "" {
  506. continue
  507. }
  508. parts := tblReg.FindStringSubmatch(q)
  509. if len(parts) >= 3 {
  510. log.Info("Creating table %s...", parts[2])
  511. } else {
  512. log.Info("Creating table ??? (Weird query) No match in: %v", parts)
  513. }
  514. _, err = app.db.Exec(q)
  515. if err != nil {
  516. log.Error("%s", err)
  517. } else {
  518. log.Info("Created.")
  519. }
  520. }
  521. os.Exit(0)
  522. }