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 = sec.Key("PATH").MustString("data/attachments")
  210. if !filepath.IsAbs(AttachmentPath) {
  211. AttachmentPath = path.Join(workDir, AttachmentPath)
  212. }
  213. AttachmentAllowedTypes = sec.Key("ALLOWED_TYPES").MustString("image/jpeg|image/png")
  214. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(32)
  215. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(10)
  216. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  217. TimeFormat = map[string]string{
  218. "ANSIC": time.ANSIC,
  219. "UnixDate": time.UnixDate,
  220. "RubyDate": time.RubyDate,
  221. "RFC822": time.RFC822,
  222. "RFC822Z": time.RFC822Z,
  223. "RFC850": time.RFC850,
  224. "RFC1123": time.RFC1123,
  225. "RFC1123Z": time.RFC1123Z,
  226. "RFC3339": time.RFC3339,
  227. "RFC3339Nano": time.RFC3339Nano,
  228. "Kitchen": time.Kitchen,
  229. "Stamp": time.Stamp,
  230. "StampMilli": time.StampMilli,
  231. "StampMicro": time.StampMicro,
  232. "StampNano": time.StampNano,
  233. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  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. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  256. sec = Cfg.Section("picture")
  257. PictureService = sec.Key("SERVICE").In("server", []string{"server"})
  258. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars")
  259. if !filepath.IsAbs(AvatarUploadPath) {
  260. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  261. }
  262. switch sec.Key("GRAVATAR_SOURCE").MustString("gravatar") {
  263. case "duoshuo":
  264. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  265. default:
  266. GravatarSource = "//1.gravatar.com/avatar/"
  267. }
  268. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  269. if err = Cfg.Section("git").MapTo(&Git); err != nil {
  270. log.Fatal(4, "Fail to map Git settings: %v", err)
  271. }
  272. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  273. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  274. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  275. }
  276. var Service struct {
  277. RegisterEmailConfirm bool
  278. DisableRegistration bool
  279. ShowRegistrationButton bool
  280. RequireSignInView bool
  281. EnableCacheAvatar bool
  282. EnableNotifyMail bool
  283. EnableReverseProxyAuth bool
  284. EnableReverseProxyAutoRegister bool
  285. ActiveCodeLives int
  286. ResetPwdCodeLives int
  287. }
  288. func newService() {
  289. Service.ActiveCodeLives = Cfg.Section("service").Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  290. Service.ResetPwdCodeLives = Cfg.Section("service").Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  291. Service.DisableRegistration = Cfg.Section("service").Key("DISABLE_REGISTRATION").MustBool()
  292. Service.ShowRegistrationButton = Cfg.Section("service").Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  293. Service.RequireSignInView = Cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").MustBool()
  294. Service.EnableCacheAvatar = Cfg.Section("service").Key("ENABLE_CACHE_AVATAR").MustBool()
  295. Service.EnableReverseProxyAuth = Cfg.Section("service").Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  296. Service.EnableReverseProxyAutoRegister = Cfg.Section("service").Key("ENABLE_REVERSE_PROXY_AUTO_REGISTERATION").MustBool()
  297. }
  298. var logLevels = map[string]string{
  299. "Trace": "0",
  300. "Debug": "1",
  301. "Info": "2",
  302. "Warn": "3",
  303. "Error": "4",
  304. "Critical": "5",
  305. }
  306. func newLogService() {
  307. log.Info("%s %s", AppName, AppVer)
  308. // Get and check log mode.
  309. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  310. LogConfigs = make([]string, len(LogModes))
  311. for i, mode := range LogModes {
  312. mode = strings.TrimSpace(mode)
  313. sec, err := Cfg.GetSection("log." + mode)
  314. if err != nil {
  315. log.Fatal(4, "Unknown log mode: %s", mode)
  316. }
  317. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  318. // Log level.
  319. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  320. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  321. validLevels)
  322. level, ok := logLevels[levelName]
  323. if !ok {
  324. log.Fatal(4, "Unknown log level: %s", levelName)
  325. }
  326. // Generate log configuration.
  327. switch mode {
  328. case "console":
  329. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  330. case "file":
  331. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  332. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  333. LogConfigs[i] = fmt.Sprintf(
  334. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  335. logPath,
  336. sec.Key("LOG_ROTATE").MustBool(true),
  337. sec.Key("MAX_LINES").MustInt(1000000),
  338. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  339. sec.Key("DAILY_ROTATE").MustBool(true),
  340. sec.Key("MAX_DAYS").MustInt(7))
  341. case "conn":
  342. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  343. sec.Key("RECONNECT_ON_MSG").MustBool(),
  344. sec.Key("RECONNECT").MustBool(),
  345. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  346. sec.Key("ADDR").MustString(":7020"))
  347. case "smtp":
  348. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  349. sec.Key("USER").MustString("example@example.com"),
  350. sec.Key("PASSWD").MustString("******"),
  351. sec.Key("HOST").MustString("127.0.0.1:25"),
  352. sec.Key("RECEIVERS").MustString("[]"),
  353. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  354. case "database":
  355. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  356. sec.Key("DRIVER").String(),
  357. sec.Key("CONN").String())
  358. }
  359. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  360. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  361. }
  362. }
  363. func newCacheService() {
  364. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  365. if EnableRedis {
  366. log.Info("Redis Enabled")
  367. }
  368. if EnableMemcache {
  369. log.Info("Memcache Enabled")
  370. }
  371. switch CacheAdapter {
  372. case "memory":
  373. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  374. case "redis", "memcache":
  375. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  376. default:
  377. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  378. }
  379. log.Info("Cache Service Enabled")
  380. }
  381. func newSessionService() {
  382. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  383. []string{"memory", "file", "redis", "mysql"})
  384. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  385. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  386. SessionConfig.CookiePath = AppSubUrl
  387. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  388. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  389. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  390. log.Info("Session Service Enabled")
  391. }
  392. // Mailer represents mail service.
  393. type Mailer struct {
  394. Name string
  395. Host string
  396. From string
  397. User, Passwd string
  398. SkipVerify bool
  399. }
  400. type OauthInfo struct {
  401. oauth2.Options
  402. AuthUrl, TokenUrl string
  403. }
  404. // Oauther represents oauth service.
  405. type Oauther struct {
  406. GitHub, Google, Tencent,
  407. Twitter, Weibo bool
  408. OauthInfos map[string]*OauthInfo
  409. }
  410. var (
  411. MailService *Mailer
  412. OauthService *Oauther
  413. )
  414. func newMailService() {
  415. sec := Cfg.Section("mailer")
  416. // Check mailer setting.
  417. if !sec.Key("ENABLED").MustBool() {
  418. return
  419. }
  420. MailService = &Mailer{
  421. Name: sec.Key("NAME").MustString(AppName),
  422. Host: sec.Key("HOST").String(),
  423. User: sec.Key("USER").String(),
  424. Passwd: sec.Key("PASSWD").String(),
  425. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  426. }
  427. MailService.From = sec.Key("FROM").MustString(MailService.User)
  428. log.Info("Mail Service Enabled")
  429. }
  430. func newRegisterMailService() {
  431. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  432. return
  433. } else if MailService == nil {
  434. log.Warn("Register Mail Service: Mail Service is not enabled")
  435. return
  436. }
  437. Service.RegisterEmailConfirm = true
  438. log.Info("Register Mail Service Enabled")
  439. }
  440. func newNotifyMailService() {
  441. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  442. return
  443. } else if MailService == nil {
  444. log.Warn("Notify Mail Service: Mail Service is not enabled")
  445. return
  446. }
  447. Service.EnableNotifyMail = true
  448. log.Info("Notify Mail Service Enabled")
  449. }
  450. func newWebhookService() {
  451. sec := Cfg.Section("webhook")
  452. Webhook.TaskInterval = sec.Key("TASK_INTERVAL").MustInt(1)
  453. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  454. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  455. }
  456. func NewServices() {
  457. newService()
  458. newLogService()
  459. newCacheService()
  460. newSessionService()
  461. newMailService()
  462. newRegisterMailService()
  463. newNotifyMailService()
  464. newWebhookService()
  465. // ssh.Listen("2222")
  466. }