setting.go 15 KB

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