setting.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. RequireSignInView bool
  269. EnableCacheAvatar bool
  270. EnableNotifyMail bool
  271. EnableReverseProxyAuth bool
  272. EnableReverseProxyAutoRegister bool
  273. ActiveCodeLives int
  274. ResetPwdCodeLives int
  275. }
  276. func newService() {
  277. Service.ActiveCodeLives = Cfg.Section("service").Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  278. Service.ResetPwdCodeLives = Cfg.Section("service").Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  279. Service.DisableRegistration = Cfg.Section("service").Key("DISABLE_REGISTRATION").MustBool()
  280. Service.RequireSignInView = Cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").MustBool()
  281. Service.EnableCacheAvatar = Cfg.Section("service").Key("ENABLE_CACHE_AVATAR").MustBool()
  282. Service.EnableReverseProxyAuth = Cfg.Section("service").Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  283. Service.EnableReverseProxyAutoRegister = Cfg.Section("service").Key("ENABLE_REVERSE_PROXY_AUTO_REGISTERATION").MustBool()
  284. }
  285. var logLevels = map[string]string{
  286. "Trace": "0",
  287. "Debug": "1",
  288. "Info": "2",
  289. "Warn": "3",
  290. "Error": "4",
  291. "Critical": "5",
  292. }
  293. func newLogService() {
  294. log.Info("%s %s", AppName, AppVer)
  295. // Get and check log mode.
  296. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  297. LogConfigs = make([]string, len(LogModes))
  298. for i, mode := range LogModes {
  299. mode = strings.TrimSpace(mode)
  300. sec, err := Cfg.GetSection("log." + mode)
  301. if err != nil {
  302. log.Fatal(4, "Unknown log mode: %s", mode)
  303. }
  304. // Log level.
  305. levelName := Cfg.Section("log."+mode).Key("LEVEL").In("Trace",
  306. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  307. level, ok := logLevels[levelName]
  308. if !ok {
  309. log.Fatal(4, "Unknown log level: %s", levelName)
  310. }
  311. // Generate log configuration.
  312. switch mode {
  313. case "console":
  314. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  315. case "file":
  316. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  317. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  318. LogConfigs[i] = fmt.Sprintf(
  319. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  320. logPath,
  321. sec.Key("LOG_ROTATE").MustBool(true),
  322. sec.Key("MAX_LINES").MustInt(1000000),
  323. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  324. sec.Key("DAILY_ROTATE").MustBool(true),
  325. sec.Key("MAX_DAYS").MustInt(7))
  326. case "conn":
  327. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  328. sec.Key("RECONNECT_ON_MSG").MustBool(),
  329. sec.Key("RECONNECT").MustBool(),
  330. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  331. sec.Key("ADDR").MustString(":7020"))
  332. case "smtp":
  333. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  334. sec.Key("USER").MustString("example@example.com"),
  335. sec.Key("PASSWD").MustString("******"),
  336. sec.Key("HOST").MustString("127.0.0.1:25"),
  337. sec.Key("RECEIVERS").MustString("[]"),
  338. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  339. case "database":
  340. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  341. sec.Key("DRIVER").String(),
  342. sec.Key("CONN").String())
  343. }
  344. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  345. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  346. }
  347. }
  348. func newCacheService() {
  349. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  350. if EnableRedis {
  351. log.Info("Redis Enabled")
  352. }
  353. if EnableMemcache {
  354. log.Info("Memcache Enabled")
  355. }
  356. switch CacheAdapter {
  357. case "memory":
  358. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  359. case "redis", "memcache":
  360. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  361. default:
  362. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  363. }
  364. log.Info("Cache Service Enabled")
  365. }
  366. func newSessionService() {
  367. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  368. []string{"memory", "file", "redis", "mysql"})
  369. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  370. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  371. SessionConfig.CookiePath = AppSubUrl
  372. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  373. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  374. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  375. log.Info("Session Service Enabled")
  376. }
  377. // Mailer represents mail service.
  378. type Mailer struct {
  379. Name string
  380. Host string
  381. From string
  382. User, Passwd string
  383. SkipVerify bool
  384. }
  385. type OauthInfo struct {
  386. oauth2.Options
  387. AuthUrl, TokenUrl string
  388. }
  389. // Oauther represents oauth service.
  390. type Oauther struct {
  391. GitHub, Google, Tencent,
  392. Twitter, Weibo bool
  393. OauthInfos map[string]*OauthInfo
  394. }
  395. var (
  396. MailService *Mailer
  397. OauthService *Oauther
  398. )
  399. func newMailService() {
  400. sec := Cfg.Section("mailer")
  401. // Check mailer setting.
  402. if !sec.Key("ENABLED").MustBool() {
  403. return
  404. }
  405. MailService = &Mailer{
  406. Name: sec.Key("NAME").MustString(AppName),
  407. Host: sec.Key("HOST").String(),
  408. User: sec.Key("USER").String(),
  409. Passwd: sec.Key("PASSWD").String(),
  410. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  411. }
  412. MailService.From = sec.Key("FROM").MustString(MailService.User)
  413. log.Info("Mail Service Enabled")
  414. }
  415. func newRegisterMailService() {
  416. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  417. return
  418. } else if MailService == nil {
  419. log.Warn("Register Mail Service: Mail Service is not enabled")
  420. return
  421. }
  422. Service.RegisterEmailConfirm = true
  423. log.Info("Register Mail Service Enabled")
  424. }
  425. func newNotifyMailService() {
  426. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  427. return
  428. } else if MailService == nil {
  429. log.Warn("Notify Mail Service: Mail Service is not enabled")
  430. return
  431. }
  432. Service.EnableNotifyMail = true
  433. log.Info("Notify Mail Service Enabled")
  434. }
  435. func newWebhookService() {
  436. WebhookTaskInterval = Cfg.Section("webhook").Key("TASK_INTERVAL").MustInt(1)
  437. WebhookDeliverTimeout = Cfg.Section("webhook").Key("DELIVER_TIMEOUT").MustInt(5)
  438. }
  439. func NewServices() {
  440. newService()
  441. newLogService()
  442. newCacheService()
  443. newSessionService()
  444. newMailService()
  445. newRegisterMailService()
  446. newNotifyMailService()
  447. newWebhookService()
  448. // ssh.Listen("2222")
  449. }