You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/Unknwon/com"
  14. "github.com/Unknwon/goconfig"
  15. "github.com/macaron-contrib/session"
  16. "github.com/gogits/gogs/modules/log"
  17. // "github.com/gogits/gogs-ng/modules/ssh"
  18. )
  19. type Scheme string
  20. const (
  21. HTTP Scheme = "http"
  22. HTTPS Scheme = "https"
  23. )
  24. var (
  25. // App settings.
  26. AppVer string
  27. AppName string
  28. AppLogo string
  29. AppUrl string
  30. // Server settings.
  31. Protocol Scheme
  32. Domain string
  33. HttpAddr, HttpPort string
  34. SshPort int
  35. OfflineMode bool
  36. DisableRouterLog bool
  37. CertFile, KeyFile string
  38. StaticRootPath string
  39. EnableGzip bool
  40. // Security settings.
  41. InstallLock bool
  42. SecretKey string
  43. LogInRememberDays int
  44. CookieUserName string
  45. CookieRememberName string
  46. ReverseProxyAuthUser string
  47. // Webhook settings.
  48. WebhookTaskInterval int
  49. WebhookDeliverTimeout int
  50. // Repository settings.
  51. RepoRootPath string
  52. ScriptType string
  53. // Picture settings.
  54. PictureService string
  55. DisableGravatar bool
  56. // Log settings.
  57. LogRootPath string
  58. LogModes []string
  59. LogConfigs []string
  60. // Attachment settings.
  61. AttachmentPath string
  62. AttachmentAllowedTypes string
  63. AttachmentMaxSize int64
  64. AttachmentMaxFiles int
  65. AttachmentEnabled bool
  66. // Time settings.
  67. TimeFormat string
  68. // Cache settings.
  69. CacheAdapter string
  70. CacheInternal int
  71. CacheConn string
  72. EnableRedis bool
  73. EnableMemcache bool
  74. // Session settings.
  75. SessionProvider string
  76. SessionConfig *session.Config
  77. // Global setting objects.
  78. Cfg *goconfig.ConfigFile
  79. ConfRootPath string
  80. CustomPath string // Custom directory path.
  81. ProdMode bool
  82. RunUser string
  83. // I18n settings.
  84. Langs, Names []string
  85. )
  86. func init() {
  87. log.NewLogger(0, "console", `{"level": 0}`)
  88. }
  89. func ExecPath() (string, error) {
  90. file, err := exec.LookPath(os.Args[0])
  91. if err != nil {
  92. return "", err
  93. }
  94. p, err := filepath.Abs(file)
  95. if err != nil {
  96. return "", err
  97. }
  98. return p, nil
  99. }
  100. // WorkDir returns absolute path of work directory.
  101. func WorkDir() (string, error) {
  102. execPath, err := ExecPath()
  103. return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
  104. }
  105. // NewConfigContext initializes configuration context.
  106. // NOTE: do not print any log except error.
  107. func NewConfigContext() {
  108. workDir, err := WorkDir()
  109. if err != nil {
  110. log.Fatal(4, "Fail to get work directory: %v", err)
  111. }
  112. ConfRootPath = path.Join(workDir, "conf")
  113. Cfg, err = goconfig.LoadConfigFile(path.Join(workDir, "conf/app.ini"))
  114. if err != nil {
  115. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  116. }
  117. CustomPath = os.Getenv("GOGS_CUSTOM")
  118. if len(CustomPath) == 0 {
  119. CustomPath = path.Join(workDir, "custom")
  120. }
  121. cfgPath := path.Join(CustomPath, "conf/app.ini")
  122. if com.IsFile(cfgPath) {
  123. if err = Cfg.AppendFiles(cfgPath); err != nil {
  124. log.Fatal(4, "Fail to load custom 'conf/app.ini': %v", err)
  125. }
  126. } else {
  127. log.Warn("No custom 'conf/app.ini' found, please go to '/install'")
  128. }
  129. AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
  130. AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
  131. AppUrl = Cfg.MustValue("server", "ROOT_URL", "http://localhost:3000")
  132. Protocol = HTTP
  133. if Cfg.MustValue("server", "PROTOCOL") == "https" {
  134. Protocol = HTTPS
  135. CertFile = Cfg.MustValue("server", "CERT_FILE")
  136. KeyFile = Cfg.MustValue("server", "KEY_FILE")
  137. }
  138. Domain = Cfg.MustValue("server", "DOMAIN", "localhost")
  139. HttpAddr = Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0")
  140. HttpPort = Cfg.MustValue("server", "HTTP_PORT", "3000")
  141. SshPort = Cfg.MustInt("server", "SSH_PORT", 22)
  142. OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE")
  143. DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG")
  144. StaticRootPath = Cfg.MustValue("server", "STATIC_ROOT_PATH", workDir)
  145. LogRootPath = Cfg.MustValue("log", "ROOT_PATH", path.Join(workDir, "log"))
  146. EnableGzip = Cfg.MustBool("server", "ENABLE_GZIP")
  147. InstallLock = Cfg.MustBool("security", "INSTALL_LOCK")
  148. SecretKey = Cfg.MustValue("security", "SECRET_KEY")
  149. LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
  150. CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
  151. CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")
  152. ReverseProxyAuthUser = Cfg.MustValue("security", "REVERSE_PROXY_AUTHENTICATION_USER", "X-WEBAUTH-USER")
  153. AttachmentPath = Cfg.MustValue("attachment", "PATH", "data/attachments")
  154. AttachmentAllowedTypes = Cfg.MustValue("attachment", "ALLOWED_TYPES", "image/jpeg|image/png")
  155. AttachmentMaxSize = Cfg.MustInt64("attachment", "MAX_SIZE", 32)
  156. AttachmentMaxFiles = Cfg.MustInt("attachment", "MAX_FILES", 10)
  157. AttachmentEnabled = Cfg.MustBool("attachment", "ENABLE", true)
  158. TimeFormat = map[string]string{
  159. "ANSIC": time.ANSIC,
  160. "UnixDate": time.UnixDate,
  161. "RubyDate": time.RubyDate,
  162. "RFC822": time.RFC822,
  163. "RFC822Z": time.RFC822Z,
  164. "RFC850": time.RFC850,
  165. "RFC1123": time.RFC1123,
  166. "RFC1123Z": time.RFC1123Z,
  167. "RFC3339": time.RFC3339,
  168. "RFC3339Nano": time.RFC3339Nano,
  169. "Kitchen": time.Kitchen,
  170. "Stamp": time.Stamp,
  171. "StampMilli": time.StampMilli,
  172. "StampMicro": time.StampMicro,
  173. "StampNano": time.StampNano,
  174. }[Cfg.MustValue("time", "FORMAT", "RFC1123")]
  175. if err = os.MkdirAll(AttachmentPath, os.ModePerm); err != nil {
  176. log.Fatal(4, "Could not create directory %s: %s", AttachmentPath, err)
  177. }
  178. RunUser = Cfg.MustValue("", "RUN_USER")
  179. curUser := os.Getenv("USER")
  180. if len(curUser) == 0 {
  181. curUser = os.Getenv("USERNAME")
  182. }
  183. // Does not check run user when the install lock is off.
  184. if InstallLock && RunUser != curUser {
  185. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  186. }
  187. // Determine and create root git reposiroty path.
  188. homeDir, err := com.HomeDir()
  189. if err != nil {
  190. log.Fatal(4, "Fail to get home directory: %v", err)
  191. }
  192. RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
  193. if !filepath.IsAbs(RepoRootPath) {
  194. RepoRootPath = filepath.Join(workDir, RepoRootPath)
  195. } else {
  196. RepoRootPath = filepath.Clean(RepoRootPath)
  197. }
  198. if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
  199. log.Fatal(4, "Fail to create repository root path(%s): %v", RepoRootPath, err)
  200. }
  201. ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
  202. PictureService = Cfg.MustValueRange("picture", "SERVICE", "server",
  203. []string{"server"})
  204. DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR")
  205. Langs = Cfg.MustValueArray("i18n", "LANGS", ",")
  206. Names = Cfg.MustValueArray("i18n", "NAMES", ",")
  207. }
  208. var Service struct {
  209. RegisterEmailConfirm bool
  210. DisableRegistration bool
  211. RequireSignInView bool
  212. EnableCacheAvatar bool
  213. EnableNotifyMail bool
  214. EnableReverseProxyAuth bool
  215. LdapAuth bool
  216. ActiveCodeLives int
  217. ResetPwdCodeLives int
  218. }
  219. func newService() {
  220. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  221. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  222. Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION")
  223. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW")
  224. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR")
  225. Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION")
  226. }
  227. var logLevels = map[string]string{
  228. "Trace": "0",
  229. "Debug": "1",
  230. "Info": "2",
  231. "Warn": "3",
  232. "Error": "4",
  233. "Critical": "5",
  234. }
  235. func newLogService() {
  236. log.Info("%s %s", AppName, AppVer)
  237. // Get and check log mode.
  238. LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
  239. LogConfigs = make([]string, len(LogModes))
  240. for i, mode := range LogModes {
  241. mode = strings.TrimSpace(mode)
  242. modeSec := "log." + mode
  243. if _, err := Cfg.GetSection(modeSec); err != nil {
  244. log.Fatal(4, "Unknown log mode: %s", mode)
  245. }
  246. // Log level.
  247. levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace",
  248. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  249. level, ok := logLevels[levelName]
  250. if !ok {
  251. log.Fatal(4, "Unknown log level: %s", levelName)
  252. }
  253. // Generate log configuration.
  254. switch mode {
  255. case "console":
  256. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  257. case "file":
  258. logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log"))
  259. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  260. LogConfigs[i] = fmt.Sprintf(
  261. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  262. logPath,
  263. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  264. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  265. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  266. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  267. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  268. case "conn":
  269. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  270. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
  271. Cfg.MustBool(modeSec, "RECONNECT"),
  272. Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
  273. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  274. case "smtp":
  275. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  276. Cfg.MustValue(modeSec, "USER", "example@example.com"),
  277. Cfg.MustValue(modeSec, "PASSWD", "******"),
  278. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  279. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  280. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  281. case "database":
  282. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  283. Cfg.MustValue(modeSec, "DRIVER"),
  284. Cfg.MustValue(modeSec, "CONN"))
  285. }
  286. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
  287. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  288. }
  289. }
  290. func newCacheService() {
  291. CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"})
  292. if EnableRedis {
  293. log.Info("Redis Enabled")
  294. }
  295. if EnableMemcache {
  296. log.Info("Memcache Enabled")
  297. }
  298. switch CacheAdapter {
  299. case "memory":
  300. CacheInternal = Cfg.MustInt("cache", "INTERVAL", 60)
  301. case "redis", "memcache":
  302. CacheConn = strings.Trim(Cfg.MustValue("cache", "HOST"), "\" ")
  303. default:
  304. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  305. }
  306. log.Info("Cache Service Enabled")
  307. }
  308. func newSessionService() {
  309. SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory",
  310. []string{"memory", "file", "redis", "mysql"})
  311. SessionConfig = new(session.Config)
  312. SessionConfig.ProviderConfig = strings.Trim(Cfg.MustValue("session", "PROVIDER_CONFIG"), "\" ")
  313. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  314. SessionConfig.Secure = Cfg.MustBool("session", "COOKIE_SECURE")
  315. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  316. SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  317. SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  318. SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC",
  319. "sha1", []string{"sha1", "sha256", "md5"})
  320. SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")
  321. if SessionProvider == "file" {
  322. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  323. }
  324. log.Info("Session Service Enabled")
  325. }
  326. // Mailer represents mail service.
  327. type Mailer struct {
  328. Name string
  329. Host string
  330. From string
  331. User, Passwd string
  332. }
  333. type OauthInfo struct {
  334. ClientId, ClientSecret string
  335. Scopes string
  336. AuthUrl, TokenUrl string
  337. }
  338. // Oauther represents oauth service.
  339. type Oauther struct {
  340. GitHub, Google, Tencent,
  341. Twitter, Weibo bool
  342. OauthInfos map[string]*OauthInfo
  343. }
  344. var (
  345. MailService *Mailer
  346. OauthService *Oauther
  347. )
  348. func newMailService() {
  349. // Check mailer setting.
  350. if !Cfg.MustBool("mailer", "ENABLED") {
  351. return
  352. }
  353. MailService = &Mailer{
  354. Name: Cfg.MustValue("mailer", "NAME", AppName),
  355. Host: Cfg.MustValue("mailer", "HOST"),
  356. User: Cfg.MustValue("mailer", "USER"),
  357. Passwd: Cfg.MustValue("mailer", "PASSWD"),
  358. }
  359. MailService.From = Cfg.MustValue("mailer", "FROM", MailService.User)
  360. log.Info("Mail Service Enabled")
  361. }
  362. func newRegisterMailService() {
  363. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  364. return
  365. } else if MailService == nil {
  366. log.Warn("Register Mail Service: Mail Service is not enabled")
  367. return
  368. }
  369. Service.RegisterEmailConfirm = true
  370. log.Info("Register Mail Service Enabled")
  371. }
  372. func newNotifyMailService() {
  373. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  374. return
  375. } else if MailService == nil {
  376. log.Warn("Notify Mail Service: Mail Service is not enabled")
  377. return
  378. }
  379. Service.EnableNotifyMail = true
  380. log.Info("Notify Mail Service Enabled")
  381. }
  382. func newWebhookService() {
  383. WebhookTaskInterval = Cfg.MustInt("webhook", "TASK_INTERVAL", 1)
  384. WebhookDeliverTimeout = Cfg.MustInt("webhook", "DELIVER_TIMEOUT", 5)
  385. }
  386. func NewServices() {
  387. newService()
  388. newLogService()
  389. newCacheService()
  390. newSessionService()
  391. newMailService()
  392. newRegisterMailService()
  393. newNotifyMailService()
  394. newWebhookService()
  395. // ssh.Listen("2022")
  396. }