setting.go 15 KB

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