setting.go 14 KB

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