setting.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package setting
  5. import (
  6. "fmt"
  7. "net/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/macaron-contrib/oauth2"
  17. "github.com/macaron-contrib/session"
  18. "gopkg.in/ini.v1"
  19. "github.com/gogits/gogs/modules/bindata"
  20. "github.com/gogits/gogs/modules/log"
  21. // "github.com/gogits/gogs/modules/ssh"
  22. )
  23. type Scheme string
  24. const (
  25. HTTP Scheme = "http"
  26. HTTPS Scheme = "https"
  27. FCGI Scheme = "fcgi"
  28. )
  29. type LandingPage string
  30. const (
  31. LANDING_PAGE_HOME LandingPage = "/"
  32. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  33. )
  34. var (
  35. // App settings.
  36. AppVer string
  37. AppName string
  38. AppUrl string
  39. AppSubUrl string
  40. // Server settings.
  41. Protocol Scheme
  42. Domain string
  43. HttpAddr, HttpPort string
  44. DisableSSH bool
  45. SSHPort int
  46. SSHDomain string
  47. OfflineMode bool
  48. DisableRouterLog bool
  49. CertFile, KeyFile string
  50. StaticRootPath string
  51. EnableGzip bool
  52. LandingPageUrl LandingPage
  53. // Security settings.
  54. InstallLock bool
  55. SecretKey string
  56. LogInRememberDays int
  57. CookieUserName string
  58. CookieRememberName string
  59. ReverseProxyAuthUser string
  60. // Database settings.
  61. UseSQLite3 bool
  62. UseMySQL bool
  63. UsePostgreSQL bool
  64. // Webhook settings.
  65. Webhook struct {
  66. TaskInterval int
  67. DeliverTimeout int
  68. SkipTLSVerify bool
  69. }
  70. // Repository settings.
  71. RepoRootPath string
  72. ScriptType string
  73. IssuePagingNum int = 10
  74. // Picture settings.
  75. PictureService string
  76. AvatarUploadPath string
  77. GravatarSource string
  78. DisableGravatar bool
  79. // Log settings.
  80. LogRootPath string
  81. LogModes []string
  82. LogConfigs []string
  83. // Attachment settings.
  84. AttachmentPath string
  85. AttachmentAllowedTypes string
  86. AttachmentMaxSize int64
  87. AttachmentMaxFiles int
  88. AttachmentEnabled bool
  89. // Time settings.
  90. TimeFormat string
  91. // Cache settings.
  92. CacheAdapter string
  93. CacheInternal int
  94. CacheConn string
  95. EnableRedis bool
  96. EnableMemcache bool
  97. // Session settings.
  98. SessionConfig session.Options
  99. // Git settings.
  100. Git struct {
  101. MaxGitDiffLines int
  102. GcArgs []string `delim:" "`
  103. Fsck struct {
  104. Enable bool
  105. Interval int
  106. Args []string `delim:" "`
  107. } `ini:"git.fsck"`
  108. }
  109. // I18n settings.
  110. Langs, Names []string
  111. // Other settings.
  112. ShowFooterBranding bool
  113. // Global setting objects.
  114. Cfg *ini.File
  115. CustomPath string // Custom directory path.
  116. CustomConf string
  117. ProdMode bool
  118. RunUser string
  119. IsWindows bool
  120. HasRobotsTxt bool
  121. )
  122. func init() {
  123. IsWindows = runtime.GOOS == "windows"
  124. log.NewLogger(0, "console", `{"level": 0}`)
  125. }
  126. func ExecPath() (string, error) {
  127. file, err := exec.LookPath(os.Args[0])
  128. if err != nil {
  129. return "", err
  130. }
  131. p, err := filepath.Abs(file)
  132. if err != nil {
  133. return "", err
  134. }
  135. return p, nil
  136. }
  137. // WorkDir returns absolute path of work directory.
  138. func WorkDir() (string, error) {
  139. execPath, err := ExecPath()
  140. return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
  141. }
  142. func forcePathSeparator(path string) {
  143. if strings.Contains(path, "\\") {
  144. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  145. }
  146. }
  147. // NewConfigContext initializes configuration context.
  148. // NOTE: do not print any log except error.
  149. func NewConfigContext() {
  150. workDir, err := WorkDir()
  151. if err != nil {
  152. log.Fatal(4, "Fail to get work directory: %v", err)
  153. }
  154. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  155. if err != nil {
  156. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  157. }
  158. CustomPath = os.Getenv("GOGS_CUSTOM")
  159. if len(CustomPath) == 0 {
  160. CustomPath = path.Join(workDir, "custom")
  161. }
  162. if len(CustomConf) == 0 {
  163. CustomConf = path.Join(CustomPath, "conf/app.ini")
  164. }
  165. if com.IsFile(CustomConf) {
  166. if err = Cfg.Append(CustomConf); err != nil {
  167. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  168. }
  169. } else {
  170. log.Warn("Custom config (%s) not found, ignore this if you're running first time", CustomConf)
  171. }
  172. Cfg.NameMapper = ini.AllCapsUnderscore
  173. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  174. forcePathSeparator(LogRootPath)
  175. sec := Cfg.Section("server")
  176. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  177. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  178. if AppUrl[len(AppUrl)-1] != '/' {
  179. AppUrl += "/"
  180. }
  181. // Check if has app suburl.
  182. url, err := url.Parse(AppUrl)
  183. if err != nil {
  184. log.Fatal(4, "Invalid ROOT_URL(%s): %s", AppUrl, err)
  185. }
  186. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  187. Protocol = HTTP
  188. if sec.Key("PROTOCOL").String() == "https" {
  189. Protocol = HTTPS
  190. CertFile = sec.Key("CERT_FILE").String()
  191. KeyFile = sec.Key("KEY_FILE").String()
  192. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  193. Protocol = FCGI
  194. }
  195. Domain = sec.Key("DOMAIN").MustString("localhost")
  196. HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  197. HttpPort = sec.Key("HTTP_PORT").MustString("3000")
  198. DisableSSH = sec.Key("DISABLE_SSH").MustBool()
  199. SSHDomain = sec.Key("SSH_DOMAIN").MustString(Domain)
  200. SSHPort = sec.Key("SSH_PORT").MustInt(22)
  201. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  202. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  203. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  204. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  205. switch sec.Key("LANDING_PAGE").MustString("home") {
  206. case "explore":
  207. LandingPageUrl = LANDING_PAGE_EXPLORE
  208. default:
  209. LandingPageUrl = LANDING_PAGE_HOME
  210. }
  211. sec = Cfg.Section("security")
  212. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  213. SecretKey = sec.Key("SECRET_KEY").String()
  214. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  215. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  216. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  217. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  218. sec = Cfg.Section("attachment")
  219. AttachmentPath = sec.Key("PATH").MustString("data/attachments")
  220. if !filepath.IsAbs(AttachmentPath) {
  221. AttachmentPath = path.Join(workDir, AttachmentPath)
  222. }
  223. AttachmentAllowedTypes = sec.Key("ALLOWED_TYPES").MustString("image/jpeg|image/png")
  224. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(32)
  225. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(10)
  226. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  227. TimeFormat = map[string]string{
  228. "ANSIC": time.ANSIC,
  229. "UnixDate": time.UnixDate,
  230. "RubyDate": time.RubyDate,
  231. "RFC822": time.RFC822,
  232. "RFC822Z": time.RFC822Z,
  233. "RFC850": time.RFC850,
  234. "RFC1123": time.RFC1123,
  235. "RFC1123Z": time.RFC1123Z,
  236. "RFC3339": time.RFC3339,
  237. "RFC3339Nano": time.RFC3339Nano,
  238. "Kitchen": time.Kitchen,
  239. "Stamp": time.Stamp,
  240. "StampMilli": time.StampMilli,
  241. "StampMicro": time.StampMicro,
  242. "StampNano": time.StampNano,
  243. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  244. RunUser = Cfg.Section("").Key("RUN_USER").String()
  245. curUser := os.Getenv("USER")
  246. if len(curUser) == 0 {
  247. curUser = os.Getenv("USERNAME")
  248. }
  249. // Does not check run user when the install lock is off.
  250. if InstallLock && RunUser != curUser {
  251. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  252. }
  253. // Determine and create root git repository path.
  254. homeDir, err := com.HomeDir()
  255. if err != nil {
  256. log.Fatal(4, "Fail to get home directory: %v", err)
  257. }
  258. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  259. sec = Cfg.Section("repository")
  260. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  261. forcePathSeparator(RepoRootPath)
  262. if !filepath.IsAbs(RepoRootPath) {
  263. RepoRootPath = path.Join(workDir, RepoRootPath)
  264. } else {
  265. RepoRootPath = path.Clean(RepoRootPath)
  266. }
  267. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  268. sec = Cfg.Section("picture")
  269. PictureService = sec.Key("SERVICE").In("server", []string{"server"})
  270. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars")
  271. forcePathSeparator(AvatarUploadPath)
  272. if !filepath.IsAbs(AvatarUploadPath) {
  273. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  274. }
  275. switch sec.Key("GRAVATAR_SOURCE").MustString("gravatar") {
  276. case "duoshuo":
  277. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  278. default:
  279. GravatarSource = "//1.gravatar.com/avatar/"
  280. }
  281. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  282. if OfflineMode {
  283. DisableGravatar = true
  284. }
  285. if err = Cfg.Section("git").MapTo(&Git); err != nil {
  286. log.Fatal(4, "Fail to map Git settings: %v", err)
  287. }
  288. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  289. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  290. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  291. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  292. }
  293. var Service struct {
  294. ActiveCodeLives int
  295. ResetPwdCodeLives int
  296. RegisterEmailConfirm bool
  297. DisableRegistration bool
  298. ShowRegistrationButton bool
  299. RequireSignInView bool
  300. EnableCacheAvatar bool
  301. EnableNotifyMail bool
  302. EnableReverseProxyAuth bool
  303. EnableReverseProxyAutoRegister bool
  304. DisableMinimumKeySizeCheck bool
  305. }
  306. func newService() {
  307. sec := Cfg.Section("service")
  308. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  309. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  310. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  311. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  312. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  313. Service.EnableCacheAvatar = sec.Key("ENABLE_CACHE_AVATAR").MustBool()
  314. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  315. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  316. Service.DisableMinimumKeySizeCheck = sec.Key("DISABLE_MINIMUM_KEY_SIZE_CHECK").MustBool()
  317. }
  318. var logLevels = map[string]string{
  319. "Trace": "0",
  320. "Debug": "1",
  321. "Info": "2",
  322. "Warn": "3",
  323. "Error": "4",
  324. "Critical": "5",
  325. }
  326. func newLogService() {
  327. log.Info("%s %s", AppName, AppVer)
  328. // Get and check log mode.
  329. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  330. LogConfigs = make([]string, len(LogModes))
  331. for i, mode := range LogModes {
  332. mode = strings.TrimSpace(mode)
  333. sec, err := Cfg.GetSection("log." + mode)
  334. if err != nil {
  335. log.Fatal(4, "Unknown log mode: %s", mode)
  336. }
  337. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  338. // Log level.
  339. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  340. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  341. validLevels)
  342. level, ok := logLevels[levelName]
  343. if !ok {
  344. log.Fatal(4, "Unknown log level: %s", levelName)
  345. }
  346. // Generate log configuration.
  347. switch mode {
  348. case "console":
  349. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  350. case "file":
  351. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  352. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  353. LogConfigs[i] = fmt.Sprintf(
  354. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  355. logPath,
  356. sec.Key("LOG_ROTATE").MustBool(true),
  357. sec.Key("MAX_LINES").MustInt(1000000),
  358. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  359. sec.Key("DAILY_ROTATE").MustBool(true),
  360. sec.Key("MAX_DAYS").MustInt(7))
  361. case "conn":
  362. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  363. sec.Key("RECONNECT_ON_MSG").MustBool(),
  364. sec.Key("RECONNECT").MustBool(),
  365. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  366. sec.Key("ADDR").MustString(":7020"))
  367. case "smtp":
  368. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  369. sec.Key("USER").MustString("example@example.com"),
  370. sec.Key("PASSWD").MustString("******"),
  371. sec.Key("HOST").MustString("127.0.0.1:25"),
  372. sec.Key("RECEIVERS").MustString("[]"),
  373. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  374. case "database":
  375. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  376. sec.Key("DRIVER").String(),
  377. sec.Key("CONN").String())
  378. }
  379. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  380. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  381. }
  382. }
  383. func newCacheService() {
  384. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  385. if EnableRedis {
  386. log.Info("Redis Enabled")
  387. }
  388. if EnableMemcache {
  389. log.Info("Memcache Enabled")
  390. }
  391. switch CacheAdapter {
  392. case "memory":
  393. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  394. case "redis", "memcache":
  395. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  396. default:
  397. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  398. }
  399. log.Info("Cache Service Enabled")
  400. }
  401. func newSessionService() {
  402. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  403. []string{"memory", "file", "redis", "mysql"})
  404. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  405. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  406. SessionConfig.CookiePath = AppSubUrl
  407. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  408. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  409. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  410. log.Info("Session Service Enabled")
  411. }
  412. // Mailer represents mail service.
  413. type Mailer struct {
  414. Name string
  415. Host string
  416. From string
  417. User, Passwd string
  418. DisableHelo bool
  419. HeloHostname string
  420. SkipVerify bool
  421. UseCertificate bool
  422. CertFile, KeyFile string
  423. }
  424. type OauthInfo struct {
  425. oauth2.Options
  426. AuthUrl, TokenUrl string
  427. }
  428. // Oauther represents oauth service.
  429. type Oauther struct {
  430. GitHub, Google, Tencent,
  431. Twitter, Weibo bool
  432. OauthInfos map[string]*OauthInfo
  433. }
  434. var (
  435. MailService *Mailer
  436. OauthService *Oauther
  437. )
  438. func newMailService() {
  439. sec := Cfg.Section("mailer")
  440. // Check mailer setting.
  441. if !sec.Key("ENABLED").MustBool() {
  442. return
  443. }
  444. MailService = &Mailer{
  445. Name: sec.Key("NAME").MustString(AppName),
  446. Host: sec.Key("HOST").String(),
  447. User: sec.Key("USER").String(),
  448. Passwd: sec.Key("PASSWD").String(),
  449. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  450. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  451. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  452. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  453. CertFile: sec.Key("CERT_FILE").String(),
  454. KeyFile: sec.Key("KEY_FILE").String(),
  455. }
  456. MailService.From = sec.Key("FROM").MustString(MailService.User)
  457. log.Info("Mail Service Enabled")
  458. }
  459. func newRegisterMailService() {
  460. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  461. return
  462. } else if MailService == nil {
  463. log.Warn("Register Mail Service: Mail Service is not enabled")
  464. return
  465. }
  466. Service.RegisterEmailConfirm = true
  467. log.Info("Register Mail Service Enabled")
  468. }
  469. func newNotifyMailService() {
  470. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  471. return
  472. } else if MailService == nil {
  473. log.Warn("Notify Mail Service: Mail Service is not enabled")
  474. return
  475. }
  476. Service.EnableNotifyMail = true
  477. log.Info("Notify Mail Service Enabled")
  478. }
  479. func newWebhookService() {
  480. sec := Cfg.Section("webhook")
  481. Webhook.TaskInterval = sec.Key("TASK_INTERVAL").MustInt(1)
  482. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  483. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  484. }
  485. func NewServices() {
  486. newService()
  487. newLogService()
  488. newCacheService()
  489. newSessionService()
  490. newMailService()
  491. newRegisterMailService()
  492. newNotifyMailService()
  493. newWebhookService()
  494. // ssh.Listen("2222")
  495. }