setting.go 15 KB

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