setting.go 15 KB

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