setting.go 16 KB

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