setting.go 15 KB

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